// Code generated by modernc.org/undup from the per-target sqlite_*.go files; DO NOT EDIT.

//go:build (freebsd && amd64) || (freebsd && arm64) || (linux && amd64) || (linux && arm64) || (linux && loong64) || (linux && ppc64le) || (linux && riscv64) || (netbsd && amd64) || (openbsd && amd64) || (openbsd && arm64)

package sqlite3

import (
	"unsafe"

	"modernc.org/libc"
)

// C documentation
//
//	/*
//	** This routine redistributes cells on the iParentIdx'th child of pParent
//	** (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
//	** 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.
//	**
//	** 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
//	** if the page is overfull. This routine ensures that all cells allocated
//	** to the page and its siblings fit into MemPage.aData[] before returning.
//	**
//	** In the course of balancing the page and its siblings, cells may be
//	** 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).
//	**
//	** If this routine fails for any reason, it might leave the database
//	** in a corrupted state. So if this routine fails, the database should
//	** be rolled back.
//	**
//	** The third argument to this function, aOvflSpace, is a pointer to a
//	** buffer big enough to hold one page. If while inserting cells into the parent
//	** page (pParent) the parent page becomes overfull, this buffer is
//	** used to store the parent's overflow cells. Because this function inserts
//	** a maximum of four divider cells into the parent page, and the maximum
//	** size of a cell stored within an internal node is always less than 1/4
//	** 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
//	** SQLITE_NOMEM.
//	*/
func _balance_nonroot(tls *libc.TLS, pParent uintptr, iParentIdx int32, aOvflSpace uintptr, isRoot int32, bBulk int32) (r1 int32) {
	bp := tls.Alloc(208)
	defer tls.Free(208)
	var aData, aSpace1, p, pBt, pCell, pCell1, pNew1, pNew2, pOld, pOld1, pOld2, pRight, pSrcEnd, pTemp, pTemp1, piCell, piEnd, v17 uintptr
	var aPgno [5]TPgno
	var apDiv [2]uintptr
	var apNew [5]uintptr
	var cntNew, cntOld [5]int32
	var cntOldNext, d, i, iB, iNew, iNew1, iOff, iOld, iOld1, iOvflSpace, iPg, iSpace1, j, k, leafData, limit, nMaxCells, nNew, nNewCell, nOld, nxDiv, pageFlags, r, sz1, sz2, szD, szLeft, szR, szRight, usableSpace, v1 int32
	var fgA, fgB, leafCorrection, maskPage, sz Tu16
	var key Tu32
	var pgnoA, pgnoB, pgnoTemp TPgno
	var szScratch Tu64
	var v13, v14 bool
	var v18 uint32
	var _ /* abDone at bp+60 */ [5]Tu8
	var _ /* apOld at bp+8 */ [3]uintptr
	var _ /* b at bp+72 */ TCellArray
	var _ /* info at bp+184 */ TCellInfo
	var _ /* pNew at bp+176 */ uintptr
	var _ /* pgno at bp+52 */ TPgno
	var _ /* rc at bp+0 */ int32
	var _ /* szNew at bp+32 */ [5]int32
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = aData, aPgno, aSpace1, apDiv, apNew, cntNew, cntOld, cntOldNext, d, fgA, fgB, i, iB, iNew, iNew1, iOff, iOld, iOld1, iOvflSpace, iPg, iSpace1, j, k, key, leafCorrection, leafData, limit, maskPage, nMaxCells, nNew, nNewCell, nOld, nxDiv, p, pBt, pCell, pCell1, pNew1, pNew2, pOld, pOld1, pOld2, pRight, pSrcEnd, pTemp, pTemp1, pageFlags, pgnoA, pgnoB, pgnoTemp, piCell, piEnd, r, sz, sz1, sz2, szD, szLeft, szR, szRight, szScratch, usableSpace, v1, v13, v14, v17, v18 /* The whole database */
	nMaxCells = 0                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                /* Allocated size of apCell, szCell, aFrom. */
	nNew = 0                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     /* Next divider slot in pParent->aCell[] */
	**(**int32)(__ccgo_up(bp)) = SQLITE_OK                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       /* Value of pPage->aData[0] */
	iSpace1 = 0                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  /* First unused byte of aSpace1[] */
	iOvflSpace = 0                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               /* Parsed information on cells being balanced */
	libc.Xmemset(tls, bp+60, 0, uint64(5))
	libc.Xmemset(tls, bp+72, 0, libc.Uint64FromInt64(104)-libc.Uint64FromInt64(4))
	**(**int32)(__ccgo_up(bp + 72 + 80 + uintptr(libc.Int32FromInt32(NB)*libc.Int32FromInt32(2)-libc.Int32FromInt32(1))*4)) = int32(0x7fffffff)
	pBt = (*TMemPage)(unsafe.Pointer(pParent)).FpBt
	/* At this point pParent may have at most one overflow cell. And if
	 ** 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().
	 */
	if !(aOvflSpace != 0) {
		return int32(SQLITE_NOMEM)
	}
	/* 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.
	 **
	 ** 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
	 ** overflow cells in the parent page, since if any existed they will
	 ** have already been removed.
	 */
	i = libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pParent)).FnOverflow) + libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pParent)).FnCell)
	if i < int32(2) {
		nxDiv = 0
	} else {
		if iParentIdx == 0 {
			nxDiv = 0
		} else {
			if iParentIdx == i {
				nxDiv = i - int32(2) + bBulk
			} else {
				nxDiv = iParentIdx - int32(1)
			}
		}
		i = int32(2) - bBulk
	}
	nOld = i + int32(1)
	if i+nxDiv-libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pParent)).FnOverflow) == libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pParent)).FnCell) {
		pRight = (*TMemPage)(unsafe.Pointer(pParent)).FaData + uintptr(libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pParent)).FhdrOffset)+int32(8))
	} else {
		pRight = (*TMemPage)(unsafe.Pointer(pParent)).FaData + uintptr(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pParent)).FmaskPage)&(libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(pParent)).FaCellIdx + uintptr(int32(2)*(i+nxDiv-libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pParent)).FnOverflow))))))<<libc.Int32FromInt32(8)|libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(pParent)).FaCellIdx + uintptr(int32(2)*(i+nxDiv-libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pParent)).FnOverflow))) + 1)))))
	}
	**(**TPgno)(__ccgo_up(bp + 52)) = _sqlite3Get4byte(tls, pRight)
	for int32(1) != 0 {
		if **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
			**(**int32)(__ccgo_up(bp)) = _getAndInitPage(tls, pBt, **(**TPgno)(__ccgo_up(bp + 52)), bp+8+uintptr(i)*8, 0)
		}
		if **(**int32)(__ccgo_up(bp)) != 0 {
			libc.Xmemset(tls, bp+8, 0, libc.Uint64FromInt32(i+libc.Int32FromInt32(1))*uint64(8))
			goto balance_cleanup
		}
		if (*TMemPage)(unsafe.Pointer((**(**[3]uintptr)(__ccgo_up(bp + 8)))[i])).FnFree < 0 {
			**(**int32)(__ccgo_up(bp)) = _btreeComputeFreeSpace(tls, (**(**[3]uintptr)(__ccgo_up(bp + 8)))[i])
			if **(**int32)(__ccgo_up(bp)) != 0 {
				libc.Xmemset(tls, bp+8, 0, libc.Uint64FromInt32(i)*uint64(8))
				goto balance_cleanup
			}
		}
		nMaxCells = nMaxCells + (libc.Int32FromUint16((*TMemPage)(unsafe.Pointer((**(**[3]uintptr)(__ccgo_up(bp + 8)))[i])).FnCell) + libc.Int32FromUint64(libc.Uint64FromInt64(32)/libc.Uint64FromInt64(8)))
		v1 = i
		i = i - 1
		if v1 == 0 {
			break
		}
		if (*TMemPage)(unsafe.Pointer(pParent)).FnOverflow != 0 && i+nxDiv == libc.Int32FromUint16(**(**Tu16)(__ccgo_up(pParent + 28))) {
			apDiv[i] = **(**uintptr)(__ccgo_up(pParent + 40))
			**(**TPgno)(__ccgo_up(bp + 52)) = _sqlite3Get4byte(tls, apDiv[i])
			(**(**[5]int32)(__ccgo_up(bp + 32)))[i] = libc.Int32FromUint16((*(*func(*libc.TLS, uintptr, uintptr) Tu16)(unsafe.Pointer(&struct{ uintptr }{(*TMemPage)(unsafe.Pointer(pParent)).FxCellSize})))(tls, pParent, apDiv[i]))
			(*TMemPage)(unsafe.Pointer(pParent)).FnOverflow = uint8(0)
		} else {
			apDiv[i] = (*TMemPage)(unsafe.Pointer(pParent)).FaData + uintptr(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pParent)).FmaskPage)&(libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(pParent)).FaCellIdx + uintptr(int32(2)*(i+nxDiv-libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pParent)).FnOverflow))))))<<libc.Int32FromInt32(8)|libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(pParent)).FaCellIdx + uintptr(int32(2)*(i+nxDiv-libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pParent)).FnOverflow))) + 1)))))
			**(**TPgno)(__ccgo_up(bp + 52)) = _sqlite3Get4byte(tls, apDiv[i])
			(**(**[5]int32)(__ccgo_up(bp + 32)))[i] = libc.Int32FromUint16((*(*func(*libc.TLS, uintptr, uintptr) Tu16)(unsafe.Pointer(&struct{ uintptr }{(*TMemPage)(unsafe.Pointer(pParent)).FxCellSize})))(tls, pParent, apDiv[i]))
			/* Drop the cell from the parent page. apDiv[i] still points to
			 ** the cell within the parent, even though it has been dropped.
			 ** 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.
			 **
			 ** But not if we are in secure-delete mode. In secure-delete mode,
			 ** the dropCell() routine will overwrite the entire cell with zeroes.
			 ** In this case, temporarily copy the cell into the aOvflSpace[]
			 ** buffer. It will be copied out again as soon as the aSpace[] buffer
			 ** is allocated.  */
			if libc.Int32FromUint16((*TBtShared)(unsafe.Pointer(pBt)).FbtsFlags)&int32(BTS_FAST_SECURE) != 0 {
				/* If the following if() condition is not true, the db is corrupted.
				 ** The call to dropCell() below will detect this.  */
				iOff = int32(int64(apDiv[i])) - int32(int64((*TMemPage)(unsafe.Pointer(pParent)).FaData))
				if iOff+(**(**[5]int32)(__ccgo_up(bp + 32)))[i] <= libc.Int32FromUint32((*TBtShared)(unsafe.Pointer(pBt)).FusableSize) {
					libc.Xmemcpy(tls, aOvflSpace+uintptr(iOff), apDiv[i], libc.Uint64FromInt32((**(**[5]int32)(__ccgo_up(bp + 32)))[i]))
					apDiv[i] = aOvflSpace + uintptr(int64(apDiv[i])-int64((*TMemPage)(unsafe.Pointer(pParent)).FaData))
				}
			}
			_dropCell(tls, pParent, i+nxDiv-libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pParent)).FnOverflow), (**(**[5]int32)(__ccgo_up(bp + 32)))[i], bp)
		}
	}
	/* Make nMaxCells a multiple of 4 in order to preserve 8-byte
	 ** alignment */
	nMaxCells = (nMaxCells + int32(3)) & ^libc.Int32FromInt32(3)
	/*
	 ** Allocate space for memory structures
	 */
	szScratch = uint64(libc.Uint64FromInt32(nMaxCells)*uint64(8) + libc.Uint64FromInt32(nMaxCells)*uint64(2) + uint64((*TBtShared)(unsafe.Pointer(pBt)).FpageSize)) /* aSpace1 */
	(**(**TCellArray)(__ccgo_up(bp + 72))).FapCell = _sqlite3DbMallocRaw(tls, uintptr(0), szScratch)
	if (**(**TCellArray)(__ccgo_up(bp + 72))).FapCell == uintptr(0) {
		**(**int32)(__ccgo_up(bp)) = int32(SQLITE_NOMEM)
		goto balance_cleanup
	}
	(**(**TCellArray)(__ccgo_up(bp + 72))).FszCell = (**(**TCellArray)(__ccgo_up(bp + 72))).FapCell + uintptr(nMaxCells)*8
	aSpace1 = (**(**TCellArray)(__ccgo_up(bp + 72))).FszCell + uintptr(nMaxCells)*2
	/*
	 ** Load pointers to all cells on sibling pages and the divider cells
	 ** into the local b.apCell[] array.  Make copies of the divider cells
	 ** into space obtained from aSpace1[]. The divider cells have already
	 ** been removed from pParent.
	 **
	 ** If the siblings are on leaf pages, then the child pointers of the
	 ** divider cells are stripped from the cells before they are copied
	 ** into aSpace1[].  In this way, all cells in b.apCell[] are without
	 ** child pointers.  If siblings are not leaves, then all cell in
	 ** b.apCell[] include child pointers.  Either way, all cells in b.apCell[]
	 ** are alike.
	 **
	 ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
	 **       leafData:  1 if pPage holds key+data and pParent holds only keys.
	 */
	(**(**TCellArray)(__ccgo_up(bp + 72))).FpRef = (**(**[3]uintptr)(__ccgo_up(bp + 8)))[0]
	leafCorrection = libc.Uint16FromInt32(libc.Int32FromUint8((*TMemPage)(unsafe.Pointer((**(**TCellArray)(__ccgo_up(bp + 72))).FpRef)).Fleaf) * int32(4))
	leafData = libc.Int32FromUint8((*TMemPage)(unsafe.Pointer((**(**TCellArray)(__ccgo_up(bp + 72))).FpRef)).FintKeyLeaf)
	i = 0
	for {
		if !(i < nOld) {
			break
		}
		pOld = (**(**[3]uintptr)(__ccgo_up(bp + 8)))[i]
		limit = libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pOld)).FnCell)
		aData = (*TMemPage)(unsafe.Pointer(pOld)).FaData
		maskPage = (*TMemPage)(unsafe.Pointer(pOld)).FmaskPage
		piCell = aData + uintptr((*TMemPage)(unsafe.Pointer(pOld)).FcellOffset)
		/* Verify that all sibling pages are of the same "type" (table-leaf,
		 ** table-interior, index-leaf, or index-interior).
		 */
		if libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(pOld)).FaData))) != libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer((**(**[3]uintptr)(__ccgo_up(bp + 8)))[0])).FaData))) {
			**(**int32)(__ccgo_up(bp)) = _sqlite3CorruptError(tls, int32(81575))
			goto balance_cleanup
		}
		/* Load b.apCell[] with pointers to all cells in pOld.  If pOld
		 ** contains overflow cells, include them in the b.apCell[] array
		 ** in the correct spot.
		 **
		 ** Note that when there are multiple overflow cells, it is always the
		 ** case that they are sequential and adjacent.  This invariant arises
		 ** because multiple overflows can only occurs when inserting divider
		 ** cells into a parent on a prior balance, and divider cells are always
		 ** adjacent and are inserted in order.  There is an assert() tagged
		 ** with "NOTE 1" in the overflow cell insertion loop to prove this
		 ** invariant.
		 **
		 ** This must be done in advance.  Once the balance starts, the cell
		 ** offset section of the btree page will be overwritten and we will no
		 ** long be able to find the cells if a pointer to each cell is not saved
		 ** first.
		 */
		libc.Xmemset(tls, (**(**TCellArray)(__ccgo_up(bp + 72))).FszCell+uintptr((**(**TCellArray)(__ccgo_up(bp + 72))).FnCell)*2, 0, uint64(2)*libc.Uint64FromInt32(limit+libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pOld)).FnOverflow)))
		if libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pOld)).FnOverflow) > 0 {
			if limit < libc.Int32FromUint16(**(**Tu16)(__ccgo_up(pOld + 28))) {
				**(**int32)(__ccgo_up(bp)) = _sqlite3CorruptError(tls, int32(81599))
				goto balance_cleanup
			}
			limit = libc.Int32FromUint16(**(**Tu16)(__ccgo_up(pOld + 28)))
			j = 0
			for {
				if !(j < limit) {
					break
				}
				**(**uintptr)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FapCell + uintptr((**(**TCellArray)(__ccgo_up(bp + 72))).FnCell)*8)) = aData + uintptr(libc.Int32FromUint16(maskPage)&(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(piCell)))<<libc.Int32FromInt32(8)|libc.Int32FromUint8(**(**Tu8)(__ccgo_up(piCell + 1)))))
				piCell = piCell + uintptr(2)
				(**(**TCellArray)(__ccgo_up(bp + 72))).FnCell = (**(**TCellArray)(__ccgo_up(bp + 72))).FnCell + 1
				goto _3
			_3:
				;
				j = j + 1
			}
			k = 0
			for {
				if !(k < libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pOld)).FnOverflow)) {
					break
				}
				/* NOTE 1 */
				**(**uintptr)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FapCell + uintptr((**(**TCellArray)(__ccgo_up(bp + 72))).FnCell)*8)) = **(**uintptr)(__ccgo_up(pOld + 40 + uintptr(k)*8))
				(**(**TCellArray)(__ccgo_up(bp + 72))).FnCell = (**(**TCellArray)(__ccgo_up(bp + 72))).FnCell + 1
				goto _4
			_4:
				;
				k = k + 1
			}
		}
		piEnd = aData + uintptr((*TMemPage)(unsafe.Pointer(pOld)).FcellOffset) + uintptr(int32(2)*libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pOld)).FnCell))
		for piCell < piEnd {
			**(**uintptr)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FapCell + uintptr((**(**TCellArray)(__ccgo_up(bp + 72))).FnCell)*8)) = aData + uintptr(libc.Int32FromUint16(maskPage)&(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(piCell)))<<libc.Int32FromInt32(8)|libc.Int32FromUint8(**(**Tu8)(__ccgo_up(piCell + 1)))))
			piCell = piCell + uintptr(2)
			(**(**TCellArray)(__ccgo_up(bp + 72))).FnCell = (**(**TCellArray)(__ccgo_up(bp + 72))).FnCell + 1
		}
		cntOld[i] = (**(**TCellArray)(__ccgo_up(bp + 72))).FnCell
		if i < nOld-int32(1) && !(leafData != 0) {
			sz = libc.Uint16FromInt32((**(**[5]int32)(__ccgo_up(bp + 32)))[i])
			**(**Tu16)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FszCell + uintptr((**(**TCellArray)(__ccgo_up(bp + 72))).FnCell)*2)) = sz
			pTemp = aSpace1 + uintptr(iSpace1)
			iSpace1 = iSpace1 + libc.Int32FromUint16(sz)
			libc.Xmemcpy(tls, pTemp, apDiv[i], uint64(sz))
			**(**uintptr)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FapCell + uintptr((**(**TCellArray)(__ccgo_up(bp + 72))).FnCell)*8)) = pTemp + uintptr(leafCorrection)
			**(**Tu16)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FszCell + uintptr((**(**TCellArray)(__ccgo_up(bp + 72))).FnCell)*2)) = libc.Uint16FromInt32(libc.Int32FromUint16(**(**Tu16)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FszCell + uintptr((**(**TCellArray)(__ccgo_up(bp + 72))).FnCell)*2))) - libc.Int32FromUint16(leafCorrection))
			if !((*TMemPage)(unsafe.Pointer(pOld)).Fleaf != 0) {
				/* The right pointer of the child page pOld becomes the left
				 ** pointer of the divider cell */
				libc.Xmemcpy(tls, **(**uintptr)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FapCell + uintptr((**(**TCellArray)(__ccgo_up(bp + 72))).FnCell)*8)), (*TMemPage)(unsafe.Pointer(pOld)).FaData+8, uint64(4))
			} else {
				for libc.Int32FromUint16(**(**Tu16)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FszCell + uintptr((**(**TCellArray)(__ccgo_up(bp + 72))).FnCell)*2))) < int32(4) {
					/* Do not allow any cells smaller than 4 bytes. If a smaller cell
					 ** does exist, pad it with 0x00 bytes. */
					v1 = iSpace1
					iSpace1 = iSpace1 + 1
					**(**Tu8)(__ccgo_up(aSpace1 + uintptr(v1))) = uint8(0x00)
					**(**Tu16)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FszCell + uintptr((**(**TCellArray)(__ccgo_up(bp + 72))).FnCell)*2)) = **(**Tu16)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FszCell + uintptr((**(**TCellArray)(__ccgo_up(bp + 72))).FnCell)*2)) + 1
				}
			}
			(**(**TCellArray)(__ccgo_up(bp + 72))).FnCell = (**(**TCellArray)(__ccgo_up(bp + 72))).FnCell + 1
		}
		goto _2
	_2:
		;
		i = i + 1
	}
	/*
	 ** 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.
	 ** cntNew[k] should equal b.nCell.
	 **
	 ** Values computed by this block:
	 **
	 **           k: The total number of sibling pages
	 **    szNew[i]: Spaced used on the i-th sibling page.
	 **   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 = libc.Int32FromUint32((*TBtShared)(unsafe.Pointer(pBt)).FusableSize - uint32(12) + uint32(leafCorrection))
	v1 = libc.Int32FromInt32(0)
	k = v1
	i = v1
	for {
		if !(i < nOld) {
			break
		}
		p = (**(**[3]uintptr)(__ccgo_up(bp + 8)))[i]
		**(**uintptr)(__ccgo_up(bp + 72 + 32 + uintptr(k)*8)) = (*TMemPage)(unsafe.Pointer(p)).FaDataEnd
		**(**int32)(__ccgo_up(bp + 72 + 80 + uintptr(k)*4)) = cntOld[i]
		if k != 0 && **(**int32)(__ccgo_up(bp + 72 + 80 + uintptr(k)*4)) == **(**int32)(__ccgo_up(bp + 72 + 80 + uintptr(k-int32(1))*4)) {
			k = k - 1 /* Omit b.ixNx[] entry for child pages with no cells */
		}
		if !(leafData != 0) {
			k = k + 1
			**(**uintptr)(__ccgo_up(bp + 72 + 32 + uintptr(k)*8)) = (*TMemPage)(unsafe.Pointer(pParent)).FaDataEnd
			**(**int32)(__ccgo_up(bp + 72 + 80 + uintptr(k)*4)) = cntOld[i] + int32(1)
		}
		(**(**[5]int32)(__ccgo_up(bp + 32)))[i] = usableSpace - (*TMemPage)(unsafe.Pointer(p)).FnFree
		j = 0
		for {
			if !(j < libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(p)).FnOverflow)) {
				break
			}
			**(**int32)(__ccgo_up(bp + 32 + uintptr(i)*4)) += int32(2) + libc.Int32FromUint16((*(*func(*libc.TLS, uintptr, uintptr) Tu16)(unsafe.Pointer(&struct{ uintptr }{(*TMemPage)(unsafe.Pointer(p)).FxCellSize})))(tls, p, **(**uintptr)(__ccgo_up(p + 40 + uintptr(j)*8))))
			goto _8
		_8:
			;
			j = j + 1
		}
		cntNew[i] = cntOld[i]
		goto _6
	_6:
		;
		i = i + 1
		k = k + 1
	}
	k = nOld
	i = 0
	for {
		if !(i < k) {
			break
		}
		for (**(**[5]int32)(__ccgo_up(bp + 32)))[i] > usableSpace {
			if i+int32(1) >= k {
				k = i + int32(2)
				if k > libc.Int32FromInt32(NB)+libc.Int32FromInt32(2) {
					**(**int32)(__ccgo_up(bp)) = _sqlite3CorruptError(tls, int32(81700))
					goto balance_cleanup
				}
				(**(**[5]int32)(__ccgo_up(bp + 32)))[k-int32(1)] = 0
				cntNew[k-int32(1)] = (**(**TCellArray)(__ccgo_up(bp + 72))).FnCell
			}
			sz1 = int32(2) + libc.Int32FromUint16(_cachedCellSize(tls, bp+72, cntNew[i]-int32(1)))
			**(**int32)(__ccgo_up(bp + 32 + uintptr(i)*4)) -= sz1
			if !(leafData != 0) {
				if cntNew[i] < (**(**TCellArray)(__ccgo_up(bp + 72))).FnCell {
					sz1 = int32(2) + libc.Int32FromUint16(_cachedCellSize(tls, bp+72, cntNew[i]))
				} else {
					sz1 = 0
				}
			}
			**(**int32)(__ccgo_up(bp + 32 + uintptr(i+int32(1))*4)) += sz1
			cntNew[i] = cntNew[i] - 1
		}
		for cntNew[i] < (**(**TCellArray)(__ccgo_up(bp + 72))).FnCell {
			sz1 = int32(2) + libc.Int32FromUint16(_cachedCellSize(tls, bp+72, cntNew[i]))
			if (**(**[5]int32)(__ccgo_up(bp + 32)))[i]+sz1 > usableSpace {
				break
			}
			**(**int32)(__ccgo_up(bp + 32 + uintptr(i)*4)) += sz1
			cntNew[i] = cntNew[i] + 1
			if !(leafData != 0) {
				if cntNew[i] < (**(**TCellArray)(__ccgo_up(bp + 72))).FnCell {
					sz1 = int32(2) + libc.Int32FromUint16(_cachedCellSize(tls, bp+72, cntNew[i]))
				} else {
					sz1 = 0
				}
			}
			**(**int32)(__ccgo_up(bp + 32 + uintptr(i+int32(1))*4)) -= sz1
		}
		if cntNew[i] >= (**(**TCellArray)(__ccgo_up(bp + 72))).FnCell {
			k = i + int32(1)
		} else {
			if i > 0 {
				v1 = cntNew[i-int32(1)]
			} else {
				v1 = 0
			}
			if cntNew[i] <= v1 {
				**(**int32)(__ccgo_up(bp)) = _sqlite3CorruptError(tls, int32(81733))
				goto balance_cleanup
			}
		}
		goto _9
	_9:
		;
		i = i + 1
	}
	/*
	 ** The packing computed by the previous block is biased toward the siblings
	 ** on the left side (siblings with smaller keys). The left siblings are
	 ** always nearly full, while the right-most sibling might be nearly empty.
	 ** The next block of code attempts to adjust the packing of siblings to
	 ** get a better balance.
	 **
	 ** This adjustment is more than an optimization.  The packing above might
	 ** be so out of balance as to be illegal.  For example, the right-most
	 ** sibling might be completely empty.  This adjustment is not optional.
	 */
	i = k - int32(1)
	for {
		if !(i > 0) {
			break
		}
		szRight = (**(**[5]int32)(__ccgo_up(bp + 32)))[i]         /* Size of sibling on the right */
		szLeft = (**(**[5]int32)(__ccgo_up(bp + 32)))[i-int32(1)] /* Index of first cell to the left of right sibling */
		r = cntNew[i-int32(1)] - int32(1)
		d = r + int32(1) - leafData
		_cachedCellSize(tls, bp+72, d)
		for cond := true; cond; cond = r >= 0 {
			szR = libc.Int32FromUint16(_cachedCellSize(tls, bp+72, r))
			szD = libc.Int32FromUint16(**(**Tu16)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FszCell + uintptr(d)*2)))
			if v14 = szRight != 0; v14 {
				if v13 = bBulk != 0; !v13 {
					if i == k-int32(1) {
						v1 = 0
					} else {
						v1 = int32(2)
					}
				}
			}
			if v14 && (v13 || szRight+szD+int32(2) > szLeft-(szR+v1)) {
				break
			}
			szRight = szRight + (szD + int32(2))
			szLeft = szLeft - (szR + int32(2))
			cntNew[i-int32(1)] = r
			r = r - 1
			d = d - 1
		}
		(**(**[5]int32)(__ccgo_up(bp + 32)))[i] = szRight
		(**(**[5]int32)(__ccgo_up(bp + 32)))[i-int32(1)] = szLeft
		if i > int32(1) {
			v1 = cntNew[i-int32(2)]
		} else {
			v1 = 0
		}
		if cntNew[i-int32(1)] <= v1 {
			**(**int32)(__ccgo_up(bp)) = _sqlite3CorruptError(tls, int32(81777))
			goto balance_cleanup
		}
		goto _11
	_11:
		;
		i = i - 1
	}
	/* Sanity check:  For a non-corrupt database file one of the following
	 ** must be true:
	 **    (1) We found one or more cells (cntNew[0])>0), or
	 **    (2) pPage is a virtual root page.  A virtual root page is when
	 **        the real root page is page 1 and we are the only child of
	 **        that page.
	 */
	/*
	 ** Allocate k new pages.  Reuse old pages where possible.
	 */
	pageFlags = libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer((**(**[3]uintptr)(__ccgo_up(bp + 8)))[0])).FaData)))
	i = 0
	for {
		if !(i < k) {
			break
		}
		if i < nOld {
			v17 = (**(**[3]uintptr)(__ccgo_up(bp + 8)))[i]
			apNew[i] = v17
			**(**uintptr)(__ccgo_up(bp + 176)) = v17
			(**(**[3]uintptr)(__ccgo_up(bp + 8)))[i] = uintptr(0)
			**(**int32)(__ccgo_up(bp)) = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 176)))).FpDbPage)
			nNew = nNew + 1
			if _sqlite3PagerPageRefcount(tls, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 176)))).FpDbPage) != int32(1)+libc.BoolInt32(i == iParentIdx-nxDiv) && **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
				**(**int32)(__ccgo_up(bp)) = _sqlite3CorruptError(tls, int32(81810))
			}
			if **(**int32)(__ccgo_up(bp)) != 0 {
				goto balance_cleanup
			}
		} else {
			if bBulk != 0 {
				v18 = uint32(1)
			} else {
				v18 = **(**TPgno)(__ccgo_up(bp + 52))
			}
			**(**int32)(__ccgo_up(bp)) = _allocateBtreePage(tls, pBt, bp+176, bp+52, v18, uint8(0))
			if **(**int32)(__ccgo_up(bp)) != 0 {
				goto balance_cleanup
			}
			_zeroPage(tls, **(**uintptr)(__ccgo_up(bp + 176)), pageFlags)
			apNew[i] = **(**uintptr)(__ccgo_up(bp + 176))
			nNew = nNew + 1
			cntOld[i] = (**(**TCellArray)(__ccgo_up(bp + 72))).FnCell
			/* Set the pointer-map entry for the new sibling page. */
			if (*TBtShared)(unsafe.Pointer(pBt)).FautoVacuum != 0 {
				_ptrmapPut(tls, pBt, (*TMemPage)(unsafe.Pointer(**(**uintptr)(__ccgo_up(bp + 176)))).Fpgno, uint8(PTRMAP_BTREE), (*TMemPage)(unsafe.Pointer(pParent)).Fpgno, bp)
				if **(**int32)(__ccgo_up(bp)) != SQLITE_OK {
					goto balance_cleanup
				}
			}
		}
		goto _16
	_16:
		;
		i = i + 1
	}
	/*
	 ** 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
	 ** helps the operating system to deliver pages from the disk more rapidly.
	 **
	 ** An O(N*N) sort algorithm is used, but since N is never more than NB+2
	 ** (5), that is not a performance concern.
	 **
	 ** When NB==3, this one optimization makes the database about 25% faster
	 ** for large insertions and deletions.
	 */
	i = 0
	for {
		if !(i < nNew) {
			break
		}
		aPgno[i] = (*TMemPage)(unsafe.Pointer(apNew[i])).Fpgno
		goto _19
	_19:
		;
		i = i + 1
	}
	i = 0
	for {
		if !(i < nNew-int32(1)) {
			break
		}
		iB = i
		j = i + int32(1)
		for {
			if !(j < nNew) {
				break
			}
			if (*TMemPage)(unsafe.Pointer(apNew[j])).Fpgno < (*TMemPage)(unsafe.Pointer(apNew[iB])).Fpgno {
				iB = j
			}
			goto _21
		_21:
			;
			j = j + 1
		}
		/* If apNew[i] has a page number that is bigger than any of the
		 ** subsequence apNew[i] entries, then swap apNew[i] with the subsequent
		 ** entry that has the smallest page number (which we know to be
		 ** entry apNew[iB]).
		 */
		if iB != i {
			pgnoA = (*TMemPage)(unsafe.Pointer(apNew[i])).Fpgno
			pgnoB = (*TMemPage)(unsafe.Pointer(apNew[iB])).Fpgno
			pgnoTemp = libc.Uint32FromInt32(_sqlite3PendingByte)/(*TBtShared)(unsafe.Pointer(pBt)).FpageSize + uint32(1)
			fgA = (*TDbPage)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(apNew[i])).FpDbPage)).Fflags
			fgB = (*TDbPage)(unsafe.Pointer((*TMemPage)(unsafe.Pointer(apNew[iB])).FpDbPage)).Fflags
			_sqlite3PagerRekey(tls, (*TMemPage)(unsafe.Pointer(apNew[i])).FpDbPage, pgnoTemp, fgB)
			_sqlite3PagerRekey(tls, (*TMemPage)(unsafe.Pointer(apNew[iB])).FpDbPage, pgnoA, fgA)
			_sqlite3PagerRekey(tls, (*TMemPage)(unsafe.Pointer(apNew[i])).FpDbPage, pgnoB, fgB)
			(*TMemPage)(unsafe.Pointer(apNew[i])).Fpgno = pgnoB
			(*TMemPage)(unsafe.Pointer(apNew[iB])).Fpgno = pgnoA
		}
		goto _20
	_20:
		;
		i = i + 1
	}
	_sqlite3Put4byte(tls, pRight, (*TMemPage)(unsafe.Pointer(apNew[nNew-int32(1)])).Fpgno)
	/* 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
	 ** originally in the same field of the right-most old sibling page. */
	if pageFlags&int32(PTF_LEAF) == 0 && nOld != nNew {
		if nNew > nOld {
			pOld1 = apNew[nOld-int32(1)]
		} else {
			pOld1 = (**(**[3]uintptr)(__ccgo_up(bp + 8)))[nOld-int32(1)]
		}
		libc.Xmemcpy(tls, (*TMemPage)(unsafe.Pointer(apNew[nNew-int32(1)])).FaData+8, (*TMemPage)(unsafe.Pointer(pOld1)).FaData+8, uint64(4))
	}
	/* 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:
	 **
	 **   a) if the cell contains a reference to an overflow chain, the
	 **      entry associated with the first page in the overflow chain, and
	 **
	 **   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
	 ** populated, not here.
	 */
	if (*TBtShared)(unsafe.Pointer(pBt)).FautoVacuum != 0 {
		v17 = apNew[0]
		pOld2 = v17
		pNew1 = v17
		cntOldNext = libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pNew1)).FnCell) + libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pNew1)).FnOverflow)
		iNew = 0
		iOld = 0
		i = 0
		for {
			if !(i < (**(**TCellArray)(__ccgo_up(bp + 72))).FnCell) {
				break
			}
			pCell = **(**uintptr)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FapCell + uintptr(i)*8))
			for i == cntOldNext {
				iOld = iOld + 1
				if iOld < nNew {
					v17 = apNew[iOld]
				} else {
					v17 = (**(**[3]uintptr)(__ccgo_up(bp + 8)))[iOld]
				}
				pOld2 = v17
				cntOldNext = cntOldNext + (libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pOld2)).FnCell) + libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pOld2)).FnOverflow) + libc.BoolInt32(!(leafData != 0)))
			}
			if i == cntNew[iNew] {
				iNew = iNew + 1
				v1 = iNew
				pNew1 = apNew[v1]
				if !(leafData != 0) {
					goto _23
				}
			}
			/* Cell pCell is destined for new sibling page pNew. Originally, it
			 ** 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
			 ** overflow cell), we can skip updating the pointer map entries.  */
			if iOld >= nNew || (*TMemPage)(unsafe.Pointer(pNew1)).Fpgno != aPgno[iOld] || !(uint64(pCell) >= uint64((*TMemPage)(unsafe.Pointer(pOld2)).FaData) && uint64(pCell) < uint64((*TMemPage)(unsafe.Pointer(pOld2)).FaDataEnd)) {
				if !(leafCorrection != 0) {
					_ptrmapPut(tls, pBt, _sqlite3Get4byte(tls, pCell), uint8(PTRMAP_BTREE), (*TMemPage)(unsafe.Pointer(pNew1)).Fpgno, bp)
				}
				if libc.Int32FromUint16(_cachedCellSize(tls, bp+72, i)) > libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pNew1)).FminLocal) {
					_ptrmapPutOvflPtr(tls, pNew1, pOld2, pCell, bp)
				}
				if **(**int32)(__ccgo_up(bp)) != 0 {
					goto balance_cleanup
				}
			}
			goto _23
		_23:
			;
			i = i + 1
		}
	}
	/* Insert new divider cells into pParent. */
	i = 0
	for {
		if !(i < nNew-int32(1)) {
			break
		}
		pNew2 = apNew[i]
		j = cntNew[i]
		pCell1 = **(**uintptr)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FapCell + uintptr(j)*8))
		sz2 = libc.Int32FromUint16(**(**Tu16)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FszCell + uintptr(j)*2))) + libc.Int32FromUint16(leafCorrection)
		pTemp1 = aOvflSpace + uintptr(iOvflSpace)
		if !((*TMemPage)(unsafe.Pointer(pNew2)).Fleaf != 0) {
			libc.Xmemcpy(tls, (*TMemPage)(unsafe.Pointer(pNew2)).FaData+8, pCell1, uint64(4))
		} else {
			if leafData != 0 {
				j = j - 1
				(*(*func(*libc.TLS, uintptr, uintptr, uintptr))(unsafe.Pointer(&struct{ uintptr }{(*TMemPage)(unsafe.Pointer(pNew2)).FxParseCell})))(tls, pNew2, **(**uintptr)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FapCell + uintptr(j)*8)), bp+184)
				pCell1 = pTemp1
				sz2 = int32(4) + _sqlite3PutVarint(tls, pCell1+4, libc.Uint64FromInt64((**(**TCellInfo)(__ccgo_up(bp + 184))).FnKey))
				pTemp1 = uintptr(0)
			} else {
				pCell1 = pCell1 - uintptr(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
				 ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
				 ** 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 ...)"
				 ** and WITHOUT ROWID tables with exactly one column which is the
				 ** primary key.
				 */
				if libc.Int32FromUint16(**(**Tu16)(__ccgo_up((**(**TCellArray)(__ccgo_up(bp + 72))).FszCell + uintptr(j)*2))) == int32(4) {
					sz2 = libc.Int32FromUint16((*(*func(*libc.TLS, uintptr, uintptr) Tu16)(unsafe.Pointer(&struct{ uintptr }{(*TMemPage)(unsafe.Pointer(pParent)).FxCellSize})))(tls, pParent, pCell1))
				}
			}
		}
		iOvflSpace = iOvflSpace + sz2
		k = 0
		for {
			if !(**(**int32)(__ccgo_up(bp + 72 + 80 + uintptr(k)*4)) <= j) {
				break
			}
			goto _27
		_27:
			;
			k = k + 1
		}
		pSrcEnd = **(**uintptr)(__ccgo_up(bp + 72 + 32 + uintptr(k)*8))
		if uint64(pCell1) < uint64(pSrcEnd) && uint64(pCell1+uintptr(sz2)) > uint64(pSrcEnd) {
			**(**int32)(__ccgo_up(bp)) = _sqlite3CorruptError(tls, int32(82016))
			goto balance_cleanup
		}
		**(**int32)(__ccgo_up(bp)) = _insertCell(tls, pParent, nxDiv+i, pCell1, sz2, pTemp1, (*TMemPage)(unsafe.Pointer(pNew2)).Fpgno)
		if **(**int32)(__ccgo_up(bp)) != SQLITE_OK {
			goto balance_cleanup
		}
		goto _26
	_26:
		;
		i = i + 1
	}
	/* Now update the actual sibling pages. The order in which they are updated
	 ** is important, as this code needs to avoid disrupting any page from which
	 ** cells may still to be read. In practice, this means:
	 **
	 **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
	 **      then it is not safe to update page apNew[iPg] until after
	 **      the left-hand sibling apNew[iPg-1] has been updated.
	 **
	 **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
	 **      then it is not safe to update page apNew[iPg] until after
	 **      the right-hand sibling apNew[iPg+1] has been updated.
	 **
	 ** If neither of the above apply, the page is safe to update.
	 **
	 ** The iPg value in the following loop starts at nNew-1 goes down
	 ** to 0, then back up to nNew-1 again, thus making two passes over
	 ** the pages.  On the initial downward pass, only condition (1) above
	 ** needs to be tested because (2) will always be true from the previous
	 ** step.  On the upward pass, both conditions are always true, so the
	 ** upwards pass simply processes pages that were missed on the downward
	 ** pass.
	 */
	i = int32(1) - nNew
	for {
		if !(i < nNew) {
			break
		}
		if i < 0 {
			v1 = -i
		} else {
			v1 = i
		}
		iPg = v1
		if (**(**[5]Tu8)(__ccgo_up(bp + 60)))[iPg] != 0 {
			goto _28
		} /* Skip pages already processed */
		if i >= 0 || cntOld[iPg-int32(1)] >= cntNew[iPg-int32(1)] {
			/* Verify condition (1):  If cells are moving left, update iPg
			 ** only after iPg-1 has already been updated. */
			/* Verify condition (2):  If cells are moving right, update iPg
			 ** only after iPg+1 has already been updated. */
			if iPg == 0 {
				v1 = libc.Int32FromInt32(0)
				iOld1 = v1
				iNew1 = v1
				nNewCell = cntNew[0]
			} else {
				if iPg < nOld {
					v1 = cntOld[iPg-int32(1)] + libc.BoolInt32(!(leafData != 0))
				} else {
					v1 = (**(**TCellArray)(__ccgo_up(bp + 72))).FnCell
				}
				iOld1 = v1
				iNew1 = cntNew[iPg-int32(1)] + libc.BoolInt32(!(leafData != 0))
				nNewCell = cntNew[iPg] - iNew1
			}
			**(**int32)(__ccgo_up(bp)) = _editPage(tls, apNew[iPg], iOld1, iNew1, nNewCell, bp+72)
			if **(**int32)(__ccgo_up(bp)) != 0 {
				goto balance_cleanup
			}
			(**(**[5]Tu8)(__ccgo_up(bp + 60)))[iPg] = (**(**[5]Tu8)(__ccgo_up(bp + 60)))[iPg] + 1
			(*TMemPage)(unsafe.Pointer(apNew[iPg])).FnFree = usableSpace - (**(**[5]int32)(__ccgo_up(bp + 32)))[iPg]
		}
		goto _28
	_28:
		;
		i = i + 1
	}
	/* All pages have been processed exactly once */
	if isRoot != 0 && libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pParent)).FnCell) == 0 && libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pParent)).FhdrOffset) <= (*TMemPage)(unsafe.Pointer(apNew[0])).FnFree {
		/* The root page of the b-tree now contains no cells. The only sibling
		 ** page is the right-child of the parent. Copy the contents of the
		 ** child page into the parent, decreasing the overall height of the
		 ** 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
		 ** for which the pointer is stored within the content being copied.
		 **
		 ** It is critical that the child page be defragmented before being
		 ** copied into the parent, because if the parent is page 1 then it will
		 ** by smaller than the child due to the database header, and so all the
		 ** free space needs to be up front.
		 */
		**(**int32)(__ccgo_up(bp)) = _defragmentPage(tls, apNew[0], -int32(1))
		_copyNodeContent(tls, apNew[0], pParent, bp)
		_freePage(tls, apNew[0], bp)
	} else {
		if (*TBtShared)(unsafe.Pointer(pBt)).FautoVacuum != 0 && !(leafCorrection != 0) {
			/* Fix the pointer map entries associated with the right-child of each
			 ** sibling page. All other pointer map entries have already been taken
			 ** care of.  */
			i = 0
			for {
				if !(i < nNew) {
					break
				}
				key = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(apNew[i])).FaData+8)
				_ptrmapPut(tls, pBt, key, uint8(PTRMAP_BTREE), (*TMemPage)(unsafe.Pointer(apNew[i])).Fpgno, bp)
				goto _32
			_32:
				;
				i = i + 1
			}
		}
	}
	/* Free any old pages that were not reused as new pages.
	 */
	i = nNew
	for {
		if !(i < nOld) {
			break
		}
		_freePage(tls, (**(**[3]uintptr)(__ccgo_up(bp + 8)))[i], bp)
		goto _33
	_33:
		;
		i = i + 1
	}
	/*
	 ** Cleanup before returning.
	 */
	goto balance_cleanup
