+// flush cache pages to main btree
+
+BTERR bt_flushmain (BtDb *bt)
+{
+uint count, cnt = 0;
+BtPageSet set[1];
+
+ while( bt->mgr->pagezero->leafpages > 0 ) {
+ if( set->latch = bt_pinleaf (bt->mgr, LEAF_page, bt->thread_no) )
+ set->page = bt_mappage (bt->mgr, set->latch);
+ else
+ return bt->mgr->err;
+
+ bt_lockpage(BtLockWrite, set->latch, bt->thread_no, __LINE__);
+ count = set->page->cnt;
+
+ if( !set->page->right )
+ count--;
+
+if( !(cnt++ % 100) )
+fprintf(stderr, "Promote LEAF_page %d with %d keys\n", cnt, set->page->act);
+
+ if( bt_atomicexec (bt->main, set->page, count, 0, bt->mgr->pagezero->redopages ? 1 : 0, bt->thread_no) )
+ return bt->mgr->line = bt->main->line, bt->mgr->err = bt->main->err;
+
+ if( set->page->right )
+ if( bt_deletepage (bt->mgr, set, bt->thread_no, 0) )
+ return bt->mgr->err;
+ else
+ continue;
+
+ bt_unlockpage(BtLockWrite, set->latch, bt->thread_no, __LINE__);
+ bt_unpinlatch (set->latch, 0, bt->thread_no, __LINE__);
+ return 0;
+ }
+
+ // leaf page count is off
+
+ bt->mgr->err_thread = bt->thread_no, bt->mgr->line = __LINE__;
+ return bt->mgr->err = BTERR_ovflw;
+}
+