balance_cleanup:
	;
	_sqlite3DbFree(tls, uintptr(0), (**(**TCellArray)(__ccgo_up(bp + 72))).FapCell)
	i = 0
	for {
		if !(i < nOld) {
			break
		}
		_releasePage(tls, (**(**[3]uintptr)(__ccgo_up(bp + 8)))[i])
		goto _34
	_34:
		;
		i = i + 1
	}
	i = 0
	for {
		if !(i < nNew) {
			break
		}
		_releasePage(tls, apNew[i])
		goto _35
	_35:
		;
		i = i + 1
	}
	return **(**int32)(__ccgo_up(bp))
}

// C documentation
//
//	/* Move the cursor so that it points to an entry in an index table
//	** near the key pIdxKey.   Return a success code.
//	**
//	** If an exact match is not found, then the cursor is always
//	** left pointing at a leaf page which would hold the entry if it
//	** were present.  The cursor might point to an entry that comes
//	** 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
//	** pointing.  The meaning of the integer written into
//	** *pRes is as follows:
//	**
//	**     *pRes<0      The cursor is left pointing at an entry that
//	**                  is smaller than pIdxKey or if the table is empty
//	**                  and the cursor is therefore left point to nothing.
//	**
//	**     *pRes==0     The cursor is left pointing at an entry that
//	**                  exactly matches pIdxKey.
//	**
//	**     *pRes>0      The cursor is left pointing at an entry that
//	**                  is larger than pIdxKey.
//	**
//	** The pIdxKey->eqSeen field is set to 1 if there
//	** exists an entry in the table that exactly matches pIdxKey.
//	*/
func _sqlite3BtreeIndexMoveto(tls *libc.TLS, pCur uintptr, pIdxKey uintptr, pRes uintptr) (r int32) {
	var c, c1, idx, lwr, nCell, nOverrun, rc, upr, v1 int32
	var chldPg TPgno
	var pCell, pCellBody, pCellKey, pPage, v3 uintptr
	var xRecordCompare TRecordCompare
	var v10 Ti8
	var v2 bool
	_, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _ = c, c1, chldPg, idx, lwr, nCell, nOverrun, pCell, pCellBody, pCellKey, pPage, rc, upr, xRecordCompare, v1, v10, v2, v3
	xRecordCompare = _sqlite3VdbeFindCompare(tls, pIdxKey)
	(*TUnpackedRecord)(unsafe.Pointer(pIdxKey)).FerrCode = uint8(0)
	/* Check to see if we can skip a lot of work.  Two cases:
	 **
	 **    (1) If the cursor is already pointing to the very last cell
	 **        in the table and the pIdxKey search key is greater than or
	 **        equal to that last cell, then no movement is required.
	 **
	 **    (2) If the cursor is on the last page of the table and the first
	 **        cell on that last page is less than or equal to the pIdxKey
	 **        search key, then we can start the search on the current page
	 **        without needing to go back to root.
	 */
	if libc.Int32FromUint8((*TBtCursor)(unsafe.Pointer(pCur)).FeState) == CURSOR_VALID && (*TMemPage)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pCur)).FpPage)).Fleaf != 0 && _cursorOnLastPage(tls, pCur) != 0 {
		if v2 = libc.Int32FromUint16((*TBtCursor)(unsafe.Pointer(pCur)).Fix) == libc.Int32FromUint16((*TMemPage)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pCur)).FpPage)).FnCell)-int32(1); v2 {
			v1 = _indexCellCompare(tls, (*TBtCursor)(unsafe.Pointer(pCur)).FpPage, libc.Int32FromUint16((*TBtCursor)(unsafe.Pointer(pCur)).Fix), pIdxKey, xRecordCompare)
			c = v1
		}
		if v2 && v1 <= 0 && libc.Int32FromUint8((*TUnpackedRecord)(unsafe.Pointer(pIdxKey)).FerrCode) == SQLITE_OK {
			**(**int32)(__ccgo_up(pRes)) = c
			return SQLITE_OK /* Cursor already pointing at the correct spot */
		}
		if int32((*TBtCursor)(unsafe.Pointer(pCur)).FiPage) > 0 && _indexCellCompare(tls, (*TBtCursor)(unsafe.Pointer(pCur)).FpPage, 0, pIdxKey, xRecordCompare) <= 0 && libc.Int32FromUint8((*TUnpackedRecord)(unsafe.Pointer(pIdxKey)).FerrCode) == SQLITE_OK {
			v3 = pCur + 1
			*(*Tu8)(unsafe.Pointer(v3)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v3))) & ^(libc.Int32FromInt32(BTCF_ValidOvfl) | libc.Int32FromInt32(BTCF_AtLast)))
			if !((*TMemPage)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pCur)).FpPage)).FisInit != 0) {
				return _sqlite3CorruptError(tls, int32(79227))
			}
			goto bypass_moveto_root /* Start search on the current page */
		}
		(*TUnpackedRecord)(unsafe.Pointer(pIdxKey)).FerrCode = uint8(SQLITE_OK)
	}
	rc = _moveToRoot(tls, pCur)
	if rc != 0 {
		if rc == int32(SQLITE_EMPTY) {
			**(**int32)(__ccgo_up(pRes)) = -int32(1)
			return SQLITE_OK
		}
		return rc
	}
	goto bypass_moveto_root
bypass_moveto_root:
	;
	for {
		pPage = (*TBtCursor)(unsafe.Pointer(pCur)).FpPage /* Pointer to current cell in pPage */
		/* pPage->nCell must be greater than zero. If this is the root-page
		 ** the cursor would have been INVALID above and this for(;;) loop
		 ** not run. If this is not the root-page, then the moveToChild() routine
		 ** would have already detected db corruption. Similarly, pPage must
		 ** be the right kind (index or table) of b-tree page. Otherwise
		 ** a moveToChild() or moveToRoot() call would have detected corruption.  */
		lwr = 0
		upr = libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell) - int32(1)
		idx = upr >> int32(1) /* idx = (lwr+upr)/2; */
		for {                 /* Size of the pCell cell in bytes */
			pCell = (*TMemPage)(unsafe.Pointer(pPage)).FaDataOfst + uintptr(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FmaskPage)&(libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(pPage)).FaCellIdx + uintptr(int32(2)*idx))))<<libc.Int32FromInt32(8)|libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(pPage)).FaCellIdx + uintptr(int32(2)*idx) + 1)))))
			/* 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
			 ** 2 bytes of the cell.
			 */
			nCell = libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pCell)))
			if nCell <= libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPage)).Fmax1bytePayload) {
				/* This branch runs if the record-size field of the cell is a
				 ** single byte varint and the record fits entirely on the main
				 ** b-tree page.  */
				c1 = (*(*func(*libc.TLS, int32, uintptr, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{xRecordCompare})))(tls, nCell, pCell+1, pIdxKey)
			} else {
				if v2 = !(libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pCell + 1)))&libc.Int32FromInt32(0x80) != 0); v2 {
					v1 = nCell&libc.Int32FromInt32(0x7f)<<libc.Int32FromInt32(7) + libc.Int32FromUint8(**(**Tu8)(__ccgo_up(pCell + 1)))
					nCell = v1
				}
				if v2 && v1 <= libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FmaxLocal) {
					/* The record-size field is a 2 byte varint and the record
					 ** fits entirely on the main b-tree page.  */
					c1 = (*(*func(*libc.TLS, int32, uintptr, uintptr) int32)(unsafe.Pointer(&struct{ uintptr }{xRecordCompare})))(tls, nCell, pCell+2, pIdxKey)
				} else {
					pCellBody = pCell - uintptr((*TMemPage)(unsafe.Pointer(pPage)).FchildPtrSize)
					nOverrun = int32(18) /* Size of the overrun padding */
					(*(*func(*libc.TLS, uintptr, uintptr, uintptr))(unsafe.Pointer(&struct{ uintptr }{(*TMemPage)(unsafe.Pointer(pPage)).FxParseCell})))(tls, pPage, pCellBody, pCur+48)
					nCell = int32((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnKey)
					/* True if key size is 2^32 or more */
					/* Invalid key size:  0x80 0x80 0x00 */
					/* Invalid key size:  0x80 0x80 0x01 */
					/* Minimum legal index key size */
					if nCell < int32(2) || libc.Uint32FromInt32(nCell)/(*TBtShared)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pCur)).FpBt)).FusableSize > (*TBtShared)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pCur)).FpBt)).FnPage {
						rc = _sqlite3CorruptError(tls, int32(79314))
						goto moveto_index_finish
					}
					pCellKey = _sqlite3Malloc(tls, libc.Uint64FromInt32(nCell)+libc.Uint64FromInt32(nOverrun))
					if pCellKey == uintptr(0) {
						rc = int32(SQLITE_NOMEM)
						goto moveto_index_finish
					}
					(*TBtCursor)(unsafe.Pointer(pCur)).Fix = libc.Uint16FromInt32(idx)
					rc = _accessPayload(tls, pCur, uint32(0), libc.Uint32FromInt32(nCell), pCellKey, 0)
					libc.Xmemset(tls, pCellKey+uintptr(nCell), 0, libc.Uint64FromInt32(nOverrun)) /* Fix uninit warnings */
					v3 = pCur + 1
					*(*Tu8)(unsafe.Pointer(v3)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v3))) & ^libc.Int32FromInt32(BTCF_ValidOvfl))
					if rc != 0 {
						Xsqlite3_free(tls, pCellKey)
						goto moveto_index_finish
					}
					c1 = _sqlite3VdbeRecordCompare(tls, nCell, pCellKey, pIdxKey)
					Xsqlite3_free(tls, pCellKey)
				}
			}
			if c1 < 0 {
				lwr = idx + int32(1)
			} else {
				if c1 > 0 {
					upr = idx - int32(1)
				} else {
					**(**int32)(__ccgo_up(pRes)) = 0
					rc = SQLITE_OK
					(*TBtCursor)(unsafe.Pointer(pCur)).Fix = libc.Uint16FromInt32(idx)
					if (*TUnpackedRecord)(unsafe.Pointer(pIdxKey)).FerrCode != 0 {
						rc = _sqlite3CorruptError(tls, int32(79346))
					}
					goto moveto_index_finish
				}
			}
			if lwr > upr {
				break
			}
			idx = (lwr + upr) >> int32(1) /* idx = (lwr+upr)/2 */
			goto _5
		_5:
		}
		if (*TMemPage)(unsafe.Pointer(pPage)).Fleaf != 0 {
			(*TBtCursor)(unsafe.Pointer(pCur)).Fix = libc.Uint16FromInt32(idx)
			**(**int32)(__ccgo_up(pRes)) = c1
			rc = SQLITE_OK
			goto moveto_index_finish
		}
		if lwr >= libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell) {
			chldPg = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(pPage)).FaData+uintptr(libc.Int32FromUint8((*TMemPage)(unsafe.Pointer(pPage)).FhdrOffset)+int32(8)))
		} else {
			chldPg = _sqlite3Get4byte(tls, (*TMemPage)(unsafe.Pointer(pPage)).FaData+uintptr(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FmaskPage)&(libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(pPage)).FaCellIdx + uintptr(int32(2)*lwr))))<<libc.Int32FromInt32(8)|libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(pPage)).FaCellIdx + uintptr(int32(2)*lwr) + 1))))))
		}
		/* This block is similar to an in-lined version of:
		 **
		 **    pCur->ix = (u16)lwr;
		 **    rc = moveToChild(pCur, chldPg);
		 **    if( rc ) break;
		 */
		(*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnSize = uint16(0)
		v3 = pCur + 1
		*(*Tu8)(unsafe.Pointer(v3)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v3))) & ^(libc.Int32FromInt32(BTCF_ValidNKey) | libc.Int32FromInt32(BTCF_ValidOvfl)))
		if int32((*TBtCursor)(unsafe.Pointer(pCur)).FiPage) >= libc.Int32FromInt32(BTCURSOR_MAX_DEPTH)-libc.Int32FromInt32(1) {
			return _sqlite3CorruptError(tls, int32(79377))
		}
		**(**Tu16)(__ccgo_up(pCur + 88 + uintptr((*TBtCursor)(unsafe.Pointer(pCur)).FiPage)*2)) = libc.Uint16FromInt32(lwr)
		**(**uintptr)(__ccgo_up(pCur + 144 + uintptr((*TBtCursor)(unsafe.Pointer(pCur)).FiPage)*8)) = (*TBtCursor)(unsafe.Pointer(pCur)).FpPage
		(*TBtCursor)(unsafe.Pointer(pCur)).Fix = uint16(0)
		(*TBtCursor)(unsafe.Pointer(pCur)).FiPage = (*TBtCursor)(unsafe.Pointer(pCur)).FiPage + 1
		rc = _getAndInitPage(tls, (*TBtCursor)(unsafe.Pointer(pCur)).FpBt, chldPg, pCur+136, libc.Int32FromUint8((*TBtCursor)(unsafe.Pointer(pCur)).FcurPagerFlags))
		if rc == SQLITE_OK && (libc.Int32FromUint16((*TMemPage)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pCur)).FpPage)).FnCell) < int32(1) || libc.Int32FromUint8((*TMemPage)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pCur)).FpPage)).FintKey) != libc.Int32FromUint8((*TBtCursor)(unsafe.Pointer(pCur)).FcurIntKey)) {
			_releasePage(tls, (*TBtCursor)(unsafe.Pointer(pCur)).FpPage)
			rc = _sqlite3CorruptError(tls, int32(79388))
		}
		if rc != 0 {
			v3 = pCur + 84
			*(*Ti8)(unsafe.Pointer(v3)) = *(*Ti8)(unsafe.Pointer(v3)) - 1
			v10 = *(*Ti8)(unsafe.Pointer(v3))
			(*TBtCursor)(unsafe.Pointer(pCur)).FpPage = **(**uintptr)(__ccgo_up(pCur + 144 + uintptr(v10)*8))
			break
		}
		/*
		 ***** End of in-lined moveToChild() call */
		goto _4
	_4:
	}
	goto moveto_index_finish
moveto_index_finish:
	;
	(*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnSize = uint16(0)
	return rc
}

// C documentation
//
//	/*
//	** Insert a new record into the BTree.  The content of the new record
//	** is described by the pX object.  The pCur cursor is used only to
//	** define what table the record should be inserted into, and is left
//	** pointing at a random location.
//	**
//	** For a table btree (used for rowid tables), only the pX.nKey value of
//	** the key is used. The pX.pKey value must be NULL.  The pX.nKey is the
//	** rowid or INTEGER PRIMARY KEY of the row.  The pX.nData,pData,nZero fields
//	** 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
//	** pX.pData,nData,nZero fields must be zero.
//	**
//	** If the seekResult parameter is non-zero, then a successful call to
//	** sqlite3BtreeIndexMoveto() to seek cursor pCur to (pKey,nKey) has already
//	** been performed.  In other words, if seekResult!=0 then the cursor
//	** is currently pointing to a cell that will be adjacent to the cell
//	** to be inserted.  If seekResult<0 then pCur points to a cell that is
//	** smaller then (pKey,nKey).  If seekResult>0 then pCur points to a cell
//	** that is larger than (pKey,nKey).
//	**
//	** If seekResult==0, that means pCur is pointing at some unknown location.
//	** In that case, this routine must seek the cursor to the correct insertion
//	** point for (pKey,nKey) before doing the insertion.  For index btrees,
//	** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
//	** key values and pX->aMem can be used instead of pX->pKey to avoid having
//	** to decode the key.
//	*/
func _sqlite3BtreeInsert(tls *libc.TLS, pCur uintptr, pX uintptr, flags int32, seekResult int32) (r int32) {
	bp := tls.Alloc(160)
	defer tls.Free(160)
	var idx int32
	var newCell, oldCell, p, pPage, v1 uintptr
	var ovfl TPgno
	var v2 Tu16
	var _ /* info at bp+104 */ TCellInfo
	var _ /* info at bp+128 */ TCellInfo
	var _ /* loc at bp+4 */ int32
	var _ /* r at bp+16 */ TUnpackedRecord
	var _ /* rc at bp+0 */ int32
	var _ /* szNew at bp+8 */ int32
	var _ /* x2 at bp+56 */ TBtreePayload
	_, _, _, _, _, _, _, _ = idx, newCell, oldCell, ovfl, p, pPage, v1, v2
	**(**int32)(__ccgo_up(bp + 4)) = seekResult /* -1: before desired location  +1: after */
	**(**int32)(__ccgo_up(bp + 8)) = 0
	p = (*TBtCursor)(unsafe.Pointer(pCur)).FpBtree
	newCell = uintptr(0)
	/* Save the positions of any other cursors open on this table.
	 **
	 ** 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
	 ** 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
	 ** not to clear the cursor here.
	 */
	if libc.Int32FromUint8((*TBtCursor)(unsafe.Pointer(pCur)).FcurFlags)&int32(BTCF_Multiple) != 0 {
		**(**int32)(__ccgo_up(bp)) = _saveAllCursors(tls, (*TBtree)(unsafe.Pointer(p)).FpBt, (*TBtCursor)(unsafe.Pointer(pCur)).FpgnoRoot, pCur)
		if **(**int32)(__ccgo_up(bp)) != 0 {
			return **(**int32)(__ccgo_up(bp))
		}
		if **(**int32)(__ccgo_up(bp + 4)) != 0 && int32((*TBtCursor)(unsafe.Pointer(pCur)).FiPage) < 0 {
			/* This can only happen if the schema is corrupt such that there is more
			 ** than one table or index with the same root page as used by the cursor.
			 ** Which can only happen if the SQLITE_NoSchemaError flag was set when
			 ** the schema was loaded. This cannot be asserted though, as a user might
			 ** set the flag, load the schema, and then unset the flag.  */
			return _sqlite3CorruptError(tls, int32(82581))
		}
	}
	/* Ensure that the cursor is not in the CURSOR_FAULT state and that it
	 ** points to a valid cell.
	 */
	if libc.Int32FromUint8((*TBtCursor)(unsafe.Pointer(pCur)).FeState) >= int32(CURSOR_REQUIRESEEK) {
		**(**int32)(__ccgo_up(bp)) = _moveToRoot(tls, pCur)
		if **(**int32)(__ccgo_up(bp)) != 0 && **(**int32)(__ccgo_up(bp)) != int32(SQLITE_EMPTY) {
			return **(**int32)(__ccgo_up(bp))
		}
	}
	/* Assert that the caller has been consistent. If this cursor was opened
	 ** expecting an index b-tree, then the caller should be inserting blob
	 ** keys with no associated data. If the cursor was opened expecting an
	 ** intkey table, the caller should be inserting integer keys with a
	 ** blob of associated data.  */
	if (*TBtCursor)(unsafe.Pointer(pCur)).FpKeyInfo == uintptr(0) {
		/* If this is an insert into a table b-tree, invalidate any incrblob
		 ** cursors open on the row being replaced */
		if (*TBtree)(unsafe.Pointer(p)).FhasIncrblobCur != 0 {
			_invalidateIncrblobCursors(tls, p, (*TBtCursor)(unsafe.Pointer(pCur)).FpgnoRoot, (*TBtreePayload)(unsafe.Pointer(pX)).FnKey, 0)
		}
		/* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
		 ** to a row with the same key as the new entry being inserted.
		 */
		/* On the other hand, BTREE_SAVEPOSITION==0 does not imply
		 ** that the cursor is not pointing to a row to be overwritten.
		 ** So do a complete check.
		 */
		if libc.Int32FromUint8((*TBtCursor)(unsafe.Pointer(pCur)).FcurFlags)&int32(BTCF_ValidNKey) != 0 && (*TBtreePayload)(unsafe.Pointer(pX)).FnKey == (*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnKey {
			/* The cursor is pointing to the entry that is to be
			 ** overwritten */
			if libc.Int32FromUint16((*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnSize) != 0 && (*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnPayload == libc.Uint32FromInt32((*TBtreePayload)(unsafe.Pointer(pX)).FnData)+libc.Uint32FromInt32((*TBtreePayload)(unsafe.Pointer(pX)).FnZero) {
				/* New entry is the same size as the old.  Do an overwrite */
				return _btreeOverwriteCell(tls, pCur, pX)
			}
		} else {
			if **(**int32)(__ccgo_up(bp + 4)) == 0 {
				/* The cursor is *not* pointing to the cell to be overwritten, nor
				 ** to an adjacent cell.  Move the cursor so that it is pointing either
				 ** to the cell to be overwritten or an adjacent cell.
				 */
				**(**int32)(__ccgo_up(bp)) = _sqlite3BtreeTableMoveto(tls, pCur, (*TBtreePayload)(unsafe.Pointer(pX)).FnKey, libc.BoolInt32(flags&int32(BTREE_APPEND) != 0), bp+4)
				if **(**int32)(__ccgo_up(bp)) != 0 {
					return **(**int32)(__ccgo_up(bp))
				}
			}
		}
	} else {
		/* This is an index or a WITHOUT ROWID table */
		/* If BTREE_SAVEPOSITION is set, the cursor must already be pointing
		 ** to a row with the same key as the new entry being inserted.
		 */
		/* If the cursor is not already pointing either to the cell to be
		 ** overwritten, or if a new cell is being inserted, if the cursor is
		 ** not pointing to an immediately adjacent cell, then move the cursor
		 ** so that it does.
		 */
		if **(**int32)(__ccgo_up(bp + 4)) == 0 && flags&int32(BTREE_SAVEPOSITION) == 0 {
			if (*TBtreePayload)(unsafe.Pointer(pX)).FnMem != 0 {
				(**(**TUnpackedRecord)(__ccgo_up(bp + 16))).FpKeyInfo = (*TBtCursor)(unsafe.Pointer(pCur)).FpKeyInfo
				(**(**TUnpackedRecord)(__ccgo_up(bp + 16))).FaMem = (*TBtreePayload)(unsafe.Pointer(pX)).FaMem
				(**(**TUnpackedRecord)(__ccgo_up(bp + 16))).FnField = (*TBtreePayload)(unsafe.Pointer(pX)).FnMem
				(**(**TUnpackedRecord)(__ccgo_up(bp + 16))).Fdefault_rc = 0
				(**(**TUnpackedRecord)(__ccgo_up(bp + 16))).FeqSeen = uint8(0)
				**(**int32)(__ccgo_up(bp)) = _sqlite3BtreeIndexMoveto(tls, pCur, bp+16, bp+4)
			} else {
				**(**int32)(__ccgo_up(bp)) = _btreeMoveto(tls, pCur, (*TBtreePayload)(unsafe.Pointer(pX)).FpKey, (*TBtreePayload)(unsafe.Pointer(pX)).FnKey, libc.BoolInt32(flags&int32(BTREE_APPEND) != 0), bp+4)
			}
			if **(**int32)(__ccgo_up(bp)) != 0 {
				return **(**int32)(__ccgo_up(bp))
			}
		}
		/* If the cursor is currently pointing to an entry to be overwritten
		 ** and the new content is the same as as the old, then use the
		 ** overwrite optimization.
		 */
		if **(**int32)(__ccgo_up(bp + 4)) == 0 {
			_getCellInfo(tls, pCur)
			if (*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnKey == (*TBtreePayload)(unsafe.Pointer(pX)).FnKey {
				(**(**TBtreePayload)(__ccgo_up(bp + 56))).FpData = (*TBtreePayload)(unsafe.Pointer(pX)).FpKey
				(**(**TBtreePayload)(__ccgo_up(bp + 56))).FnData = int32((*TBtreePayload)(unsafe.Pointer(pX)).FnKey)
				(**(**TBtreePayload)(__ccgo_up(bp + 56))).FnZero = 0
				return _btreeOverwriteCell(tls, pCur, bp+56)
			}
		}
	}
	pPage = (*TBtCursor)(unsafe.Pointer(pCur)).FpPage
	if (*TMemPage)(unsafe.Pointer(pPage)).FnFree < 0 {
		if libc.Int32FromUint8((*TBtCursor)(unsafe.Pointer(pCur)).FeState) > int32(CURSOR_INVALID) {
			/* ^^^^^--- due to the moveToRoot() call above */
			**(**int32)(__ccgo_up(bp)) = _sqlite3CorruptError(tls, int32(82704))
		} else {
			**(**int32)(__ccgo_up(bp)) = _btreeComputeFreeSpace(tls, pPage)
		}
		if **(**int32)(__ccgo_up(bp)) != 0 {
			return **(**int32)(__ccgo_up(bp))
		}
	}
	newCell = (*TBtShared)(unsafe.Pointer((*TBtree)(unsafe.Pointer(p)).FpBt)).FpTmpSpace
	if flags&int32(BTREE_PREFORMAT) != 0 {
		**(**int32)(__ccgo_up(bp)) = SQLITE_OK
		**(**int32)(__ccgo_up(bp + 8)) = (*TBtShared)(unsafe.Pointer((*TBtree)(unsafe.Pointer(p)).FpBt)).FnPreformatSize
		if **(**int32)(__ccgo_up(bp + 8)) < int32(4) {
			**(**int32)(__ccgo_up(bp + 8)) = int32(4)
			**(**uint8)(__ccgo_up(newCell + 3)) = uint8(0)
		}
		if (*TBtShared)(unsafe.Pointer((*TBtree)(unsafe.Pointer(p)).FpBt)).FautoVacuum != 0 && **(**int32)(__ccgo_up(bp + 8)) > libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FmaxLocal) {
			(*(*func(*libc.TLS, uintptr, uintptr, uintptr))(unsafe.Pointer(&struct{ uintptr }{(*TMemPage)(unsafe.Pointer(pPage)).FxParseCell})))(tls, pPage, newCell, bp+104)
			if (**(**TCellInfo)(__ccgo_up(bp + 104))).FnPayload != uint32((**(**TCellInfo)(__ccgo_up(bp + 104))).FnLocal) {
				ovfl = _sqlite3Get4byte(tls, newCell+uintptr(**(**int32)(__ccgo_up(bp + 8))-int32(4)))
				_ptrmapPut(tls, (*TBtree)(unsafe.Pointer(p)).FpBt, ovfl, uint8(PTRMAP_OVERFLOW1), (*TMemPage)(unsafe.Pointer(pPage)).Fpgno, bp)
				if **(**int32)(__ccgo_up(bp)) != 0 {
					goto end_insert
				}
			}
		}
	} else {
		**(**int32)(__ccgo_up(bp)) = _fillInCell(tls, pPage, newCell, pX, bp+8)
		if **(**int32)(__ccgo_up(bp)) != 0 {
			goto end_insert
		}
	}
	idx = libc.Int32FromUint16((*TBtCursor)(unsafe.Pointer(pCur)).Fix)
	(*TBtCursor)(unsafe.Pointer(pCur)).Finfo.FnSize = uint16(0)
	if **(**int32)(__ccgo_up(bp + 4)) == 0 {
		if idx >= libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell) {
			return _sqlite3CorruptError(tls, int32(82746))
		}
		**(**int32)(__ccgo_up(bp)) = _sqlite3PagerWrite(tls, (*TMemPage)(unsafe.Pointer(pPage)).FpDbPage)
		if **(**int32)(__ccgo_up(bp)) != 0 {
			goto end_insert
		}
		oldCell = (*TMemPage)(unsafe.Pointer(pPage)).FaData + uintptr(libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FmaskPage)&(libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(pPage)).FaCellIdx + uintptr(int32(2)*idx))))<<libc.Int32FromInt32(8)|libc.Int32FromUint8(**(**Tu8)(__ccgo_up((*TMemPage)(unsafe.Pointer(pPage)).FaCellIdx + uintptr(int32(2)*idx) + 1)))))
		if !((*TMemPage)(unsafe.Pointer(pPage)).Fleaf != 0) {
			libc.Xmemcpy(tls, newCell, oldCell, uint64(4))
		}
		(*(*func(*libc.TLS, uintptr, uintptr, uintptr))(unsafe.Pointer(&struct{ uintptr }{(*TMemPage)(unsafe.Pointer(pPage)).FxParseCell})))(tls, pPage, oldCell, bp+128)
		if uint32((**(**TCellInfo)(__ccgo_up(bp + 128))).FnLocal) != (**(**TCellInfo)(__ccgo_up(bp + 128))).FnPayload {
			**(**int32)(__ccgo_up(bp)) = _clearCellOverflow(tls, pPage, oldCell, bp+128)
		} else {
			**(**int32)(__ccgo_up(bp)) = SQLITE_OK
		}
		v1 = pCur + 1
		*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) & ^libc.Int32FromInt32(BTCF_ValidOvfl))
		if libc.Int32FromUint16((**(**TCellInfo)(__ccgo_up(bp + 128))).FnSize) == **(**int32)(__ccgo_up(bp + 8)) && uint32((**(**TCellInfo)(__ccgo_up(bp + 128))).FnLocal) == (**(**TCellInfo)(__ccgo_up(bp + 128))).FnPayload && (!((*TBtShared)(unsafe.Pointer((*TBtree)(unsafe.Pointer(p)).FpBt)).FautoVacuum != 0) || **(**int32)(__ccgo_up(bp + 8)) < libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FminLocal)) {
			/* 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().
			 **
			 ** This optimization cannot be used on an autovacuum database if the
			 ** new entry uses overflow pages, as the insertCell() call below is
			 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry.  */
			/* clearCell never fails when nLocal==nPayload */
			if oldCell < (*TMemPage)(unsafe.Pointer(pPage)).FaData+uintptr((*TMemPage)(unsafe.Pointer(pPage)).FhdrOffset)+uintptr(10) {
				return _sqlite3CorruptError(tls, int32(82773))
			}
			if oldCell+uintptr(**(**int32)(__ccgo_up(bp + 8))) > (*TMemPage)(unsafe.Pointer(pPage)).FaDataEnd {
				return _sqlite3CorruptError(tls, int32(82776))
			}
			libc.Xmemcpy(tls, oldCell, newCell, libc.Uint64FromInt32(**(**int32)(__ccgo_up(bp + 8))))
			return SQLITE_OK
		}
		_dropCell(tls, pPage, idx, libc.Int32FromUint16((**(**TCellInfo)(__ccgo_up(bp + 128))).FnSize), bp)
		if **(**int32)(__ccgo_up(bp)) != 0 {
			goto end_insert
		}
	} else {
		if **(**int32)(__ccgo_up(bp + 4)) < 0 && libc.Int32FromUint16((*TMemPage)(unsafe.Pointer(pPage)).FnCell) > 0 {
			v1 = pCur + 86
			*(*Tu16)(unsafe.Pointer(v1)) = *(*Tu16)(unsafe.Pointer(v1)) + 1
			v2 = *(*Tu16)(unsafe.Pointer(v1))
			idx = libc.Int32FromUint16(v2)
			v1 = pCur + 1
			*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) & ^(libc.Int32FromInt32(BTCF_ValidNKey) | libc.Int32FromInt32(BTCF_ValidOvfl)))
		} else {
		}
	}
	**(**int32)(__ccgo_up(bp)) = _insertCellFast(tls, pPage, idx, newCell, **(**int32)(__ccgo_up(bp + 8)))
	/* 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.
	 **
	 ** Previous versions of SQLite called moveToRoot() to move the cursor
	 ** back to the root page as balance() used to invalidate the contents
	 ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
	 ** set the cursor state to "invalid". This makes common insert operations
	 ** slightly faster.
	 **
	 ** There is a subtle but important optimization here too. When inserting
	 ** multiple records into an intkey b-tree using a single cursor (as can
	 ** happen while processing an "INSERT INTO ... SELECT" statement), it
	 ** is advantageous to leave the cursor pointing to the last entry in
	 ** the b-tree if possible. If the cursor is left pointing to the last
	 ** entry in the table, and the next row inserted has an integer key
	 ** larger than the largest existing key, it is possible to insert the
	 ** row without seeking the cursor. This can be a big performance boost.
	 */
	if (*TMemPage)(unsafe.Pointer(pPage)).FnOverflow != 0 {
		v1 = pCur + 1
		*(*Tu8)(unsafe.Pointer(v1)) = Tu8(int32(*(*Tu8)(unsafe.Pointer(v1))) & ^(libc.Int32FromInt32(BTCF_ValidNKey) | libc.Int32FromInt32(BTCF_ValidOvfl)))
		**(**int32)(__ccgo_up(bp)) = _balance(tls, pCur)
		/* Must make sure nOverflow is reset to zero even if the balance()
		 ** 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.  */
		(*TMemPage)(unsafe.Pointer((*TBtCursor)(unsafe.Pointer(pCur)).FpPage)).FnOverflow = uint8(0)
		(*TBtCursor)(unsafe.Pointer(pCur)).FeState = uint8(CURSOR_INVALID)
		if flags&int32(BTREE_SAVEPOSITION) != 0 && **(**int32)(__ccgo_up(bp)) == SQLITE_OK {
			_btreeReleaseAllCursorPages(tls, pCur)
			if (*TBtCursor)(unsafe.Pointer(pCur)).FpKeyInfo != 0 {
				(*TBtCursor)(unsafe.Pointer(pCur)).FpKey = _sqlite3Malloc(tls, libc.Uint64FromInt64((*TBtreePayload)(unsafe.Pointer(pX)).FnKey))
				if (*TBtCursor)(unsafe.Pointer(pCur)).FpKey == uintptr(0) {
					**(**int32)(__ccgo_up(bp)) = int32(SQLITE_NOMEM)
				} else {
					libc.Xmemcpy(tls, (*TBtCursor)(unsafe.Pointer(pCur)).FpKey, (*TBtreePayload)(unsafe.Pointer(pX)).FpKey, libc.Uint64FromInt64((*TBtreePayload)(unsafe.Pointer(pX)).FnKey))
				}
			}
			(*TBtCursor)(unsafe.Pointer(pCur)).FeState = uint8(CURSOR_REQUIRESEEK)
			(*TBtCursor)(unsafe.Pointer(pCur)).FnKey = (*TBtreePayload)(unsafe.Pointer(pX)).FnKey
		}
	}
	goto end_insert
end_insert:
	;
	return **(**int32)(__ccgo_up(bp))
	return r
}

// C documentation
//
//	/*
//	** 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
//	** 4-byte big-endian integers, as follows:
//	**
//	**     0: Page number.
//	**     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)
//	**    16: Checksum-1.
//	**    20: Checksum-2.
//	*/
func _walEncodeFrame(tls *libc.TLS, pWal uintptr, iPage Tu32, nTruncate Tu32, aData uintptr, aFrame uintptr) {
	var aCksum uintptr
	var nativeCksum int32
	_, _ = aCksum, nativeCksum /* True for native byte-order checksums */
	aCksum = pWal + 72 + 24
	_sqlite3Put4byte(tls, aFrame, iPage)
	_sqlite3Put4byte(tls, aFrame+4, nTruncate)
	if (*TWal)(unsafe.Pointer(pWal)).FiReCksum == uint32(0) {
		libc.Xmemcpy(tls, aFrame+8, pWal+72+32, uint64(8))
		nativeCksum = libc.BoolInt32(libc.Int32FromUint8((*TWal)(unsafe.Pointer(pWal)).Fhdr.FbigEndCksum) == SQLITE_BIGENDIAN)
		_walChecksumBytes(tls, nativeCksum, aFrame, int32(8), aCksum, aCksum)
		_walChecksumBytes(tls, nativeCksum, aData, libc.Int32FromUint32((*TWal)(unsafe.Pointer(pWal)).FszPage), aCksum, aCksum)
		_sqlite3Put4byte(tls, aFrame+16, **(**Tu32)(__ccgo_up(aCksum)))
		_sqlite3Put4byte(tls, aFrame+20, **(**Tu32)(__ccgo_up(aCksum + 1*4)))
	} else {
		libc.Xmemset(tls, aFrame+8, 0, uint64(16))
	}
}
