%D \module
%D   [       file=page-ini,
%D        version=2000.10.20,
%D          title=\CONTEXT\ Page Macros,
%D       subtitle=Initializations, 
%D         author=Hans Hagen,
%D           date=\currentdate,
%D      copyright={PRAGMA / Hans Hagen \& Ton Otten}]
%C
%C This module is part of the \CONTEXT\ macro||package and is
%C therefore copyrighted by \PRAGMA. See mreadme.pdf for
%C details.

\writestatus{loading}{Context Page Macros / Initializations} 

%D This class of modules implements the output routines and 
%D floating body support. Although the modules are relatively 
%D new, the code herein is rather old. This reordering was 
%D needed when column sets were implemented and sharing code 
%D started to make sense. 

%D The history shows from the code, since both column 
%D mechanism use a different way of looping over columns. 

\unprotect

% message will be distributed 

\startmessages  dutch  library: systems
  title: systeem
      1: laden hulpfile uitgesteld (typemode)
      2: -- geladen
%     3: probeer LaTeX eens
      4: commando -- is al gedefinieerd
      5: macro's uit module -- geladen
      6: geen macro's in module -- gevonden
      7: macro's uit module -- reeds geladen
      8: nieuwe versie hulpfile, tweede run nodig
      9: -- niet gevonden/geplaatst
     10: gebruik geen em in --
     11: aanmaken basale hulpfile
     12: de hulpfile is niet gesorteerd, gebruik texutil
     13: markering -- gedefinieerd --
     14: geforceerde paginaovergang in lijst voor --
     15: wegschrijven buffer --
     16: inlezen buffer --
     17: verbatim inlezen buffer --
     18: synoniem -- -- bestaat niet
     19: betekenissen (synoniemen) van -- geladen
     20: betekenissen (sorteren) van -- geladen
     21: de hulpfile is niet geladen
     22: gebruik een goede hulpfile
     23: -- gearrangeerd op --
     24: Plaatsblokken
     25: Verwijzingen
     26: Registers
     27: Versie
\stopmessages

\startmessages  english  library: systems
  title: system
      1: loading utility-file postponed (typemode)
      2: -- loaded
%     3: try LaTeX
      4: command -- is already defined
      5: macros of module -- loaded
      6: no macros found in module --
      7: macros of module -- already loaded
      8: new version of utility file, second pass needed
      9: -- not found/processed
     10: don't use em in --
     11: building simple util
     12: the utility-file is not sorted, use texutil
     13: mark -- defined --
     14: forced newpage in list at --
     15: saving buffer --
     16: typesetting buffer --
     17: typesetting verbatim buffer --
     18: synonym -- -- does not exist
     19: meaning (synonyms) of -- loaded
     20: meaning (sorts) of -- loaded
     21: no utility data is loaded
     22: use a valid utilityfile
     23: -- arranged at --
     24: Floatblocks
     25: References
     26: Registers
     27: Version
\stopmessages

\startmessages  german  library: systems
  title: system
      1: Laden der Hilfsdatei verschoben (tippenmodus)
      2: -- geladen
%     3: Versuche LaTeX
      4: Befehl -- ist bereits definiert
      5: Makros aus Modul -- geladen
      6: Keine Makros in Modul -- gefunden
      7: Makros aus Modul -- bereits geladen
      8: Neue Version der Hilfsdatei, zweiter Durchlauf benoetigt
      9: -- nicht gefunden/verarbeitet
     10: Benutzte kein em in --
     11: Erstelle einfache Hilfdatei
     12: Die Hilfdatei ist nicht sortiert, verwende texutil
     13: Beschriftung -- definiert --
     14: Erzwungendes Seitenumbruch in Liste bei --
     15: Speichere Buffer --
     16: Setzte Buffer --
     17: Setzte tippen-Buffer --
     18: Synonym -- -- existiert nicht
     19: Bedeutung (synonyme) von -- geladen
     20: Bedeutung (sortieren) von -- geladen
     21: Die Hilfsdatei ist nicht geladen
     22: Benoetige gueltige Hilfsdateie
     23: -- angeordnet auf --
     24: Fliessbloecke
     25: Referenzen
     26: Register
     27: Version
\stopmessages

\startmessages  czech  library: systems
  title: system
      1: nacteni pomocneho souboru odlozeno (typemode)
      2: -- nacteno
%     3: zkuste LaTeX
      4: prikaz -- je jiz definovan
      5: makra z -- nactena
      6: zadna makra v -- nenalezena
      7: makra z -- jsou jiz nactena
      8: nova verze pomocneho souboru, je treba druheho behu
      9: -- nenalezeno/nezpracovano
     10: nepouzivejte em v --
     11: vytvarim jednoduchy pomocny soubor
     12: pomosny soubor neni setriden, pouzijte texutil
     13: znacka -- definovana --
     14: vynucena nova stranka v seznamu na --
     15: uklada se buffer --
     16: sazi se buffer --
     17: sazi se doslovny (verbatim) buffer --
     18: synonymum -- -- neexistuje
     19: vyznam (synonyma) -- nacten
     20: vyznam (trideni) -- nacten
     21: pomocny soubor necten
     22: pouzijte platny pomocny soubor
     23: -- upraveno na --
     24: plovouci bloky
     25: reference
     26: registry
     27: verze
\stopmessages

\startmessages  italian  library: systems
  title: sistema
      1: caricamento dei file supplementari posticipato (typemode)
      2: -- caricato
%     3: provare LaTeX
      4: comando -- già definito
      5: macro del modulo -- caricate
      6: nessuna macro trovata nel modulo --
      7: macro del modulo -- già caricate
      8: nuova versione del file supplementare, seconda passata necessaria
      9: -- non trovato/elaborato
     10: non usare em in --
     11: costruzione di un semplice supplemento
     12: file di supplemento non ordinato, usare texutil
     13: marcatura -- definita --
     14: nuova pagina obbligata in lista a --
     15: salvataggio del buffer --
     16: composizione del buffer --
     17: composizione verbatim del buffer --
     18: sinonimo -- -- non esistente
     19: significato (sinonimi) di -- caricato
     20: significato (specie) di -- caricato
     21: nessuna informazione supplementare caricata
     22: usare un file supplementare valido
     23: -- sistemato a --
     24: Oggetti mobili
     25: Riferimenti
     26: Registri
     27: Versione
\stopmessages

\startmessages  norwegian  library: systems
  title: system
      1: innlesning av hjelpefila utsatt (typemode)
      2: -- er lest inn
%     3: forsøker LaTeX
      4: kommando -- er allerede definert
      5: makroene i modul  -- er lest inn
      6: ingen makroer funnet i modul ---
      7: makroene i modul -- er allerede lest inn
      8: ny versjon av hjelpefil, andre gjennomkjøring nødvendig
      9: -- ikke funnet/behandlet
     10: ikke bruk em i --
     11: lager enkel hjelpefil
     12: hjelpefila er ikke sortert, bruk texutil
     13: markering -- definert --
     14: tvunget sideskift i liste ved --
     15: lagrer Buffer --
     16: tegnsetter buffer --
     17: tegnsetter verbatim-buffer --
     18: synonym -- -- eksisterer ikke
     19: betydning (synonymer) av -- er lest inn
     20: betydning (sorterer) av -- er lest inn
     21: hjelpefila er ikke lest inn
     22: bruk en gyldig hjelpefil
     23: -- arrangert på --
     24: Flytblokker
     25: Referanser
     26: Registere
     27: Versjon
\stopmessages

\startmessages  romanian  library: systems
  title: sistem
      1: se incarca utilitarul-fisierul este amanat (typemode)
      2: -- s-a incarcat
%     3: incercati LaTeX
      4: comanda -- este deja definita
      5: macro-urile din modulul -- s-au incarcat
      6: nu s-au gasit macro-uri in modulul --
      7: macro-urile din modulul -- s-au incarcat deja
      8: o noua versiune de fisier utilitar, este necesara o noua trecere
      9: -- nu este gasit/procesat
     10: nu folositi em in --
     11: se creeaza un utilitar simplu
     12: fisierul utilitar nu este sortat, folositi texutil
     13: marcajul -- definit --
     14: s-a fortat trecere pa pagina noua in lista la --
     15: buffer salvat --
     16: buffer-ul -- s-a cules
     17: se culege buffer-ul verbatim --
     18: sinonimul -- -- nu exista
     19: intelesul (sinonimele) pentru -- incarcat
     20: intelesul (ordinea) pentru -- incarcat
     21: nici o data utilitara nu este incarcata
     22: folositi un fisier utilitar valid
     23: -- aranjat la --
     24: Blocuri
     25: Referinte
     26: Registri
     27: Versiune
\stopmessages

\startmessages  dutch  library: layouts
  title: layout
      1: teksthoogte aangepast met -- op pagina --
      2: -- maal uitgestelde tekst tussengevoegd
      3: -- maal tekst plaatsen uitstellen
      4: margeblokken actief
      5: margeblokken inactief
      6: subpagina reeks -- verwerkt (aantal --)
%      7: beeldmerken berekenen
%      8: achtergronden berekenen
     10: -- en -- tellen niet op tot 1.0
     11: interlinie -- niet toegestaan in gridmode
\stopmessages

\startmessages  english  library: layouts
  title: layout
      1: textheight adapted with -- at page --
      2: -- times postponed text placed
      3: -- times text postponed
      4: marginblocks active
      5: marginblocks inactive
      6: subpage set -- processed (size --)
%      7: calculating logospace
%      8: calculating backgrounds
     10: -- and -- don't add up to 1.0
     11: spacing -- not permitted in gridmode
\stopmessages

\startmessages  german  library: layouts
  title: Layout
      1: Texthoehe angepasst mit -- auf Seite --
      2: -- mal verschobener Text plaziert
      3: -- mal Text verschoben
      4: marginalbloecke aktiv
      5: marginalbloecke inaktiv
      6: Unterseitenfolge -- verarbeitet (Groesse --)
%      7: berechne Platz des Logo
%      8: berechne Hintergrund
     10: -- und -- ergeben zusammen nicht 1.0
     11: Zwischenraum -- nicht im Grittermoduserlau
\stopmessages

\startmessages  czech  library: layouts
  title: layout
      1: vyska textu prizpusobena s -- na strane --
      2: -- krat odlozeny text umisten
      3: -- krat text odlozen
      4: okrajove bloky aktivni
      5: okrajove bloky neaktivni
      6: sada stran -- zpracovana (velikost --)
%      7: pocita se misto pro logo
%      8: pocita se pozadi
     10: -- a -- nedava dohromady 1.0
     11: svisla mezera -- neni povolena v pevnem radkovem rejstriku
\stopmessages

\startmessages  italian  library: layouts
  title: layout
      1: altezza del testo adattata con -- a pagina --
      2: posizionato testo posticipato -- volte
      3: testo posticipato -- volte
      4: blocchi in margine attivi
      5: blocchi in margine inattivi
      6: gruppo di sottopagine -- elaborato (dimensione --)
%      7: calcolo dello spazio per logo
%      8: calcolo dello sfondo
     10: -- e -- non sommano a 1.0
     11: spaziatura -- non permessa in modo griglia
\stopmessages

\startmessages  norwegian  library: layouts
  title: layout
      1: teksthøyde tilpasset med -- på side --
      2: -- ganger forskjøvet tekst plassert
      3: -- ganger tekst forskjøvet 
      4: margblokker aktive
      5: margblokker inaktive
      6: delside sett -- behandlet (størrelse --)
%      7: beregner plass for logo
%      8: beregner bakgrunn
     10: -- og -- er ikke 1.0 til sammen
     11: mellomrom -- ikke tillatt i gridmodus
\stopmessages

\startmessages  romanian  library: layouts
  title: aranjamente
      1: textheight adaptat cu -- la pagina --
      2: textul amanat de -- ori a fost plasat
      3: textul amanat de -- ori 
      4: blocuri marginale active
      5: blocuri marginale inactive
      6: setul -- de subpagini procesat (dimensiunea --)
%      7: se calculeaza spatiul pentru logo
%      8: se calculeaza fundalurile
     10: -- si -- nu se adauga pana la 1.0
     11: spatierea -- nu este permisa in gridmode
\stopmessages

\def\m!otr{otr}

\chardef\normalpagebox=255

\newbox\pagebox

\ifx\recalculatelayout\undefined

  \let \recalculatelayout \relax

\fi 

\ifx\recalculatelogos\undefined

  \let \recalculatelogos  \relax
  \let \addlogobackground \gobbleoneargument % <box>

\fi 

\ifx\recalculatebackgrounds\undefined

  \let \recalculatebackgrounds \relax
  \let \addmainbackground      \gobbleoneargument % <box>
  \let \addtextbackground      \gobbleoneargument % <box>
  \let \addpagebackground      \gobbleoneargument % <box>
  \let \addprintbackground     \gobbleoneargument % <box>
  \let \addstatusinfo          \gobbleoneargument % <box>

\fi 

\ifx\realpageno\undefined

  \countdef\realpageno\zerocount \realpageno\plusone

\fi 

\ifx\realfolio\undefined 

  \def\realfolio{\the\realpageno} 
 
\fi

\newcount\nofshipouts

\appendtoks
  \global\advance\nofshipouts\plusone
\to \everyaftershipout
      
% principle:
%
% multiple otr's
%
% (1) single column, simple routine (old one)
% (2) multi column, collect and split routine (old one)
% (3) multi column, page by page (new one, needed for taco)
% (4) single column, spread handling (for fun)
% (5) multi column, page by page, spread handling (as challenge)
%
% common components
%
% (1) float placement
% (2) float flushing
% (3) page body building
% (4) ...
%
% ort
%
% + balancing
% - mixed / one / multi / balancetofit
% + backgrounds
% + pre / post
% + distances / heights
% + ragged / baseline / normal
% - pos sync
% - last page
%
% - itemize / subtexts -> old mechanism
%
% floats
%
% - top / bottom / side / page / column / spead
% - flush / packed flush / current page / next page / area
%
% footnotes
%
% + carry over pre column / local to column
% + last column / pre last column / each column
% - multiple classes
% - area / page / end
%
% areas
%
% - top / bottom / mid in spread
%
% IMPORTANT
%
% switchtobodyfont in between ivm top

% floats:
%
% tricky in balancing mode, a la huidige multi columns

\startmessages  dutch  library: columns
  title: kolommen
      1: maximaal -- kolommen
      2: gebruik eventueel \string\filbreak
      3: probleempje, probeer [balanceren=nee]
      4: plaatsblok boven nog niet mogelijk
      5: plaatsblok onder nog niet mogelijk
      6: -- plaatsblok(en) opgeschort
      7: balanceren afgebroken na 100 stappen
      8: gebalanceerd in -- stap(pen)
      9: uitlijnen controleren!
     10: (minder dan) 1 regel over
     11: plaatsblok te breed voor kolom
     12: plaatsblok verplaatst naar volgende kolom / --
     13: breed figuur geplaatst boven kolommen
\stopmessages

\startmessages  english  library: columns
  title: columns
      1: only -- columns possible
      2: use \string\filbreak\space as alternative
      3: problems, disable balancing
      4: top float not yet supported
      5: bottom float not yet supported
      6: -- float(s) postponed
      7: balancing aborted after 100 steps
      8: balanced in -- step(s)
      9: check raggedness
     10: (less than) 1 line left
     11: float to wide for column
     12: float moved to next column / --
     13: wide float moved to top of columns
\stopmessages

\startmessages  german  library: columns
  title: Spalten
      1: nur -- Spalten moeglich
      2: benutzte \string\filbreak\space als Alternative
      3: Problem, verwende [ausgleich=nein]
      4: Gleitobjekt oben ncoh nicht unterstuetzt
      5: Gleitobjekt unten ncoh nicht unterstuetzt
      6: -- Gleitobjekt(e) verschoben
      7: ausgleich nach 100 Schritten abgebrocheb
      8: ausgeglichen nach  -- Schritt(en)
      9: Ausrichtung ueberpruefen
     10: (weniger als) 1 Zeile uebrig
     11: Gleitobjekt zu breit fuer Spalte
     12: Gleitobjekt in naechste Zeile verschoben / --
     13: breites Gleitobjekt an den Anfang der Spalten verschoben
\stopmessages

\startmessages  czech  library: columns
  title: sloupce
      1: je mozno pouze -- sloupcu
      2: pouzijte \string\filbreak\space jako alternativu
      3: problem, vypina se vyvazovani
      4: horni plovouci objekt jeste neni podporovan
      5: spodni plovouci objekt jeste neni podporovan
      6: -- plovouci objekt(y) odlozeny
      7: vyvazovani ukonceno po 100 krocich
      8: vyvazeno v -- krocich
      9: kontrola nerovnost
     10: zbyl (mene nez) 1 radek
     11: plovouci objekt je pro sloupec prilis siroky
     12: plovouci objekt je presunut do nasledujiciho sloupce / -- 
     13: siroky plovouci objekt je presunut nad sloupce
\stopmessages

\startmessages  italian  library: columns
  title: colonne
      1: solo -- colonne possibili
      2: in alternativa, usare \string\filbreak
      3: problemi, disabilitare il bilanciamento
      4: float in cima non ancora supportato
      5: float in fondo non ancora supportato
      6: -- float(s) posticipate
      7: bilanciamento annullato dopo 100 passi
      8: bilanciamento in -- passo/i
      9: controllare seghettamento
     10: (meno di) una riga rimasta
     11: oggetto mobile troppo ampio per la colonna
     12: oggetto mobile spostata alla colonna successiva / --
     13: oggetto mobile ampio spostato sopra le colonne
\stopmessages

\startmessages  norwegian  library: columns
  title: kolonner
      1: maksimalt -- kolonner
      2: bruk \string\filbreak\space som et alternativ
      3: problemer, slår av balansering
      4: flytblokker øverst er ikke støttet enda
      5: flytblokker nedert er ikke støttet enda
      6: -- flytblokk forskjøvet
      7: balansering avbrutt etter 100 iterasjoner
      8: balansert etter -- iterasjoner
      9: kontroller tekstlayout!
     10: (mindre enn) 1 linje igjen
     11: flytblokk for bredt for kolonna
     12: flytblokk forskjøvet til neste kolonne / --
     13: bred flytblokk forksjøvet til toppen av kolonnene
\stopmessages

\startmessages  romanian  library: columns
  title: coloane
      1: este posibil numai -- coloane
      2: folositi \string\filbreak\space ca alternativa
      3: probleme, se dezactiveaza alinierea
      4: cadrele top (top float) nu sunt inca suportate
      5: cadrele bottom (bottom float) nu sunt inca suportate
      6: -- blocurile sunt amanate
      7: alinierea este oprita dupa 100 de incercari
      8: aliniat in  -- pas(i)
      9: verificat alinierea
     10: a mai ramas (mai putin de) 1 linie
     11: blocul este prea lat pentru coloana
     12: blocul este mutat pe urmatoarea coloana / --
     13: blocul lat este mutat in partea de sus a coloanelor
\stopmessages

%D In case we're not running \ETEX, we need to bypass a 
%D couple of primitives.  

\beginTEX \...discards

  \chardef \savingvdiscards \zerocount
  \let     \splitdiscards   \relax   
  \let     \pagediscards    \relax    

\endTEX

% ONE = single column 
% MUL = multi column
% SET = columns sets 

\def\@@OTR{OTR}

\let\OTRdefault\empty

\beginETEX \ifcsname

\def\OTRcommand#1%
  {\csname\@@OTR
     \ifcsname\@@OTR\OTRidentifier\strippedcsname#1\endcsname
       \OTRidentifier
     \else\ifcsname\@@OTR\OTRdefault\strippedcsname#1\endcsname % fallback 
       \OTRdefault 
     \fi\fi
   \strippedcsname#1\endcsname}

\endETEX

\beginTEX

\def\OTRcommand#1%
  {\csname\@@OTR
     \@EA\ifx\csname\@@OTR\OTRidentifier\strippedcsname#1\endcsname\relax
       \@EA\ifx\csname\@@OTR\OTRdefault\strippedcsname#1\endcsname\relax % fallback 
       \else
         \OTRdefault
       \fi
     \else
       \OTRidentifier
     \fi
   \strippedcsname#1\endcsname}

\endTEX

% obsolete 

\def\installotr#1% andere naam, beter \connectotr of zo
  {\def\OTRidentifier{#1}}

\def\activateotr#1#2%
  {\def\OTRidentifier{#1}%
   \def\OTRdefault   {#2}}

%D The initialization of the \type {\hsize} and \type {\vsize}
%D depends on the OTR used. 

\def\setvsize             {\OTRcommand\setvsize}
\def\sethsize             {\OTRcommand\sethsize}
\def\finalsidefloatoutput {\OTRcommand\finalsidefloatoutput}
\def\dopagecontents       {\OTRcommand\dopagecontents}

\def\dosettopinserts      {\OTRcommand\dosettopinserts}
\def\dosetbotinserts      {\OTRcommand\dosetbotinserts}
\def\dotopinsertions      {\OTRcommand\dotopinsertions}
\def\dobotinsertions      {\OTRcommand\dobotinsertions}
\def\dosetbothinserts     {\OTRcommand\dosetbothinserts}

\def\doflushfloats        {\OTRcommand\doflushfloats}
\def\flushfloatbox        {\OTRcommand\flushfloatbox}
\def\docheckiffloatfits   {\OTRcommand\docheckiffloatfits}
   
\def\someherefloat        {\OTRcommand\someherefloat}
\def\somefixdfloat        {\OTRcommand\somefixdfloat}
\def\somepagefloat        {\OTRcommand\somepagefloat}
\def\sometopsfloat        {\OTRcommand\sometopsfloat}
\def\somebotsfloat        {\OTRcommand\somebotsfloat}
\def\somesidefloat        {\OTRcommand\somesidefloat}

\def\flushsavedfloats     {\OTRcommand\flushsavedfloats}

\def\gotonextpage         {\OTRcommand\gotonextpage }
\def\gotonextpageX        {\OTRcommand\gotonextpageX} % will become obsolete 

% beter een \installotr#1 met #1 = macro en auto test 

\newif   \iftraceotr 
\newif   \ifinotr
\newtoks \mainoutput 
\newcount\otrlevel 

% When issuing two \par\penalty-\@M's, only the first 
% triggers the otr; obscure feature or optimization?  

\def\outputcounter{-100010} % -10010 

\def\doinvokeoutput
  {\iftraceotr
     \expandafter\dodotracedoutput
   \else
     \expandafter\dodoinvokeoutput
   \fi}

\def\outputmessage#1#2#3%
  {\iftraceotr\writestatus\m!otr{#1 #2 \number#3}\fi}

\def\dodoinvokeoutput#1%
  {\outputmessage+{special}{#1}%
   \bgroup\par\penalty#1\relax\egroup
   \outputmessage-{special}{#1}}

\def\dodotracedoutput#1%
  {\outputmessage+{traced}{#1/\the\outputpenalty}% 
   \writestatus\m!otr{c:\number\mofcolumns,v:\the\vsize,g:\the\pagegoal,t:\the\pagetotal}%
   \dodoinvokeoutput{#1}%
   \writestatus\m!otr{c:\number\mofcolumns,v:\the\vsize,g:\the\pagegoal,t:\the\pagetotal}%
   \outputmessage-{traced}{#1/\the\outputpenalty}}

\def\installoutput#1#2% \invoke \action 
  {\decrement\outputcounter
   \edef#1{\noexpand\doinvokeoutput{\outputcounter}}% 
   \setvalue{\@@OTR\outputcounter}{#2}}

\def\invokeoutputroutine
  {\outputmessage+{trying}\outputpenalty
   \executeifdefined{\@@OTR\the\outputpenalty}\dodonormaloutput
   \outputmessage-{trying}\outputpenalty}

\def\dodonormaloutput
  {\outputmessage+{normal}\outputpenalty
   \the\OTRcommand\output
   \outputmessage-{normal}\outputpenalty}

\mainoutput{\invokeoutputroutine} \output{\inotrtrue\the\mainoutput}

\installoutput\synchronizeoutput
  {\ifvoid\normalpagebox\else\unvbox\normalpagebox\fi}

%D In order to force consistent use of variables, we 
%D predefine a lot of them here. 

%D The next two registers can be used to store pre column 
%D material as well as footnotes or so. 

\newbox\precolumnbox   \newdimen\precolumnboxheight
\newbox\postcolumnbox  \newdimen\postcolumnboxheight

%D We reserve a counter for the number of columns as well as 
%D the current column. Both are not to be changed by users! 

\newcount\nofcolumns \nofcolumns = 1
\newcount\mofcolumns \mofcolumns = 1

\chardef\maxnofcolumns       = 50 
\chardef\allocatednofcolumns =  0

%D The next dimensions reports the final column height 

\newdimen\finalcolumnheights 
\newcount\finalcolumnlines

%D During initialization the temporary boxes are allocated.
%D This enables us to use as much columns as we want, without
%D exhausting the pool of boxes too fast. We could have packed
%D them in one box, but we've got enough boxes.
%D
%D Two sets of boxes are declared, the txtboxes are used for
%D the text, the topboxes are for moved column floats.

\def\@col@{@col@}

\def\initializecolumns#1%
  {\ifnum#1>\maxnofcolumns
     \showmessage\m!columns1\maxnofcolumns
     \nofcolumns\maxnofcolumns
   \else
     \nofcolumns#1\relax
   \fi
   \ifnum\nofcolumns>\allocatednofcolumns
     \dorecurse\nofcolumns
       {\ifnum\recurselevel>\allocatednofcolumns\relax
          % \newbox\next \letgvalue{\@col@-\recurselevel-t}=\next
          \@EA\newbox\csname\@col@-\recurselevel-t\endcsname % text
          \@EA\newbox\csname\@col@-\recurselevel-f\endcsname % foot
          \@EA\newbox\csname\@col@-\recurselevel-h\endcsname % top insert
          \@EA\newbox\csname\@col@-\recurselevel-l\endcsname % top insert
        \fi}%
     \global\chardef\allocatednofcolumns=\nofcolumns
   \fi}

\def\firstcolumnbox     {\columntextbox\plusone}
\def\currentcolumnbox   {\columntextbox\mofcolumns}
\def\lastcolumnbox      {\columntextbox\nofcolumns}

\def\firsttopcolumnbox  {\columntopbox \plusone}
\def\currenttopcolumnbox{\columntopbox \mofcolumns}
\def\lasttopcolumnbox   {\columntopbox \nofcolumns}

\def\columntextbox#1{\csname\@col@-\number#1-t\endcsname}
\def\columnfootbox#1{\csname\@col@-\number#1-f\endcsname}
\def\columntopbox #1{\csname\@col@-\number#1-h\endcsname}
\def\columnbotbox #1{\csname\@col@-\number#1-l\endcsname}

\def\columnsettextbox{\global\setbox\columntextbox}
\def\columnsetfootbox{\global\setbox\columnfootbox}
\def\columnsettopbox {\global\setbox\columntopbox}
\def\columnsetbotbox {\global\setbox\columnbotbox}

\def\columngettextbox{\copy\columntextbox}
\def\columngetfootbox{\copy\columnfootbox}
\def\columngettopbox {\copy\columntopbox}
\def\columngetbotbox {\copy\columnbotbox}

\def\columnerasetextboxes{\dorecurse\allocatednofcolumns{\columnsettextbox\recurselevel\emptybox}}
\def\columnerasefootboxes{\dorecurse\allocatednofcolumns{\columnsetfootbox\recurselevel\emptybox}}
\def\columnerasetopboxes {\dorecurse\allocatednofcolumns{\columnsettopbox \recurselevel\emptybox}}
\def\columnerasebotboxes {\dorecurse\allocatednofcolumns{\columnsetbotbox \recurselevel\emptybox}}

%D Without going in details we present two macro's which handle
%D the columns. The action which is transfered by the the first
%D and only parameter can do something with \type
%D {\currentcolumnbox}. In case of the mid columns, \type
%D {\firstcolumnbox} and \type {\lastcolumnbox} are handled
%D outside these macro's. 

\def\dohandlecolumn#1%
  {\mofcolumns\recurselevel
   \let\currentcolumn\recurselevel
   #1\relax}

\def\dohandleallcolumns#1%
  {\dorecurse\nofcolumns{\dohandlecolumn{#1}}}

\def\dohandlerevcolumns#1%
  {\dostepwiserecurse\nofcolumns\plusone\minusone{\dohandlecolumn{#1}}}

\def\dohandlemidcolumns#1%
  {\dohandleallcolumns
     {\ifnum\recurselevel>\plusone 
        \ifnum\recurselevel<\nofcolumns
          \dohandlecolumn{#1}%
        \fi
      \fi}}

%D This register can be used as a temporary storage for page 
%D content.  

\newbox\restofpage

%D Features.

\newif\ifintermediatefootnotes 
\newif\ifcarryoverfootnotes  %\carryoverfootnotestrue
\newif\iflastcolumnfootnotes %\lastcolumnfootnotestrue
\newif\ifbalancecolumns      %\balancecolumnstrue
\newif\ifbalancetoheight     %\balancetoheighttrue
\newif\ifforcecolumngrid      \forcecolumngridtrue
\newif\ifstretchcolumns       \stretchcolumnsfalse
\newif\ifinheritcolumns       \inheritcolumnsfalse
\newif\ifheightencolumns      \heightencolumnsfalse

\newif\ifbalancingcolumns     
\newif\ifcollectingcontent     
\newif\ifcolumnoverflow
\newif\iffinalflushingfloats
\newif\ifpackflushedfloats   \packflushedfloatstrue % for the moment 

\newdimen\intercolumnwidth
\newdimen\localcolumnwidth
\newdimen\savedpagetotal

\chardef\columndirection=0   % 0:lr 1:rl

\def\minbalancetoplines      {1}
\def\minfreecolumnlines      {2}

\newif\ifrecentercolumnbox    \recentercolumnboxtrue
\newif\ifrerecentercolumnbox  \rerecentercolumnboxtrue
\newif\ifpackcolumnfloats     \packcolumnfloatstrue

\newbox\collectedpagefloats

%D The \type {\ifdim} test is needed, because otherwise the
%D last line of a text end up on top of the baseline instead of
%D on the baseline, as is the case with preceding pages. 
%D Also, a \type {\vfil} better than a \type {\vfill}. 

\def\eject         {\par\penalty-\@M } % == {\par\break} % plain 
\def\supereject    {\par\penalty-\@MM} % also plain 

\def\doejectpage   {\par\ifdim\pagetotal>\pagegoal\else\normalvfil\fi}
\def\ejectpage     {\doejectpage\eject}
\def\superejectpage{\doejectpage\supereject}

% floats 

\def\ejectinsert
  {\flushnotes
   \bgroup
   \noftopfloats\!!thousand
   \nofbotfloats\zerocount
   \doflushfloats
   \egroup}

\def\ejectdummypage
  {\ejectinsert 
   \hardespatie % will be different 
   \vfill
   \gotonextpage}

\def\beforefinaloutput
  {}

\def\afterfinaloutput
  {\forgetall
   \vskip\zeropoint\relax
   \ifvoid\normalpagebox \else
     \unvbox\normalpagebox
     \penalty\outputpenalty
   \fi
   % not really needed, replaced by \flushsavedfloats 
   \ifnum\outputpenalty>-\@MM \else % better use a proper otr signal
     \dosupereject 
   \fi
   % but does not hurt either 
   \inpagebodytrue      % needed for enabling \blanko !
   \flushsavedfloats    % was \dosetbothinserts; only otr one !  
   \setvsize            % this is needed for interacting components, like floats and multicolumns
   \adaptfuzzypagegoal} % watch this hack!

\def\dofinaloutput#1#2%
  {\beforefinaloutput
   \the\everybeforeshipout
   \ifspecialbasedsettings
     \myshipout{\hbox{\hbox to \zeropoint{\the\pageboundsettings}%
                      \hbox{\dopagebody#1#2\setpagecounters}}}%
   \else
     \the\pageboundsettings
     \myshipout{\hbox{\dopagebody#1#2\setpagecounters}}%
   \fi
   \the\everyaftershipout
   \afterfinaloutput
   \popcolor}  % ... and here ...

\def\donofinaloutput#1#2%
  {\beforefinaloutput
   \the\everybeforeshipout
   \setpagecounters
   \message{[-\the\realpageno]}%
   \setbox\scratchbox\hbox
     {%\the\everyshipout % still needed here ? 
      \dopagebody#1#2}%
   \deadcycles\zerocount
   \gotonextrealpage
   \the\everyaftershipout
   \afterfinaloutput
   \popcolor}  % ... and here

\def\finaloutput#1#2%
  {\checkpageversion
   \ifverwerken
     \ifgeselecteerd
       \@EAEAEA\dofinaloutput
     \else
       \@EAEAEA\donofinaloutput
     \fi
   \else
     \ifgeselecteerd
       \@EAEAEA\donofinaloutput
     \else
       \@EAEAEA\dofinaloutput
     \fi
   \fi#1#2%
   \resetselectiepagina
   \verhoogpaginanummer
   \checkpagedimensions
   \ifnum\outputpenalty>-\@MM \else
     \dosupereject
   \fi
   \doflushspread 
   \douitstellen}

\ifx\doflushspread\undefined \let\doflushspread\relax \fi 

\def\dooutput
  {\finaloutput\unvbox\normalpagebox}

\maxdeadcycles=1000

% will be installable tracer 

\newif\ifvoorlopig \voorlopigfalse
\newif\ifconcept   \conceptfalse

\def\doplaatsversieaanduiding#1#2%
  {\doifsomething{#2}
     {\@EA\convertargument#2\to\ascii
      \ #1: \ascii\
      \!!doneatrue}}

\def\plaatsversieaanduiding% nog engels maken
  {\ifvoorlopig
     \vskip\!!sixpoint
     \hbox to \zetbreedte
       {\infofont
        \getmessage\m!systems{27}: \currentdate\
        \doplaatsversieaanduiding{Project}\currentproject
        \doplaatsversieaanduiding{Produkt}\currentproduct
        \doplaatsversieaanduiding{Onderdeel}\currentcomponent
        \if!!donea\else\ File: \jobname\fi
        \hss\reportpagedimensions}%
   \fi
   \ifconcept
     \vskip\!!sixpoint
     \hbox to \zetbreedte
       {\infofont
        Concept: \currentdate
        \hss\reportpagedimensions}%
   \fi}

% tot hier

\def\doversie[#1]%
  {\voorlopigfalse
   \conceptfalse
   \overfullrule\zeropoint
   \processaction
     [#1]
     [\v!voorlopig=>\voorlopigtrue\overfullrule5pt,
        \v!concept=>\concepttrue]}

\def\versie
  {\dosingleargument\doversie}

%\def\addstatusinfo#1%
%  {\ifvoorlopig \donetrue  \else 
%   \ifconcept   \donetrue  \else 
%                \donefalse \fi \fi 
%   \ifdone 
%     \setbox#1=\vbox to \papierhoogte
%       {\vsmashbox#1\box#1 
%        \offinterlineskip
%        \vskip\kopwit 
%        \hsize\papierbreedte
%        \hfill\hbox{\plaatstestinfo\hskip.5cm}\vss
%        \settexthoffset\hskip\texthoffset
%        \tlap{\plaatsversieaanduiding}
%        \vskip.5cm}%
%   \fi} 

\def\addstatusinfo
  {\ifvoorlopig
     \@EA\doaddstatusinfo
   \else\ifconcept  
     \@EAEAEA\doaddstatusinfo
   \else
     \@EAEAEA\gobbleoneargument
   \fi\fi}

\def\doaddstatusinfo#1%
  {\setbox#1\vbox to \papierhoogte
     {\vsmashbox#1\box#1 
      \offinterlineskip
      \vskip\kopwit 
      \hsize\papierbreedte
      \hfill\hbox{\plaatstestinfo\hskip.5cm}\vss
      \settexthoffset\hskip\texthoffset
      \tlap{\plaatsversieaanduiding}
      \vskip.5cm}}

\def\dotestinfo#1#2#3%
  {\ifvoorlopig\ifinpagebody\else
     \begingroup
       \@EA\convertargument#3\to\ascii
       \xdef\extratestinfo
         {#2 \ascii}%
       \gdef\totaltestinfo
         {\global\setbox#1\vbox
            {\unvbox#1\relax 
             \infofont \stelinterliniein
             \hbox
               {\strut
                \expandafter\doboundtext\expandafter
                   {\extratestinfo}{12em}{..}%
                \quad}}}%
     \endgroup
     \ifinner
       \aftergroup\totaltestinfo
     \else
       \totaltestinfo
     \fi
   \fi\fi}

% this will be inserts some day

% \installinsertion\referentieinfobox 
% \installinsertion\registerinfobox   
% \installinsertion\floatinfobox      

\newbox\referentieinfobox
\newbox\registerinfobox
\newbox\floatinfobox

\def\referentieinfo{\dotestinfo\referentieinfobox}
\def\registerinfo  {\dotestinfo\registerinfobox}
\def\floatinfo     {\dotestinfo\floatinfobox}

\def\plaatstestinfo
  {\ifvoorlopig
     \vbox to \zethoogte
       {\forgetall
        \infofont
        \hsize10em
        \ifvoid\floatinfobox\else
          \strut \getmessage\m!systems{24}%
          \vskip\!!sixpoint
          \unvbox\floatinfobox
          \vskip\!!twelvepoint
        \fi
        \ifvoid\referentieinfobox\else
          \strut \getmessage\m!systems{25}%
          \vskip\!!sixpoint
          \unvbox\referentieinfobox
          \vskip\!!twelvepoint
        \fi
        \ifvoid\registerinfobox\else
          \strut \getmessage\m!systems{26}%
          \vskip\!!sixpoint
          \unvbox\registerinfobox
        \fi
        \vss}
   \fi}

\versie[\v!definitief]

% De volgende macro's worden gedefinieerd in de module
% colo-ini. Om resetten bij twee maal laden te voorkomen
% checken we wel even. Anders krijgen we een mark-build-up.

\newif\ifinpagebody

\ifx\pushcolor\undefined 
  \let \pushcolor      \relax
  \let \popcolor       \relax
  \let \startcolorpage \relax
  \let \stopcolorpage  \relax
\fi 

% bewaren tvb documentatie
%
% \hbox to \hsize
%   {\en
%    \switchnaarkorps[5pt]%
%    \emergencystretch2em
%    \dimen0=\baselineskip
%    \baselineskip=\dimen0 plus 1pt
%    \hsize=.2\hsize
%    \vsize=2\hsize
%    \ruledvbox to \vsize{\input tufte \par}\hss
%    \ruledvbox to \vsize{\input tufte \par\kern-\prevdepth}\hss
%    \ruledvbox to \vsize{\input tufte \par\kern0pt}\hss
%    \ruledvbox to \vsize{\input tufte \par\vfill}\hss
%    \ruledvbox to \vsize{\input tufte \par\kern-\prevdepth\vfill}}
%
% \hbox to \hsize
%   {\en
%    \switchnaarkorps[5pt]%
%    \emergencystretch2em
%    \dimen0=\baselineskip
%    \baselineskip=\dimen0 plus 1pt
%    \hsize=.18\hsize
%    \vsize=2.5\hsize
%    \setbox0=\vbox{\input tufte\relax}%
%    \ruledvbox to \vsize{\unvcopy0}\hss
%    \ruledvbox to \vsize{\unvcopy0\kern-\dp0}\hss
%    \ruledvbox to \vsize{\unvcopy0\kern0pt}\hss
%    \ruledvbox to \vsize{\unvcopy0\vfill}\hss
%    \ruledvbox to \vsize{\unvcopy0\kern-\dp0\vfill}}

\newtoks\afterpage     \newtoks\aftereverypage
\newtoks\beforepage    \newtoks\beforeeverypage

\chardef\showgridstate=0 

\def\showgrid
  {\dosingleempty\doshowgrid}

\def\doshowgrid[#1]%
  {\chardef\showgridstate\plusone % downward compatible default
   \processaction
     [#1]%
     [\v!reset=>\chardef\showgridstate0,
     %\v!onder=>\chardef\showgridstate1,%
      \v!boven=>\chardef\showgridstate2]}

\def\buildpagebox#1%
  {\setbox#1\vbox to \papierhoogte
     {\hsize\papierbreedte
      \vskip\kopwit
      \doifbothsides
        \hskip\rugwit
      \orsideone
        \hskip\rugwit
      \orsidetwo
        \hskip\papierbreedte
        \hskip-\rugwit
        \hskip-\zetbreedte
      \od
      \box#1}%
   \dp#1\zeropoint}

\newif\ifpagebodyornaments \pagebodyornamentstrue
\newif\ifarrangingpages    \arrangingpagesfalse

\appendtoks 
  \global\pagebodyornamentstrue
\to \everyaftershipout 

\let\poparrangedpages\relax
\let\pusharrangedpage\relax

\let\shiftprintpagebox\gobbleoneargument
\let\shiftpaperpagebox\gobbleoneargument

\def\reportarrangedpage#1%
  {\showmessage\m!systems
     {23}{\the\realpageno.\the\pageno\ifnum\subpageno>0 .\the\subpageno\fi,#1}}

\newif\ifsavepagebody \newbox\savedpagebody

\def\buildpagebody#1#2%
  {\ifsavepagebody\global\setbox\savedpagebody\fi 
   \vbox
     {\beginrestorecatcodes
      \forgetall  % igv problemen, check: \boxmaxdepth\maxdimen
      \boxmaxdepth\maxdimen % new
      \mindermeldingen
      \setbox\pagebox\vbox
        {\offinterlineskip
         \ifpagebodyornaments
%           \getbackgroundbox
%           \getlogobox
           \bgroup % else footnotes get inconsistent font/baseline
           % \doconvertfont\@@lyletter\empty 
             \dostartattributes\??ly\c!letter\c!kleur\empty
               \offinterlineskip 
               \gettextboxes
             \dostopattributes
           \egroup
         \fi
         \getmainbox#1#2}% including footnotes 
      \ifpagebodyornaments
        \addmainbackground \pagebox
        \addlogobackground \pagebox
      \fi
      \buildpagebox        \pagebox
      \addstatusinfo       \pagebox
      \ifpagebodyornaments
        \addpagebackground \pagebox
      \fi
      \ifarrangingpages 
        \shiftpaperpagebox \pagebox % \v!papier
      \else
        \clippagebox       \pagebox
        \addpagecutmarks   \pagebox   
        \replicatepagebox  \pagebox
        \scalepagebox      \pagebox
        \mirrorpaperbox    \pagebox
        \rotatepaperbox    \pagebox
        \addpagecolormarks \pagebox 
        \centerpagebox     \pagebox
        \addprintbackground\pagebox
        \mirrorprintbox    \pagebox
        \rotateprintbox    \pagebox
        \shiftprintpagebox \pagebox % \v!pagina
        \offsetprintbox    \pagebox
        \negateprintbox    \pagebox
      \fi
      \box\pagebox
      \endrestorecatcodes}%
   \ifsavepagebody\copy\savedpagebody\fi}

\def\finishpagebox#1%
  {\ifarrangingpages
     \addpagecutmarks  #1% 
     \addpagecolormarks#1%
     \centerpagebox    #1%
     \mirrorprintbox   #1%
     \rotateprintbox   #1%
     \offsetprintbox   #1%
     \negateprintbox   #1%
   \fi}

\appendtoks \restoreglobalbodyfont \to \everybeforepagebody
\appendtoks \restorecolumnsettings \to \everybeforepagebody

\def\dopagebody#1#2%
  {%\getallmarks % now in following token register  
   \the\everybeforepagebody
   \startcolorpage
   \gotonextsubpage  % nog eens: als in pagina (tbv standaard opmaak)
   \dontshowboxes    % dan hier blokkeren en verderop resetten
   \naastpagina
   \checkreferences
   \checkmargeblokken
   \dotoks\beforeeverypage
   \flushtoks\beforepage
   \inpagebodytrue\buildpagebody#1#2%
   \flushtoks\afterpage
   \dotoks\aftereverypage
   \resetpagebreak
   \updatelistreferences
   \resetlayoutlines % will go to \aftereverypage
   \stopcolorpage
   \the\everyafterpagebody}

\newtoks\pageboundsettings

\prependtoks \initializepaper \to \pageboundsettings

\let\checkpageversion=\relax

% not here 

\newif\ifpaginageblokkeerd
\paginageblokkeerdfalse

\def\testpagina[#1][#2]%
  {\relax % needed ! 
   \ifpaginageblokkeerd \else
     \ifdim\pagegoal<\maxdimen 
       \ifdim\pagetotal<\pagegoal % \relax
         \scratchdimen\lineheight
         \multiply\scratchdimen#1\relax
         \advance\scratchdimen \pagetotal
         \ifdim\lastskip<\parskip
           \advance\scratchdimen \parskip
         \fi
         \advance\scratchdimen#2\relax
         \ifdim\scratchdimen>.99\pagegoal
           \penalty-\!!tenthousand\relax
         \fi
       \fi 
     \else
       \goodbreak
     \fi
   \fi}

\let\resetcurrentsectionmarks\relax

% was: \resetsectionmarks\firstsection, zie \handelpaginaaf

\def\page  {\pagebreak} % the short form of \pagebreak (mult-com one)  
\def\pagina{\pagebreak} % for the moment, keep this one

\def\resetpagebreak
  {\global\paginageblokkeerdfalse}

\def\simplifypagebreak
  {\def\pagebreak{\goodbreak}}

\def\executepagebreakhandler#1%
  {\edef\@@pagespecification{#1}%
   \doifdefinedelse{\??pe:\@@pagespecification}
     {\getvalue{\??pe:\@@pagespecification}}
     {\doifdefinedelse{\??pe::\@@pagespecification}
        {\executepagebreakhandlers{\getvalue{\??pe::\@@pagespecification}}}
        {\getvalue{\??pe:\s!unknown}}}}

\long\def\installpagebreakhandler#1#2%
  {\long\setvalue{\??pe:#1}{#2}}

\definecomplexorsimple\pagebreak

\def\simplepagebreak
  {\flushnotes
   \executepagebreakhandler\v!ja}

\def\complexpagebreak[#1]% if empty, do nothing and avoid processing, 
  {\flushnotes        % see head's; watch how we group 
   \doifsomething{#1}{\bgroup\executepagebreakhandlers{#1}\egroup}} 

\def\executepagebreakhandlers#1%
  {\processcommacommand[#1]\executepagebreakhandler}

\installpagebreakhandler \s!unknown
  {\doifinstringelse{+}\@@pagespecification
     {\ejectinsert
      \gotonextpage
      \dorecurse\@@pagespecification\ejectdummypage}
     {\doifnumberelse\@@pagespecification
        {\ejectinsert
         \gotonextpage
         \doloop
           {\ifnum\userpageno<\@@pagespecification\relax
              \ejectdummypage
            \else
              \exitloop
            \fi}}
        {}}}

\installpagebreakhandler \s!default
  {} % do nothing if empty

\installpagebreakhandler  \v!reset
  {\global\paginageblokkeerdfalse}

\installpagebreakhandler \v!blokkeer
  {\global\paginageblokkeerdtrue}

\installpagebreakhandler \v!ja
  {\ifpaginageblokkeerd\else
     \ejectinsert
     \gotonextpage 
     \ifbinnenkolommen % this will move to MUL 
       \ejectpage  % anders soms geen overgang
     \fi
   \fi}

\installpagebreakhandler \v!opmaak % ?? 
  {\ifpaginageblokkeerd\else
     \eject
   \fi}

\installpagebreakhandler \v!blanko
  {\global\pagebodyornamentsfalse}

\installpagebreakhandler \v!nee
  {\ifpaginageblokkeerd\else
     \dosomebreak\nobreak
   \fi}

\installpagebreakhandler \v!voorkeur
  {\ifpaginageblokkeerd\else
     \ifbinnenkolommen % this will move to MUL  
       \dosomebreak\goodbreak
     \else
       \testpagina[3][\zeropoint]%
     \fi
    \fi}

\installpagebreakhandler \v!grotevoorkeur
  {\ifpaginageblokkeerd\else
     \ifbinnenkolommen % this will move to MUL
       \dosomebreak\goodbreak
     \else
       \testpagina[5][\zeropoint]%
     \fi
   \fi}

\installpagebreakhandler \v!leeg
  {\ejectinsert
   \gotonextpage
   \doifnotvalue{\??tk\v!hoofd\c!status}\v!stop
     {\setupheader[\c!status=\v!leeg]}%
   \doifnotvalue{\??tk\v!voet\c!status}\v!stop
     {\setupfooter[\c!status=\v!leeg]}%
   \ejectdummypage}

\installpagebreakhandler \v!links
  {\ejectinsert
   \gotonextpageX % will become \gotonextpage
   \doifbothsidesoverruled
   \orsideone
     \resetcurrentsectionmarks
     \ejectdummypage
   \orsidetwo
   \od}

\installpagebreakhandler \v!rechts
  {\ejectinsert
   \gotonextpageX % will become \gotonextpage
   \doifbothsidesoverruled
   \orsideone
   \orsidetwo
     \resetcurrentsectionmarks
     \ejectdummypage
   \od}

\installpagebreakhandler \v!even
  {\pagina
   \doifoddpageelse
     {\resetcurrentsectionmarks\ejectdummypage}\donothing}

\installpagebreakhandler \v!oneven
  {\pagina
   \doifoddpageelse
     \donothing{\resetcurrentsectionmarks\ejectdummypage}}

\installpagebreakhandler \v!viertal % not yet ok inside columnsets 
  {\ifdubbelzijdig
     \!!counta\realpageno
     \!!countb\realpageno
     \divide\!!counta 4
     \divide\!!countb 2
     \ifnum\!!counta=\!!countb
     \else
       \executepagebreakhandler\v!ja
       \executepagebreakhandler\v!leeg
       \executepagebreakhandler\v!leeg
     \fi
   \fi}

\installpagebreakhandler \v!laatste
  {\ejectinsert
   \gotonextpageX % will become \gotonextpage
   \relax
   \doifbothsidesoverruled
     \naastpagina
   \orsideone
   \orsidetwo
     \noheaderandfooterlines
     \ejectdummypage
   \od
   \filluparrangedpages}

% public page handler, beware: definepage already in use (core-ref) 
%
% \definepagebreak[instance][forsure]
% \definepagebreak[forsure][yes,+4]

\def\definepagebreak
  {\dodoubleargument\dodefinepagebreak}

\def\dodefinepagebreak[#1][#2]% non recursive, meant for simple mappings
  {\setvalue{\??pe::#1}{#2}}

% hier nog uti blokkeren

% don't change this / test case:
%
% \setupbackgrounds[state=repeat]
% \setupbackgrounds[text][text][background=whatever]
% \couplepage[chapter][before={\defineoverlay[whatever][ON]}]
% \setuphead[chapter][before={\pagetype[chapter]}] 
% \chapter{First} \page test \chapter{second} \page test 

\long\def\installcolumnbreakhandler#1#2#3% #1=otr-id #2=tag 
  {\long\setvalue{\??cn:#1:#2}{#3}}

\def\definecolumnbreak
  {\dodoubleargument\dodefinecolumnbreak}

\def\dodefinecolumnbreak[#1][#2]% non recursive, meant for simple mappings
  {\setvalue{\??cn::#1}{#2}}

%\def\columnbreak
%  {\dosingleempty\docolumnbreak}
%
%\def\docolumnbreak[#1]%
%  {\expanded{\nextcolumn[\executeifdefined{\??cn::#1}{#1}]}}

\definecomplexorsimple\columnbreak

\def\simplecolumnbreak
  {\executecolumnbreakhandler\v!ja}

\def\complexcolumnbreak[#1]% if empty, do nothing and avoid processing
  {\doifsomething{#1}{\executecolumnbreakhandlers{#1}}}   

\def\executecolumnbreakhandlers#1%
  {\processcommacommand[#1]\executecolumnbreakhandler}

\def\executecolumnbreakhandler#1% here no commalist 
  {\edef\@@columnspecification{#1}%
   \doifdefinedelse{\??cn:\OTRidentifier:\@@columnspecification}
     {\getvalue{\??cn:\OTRidentifier:\@@columnspecification}}
     {\doifdefinedelse{\??cn::\@@columnspecification}
        {\executecolumnbreakhandlers{\getvalue{\??cn::\@@columnspecification}}}
        {\getvalue{\??cn:\OTRidentifier:\s!unknown}}}}

%let\nextcolumn\columnbreak
\let\column    \columnbreak

\newif\ifgeselecteerd \geselecteerdtrue
\newif\ifselecteren   \selecterenfalse
\newif\ifverwerken    \verwerkentrue

\let\selectie   \empty
\let\paginasoort\empty
\let\naastpagina\relax
\let\napagina   \relax
\let\voorpagina \relax

\def\dodovoorpagina#1%
  {\global\let\voorpagina\relax
   \getvalue{\??pg#1\c!voor}}

\def\dovoorpagina
  {\doifsomething\paginasoort
     {\processcommacommand[\paginasoort]\dodovoorpagina}}

\def\dododonapagina#1%
  {\global\let\napagina\relax
   \global\let\paginasoort\empty
   \getvalue{\??pg#1\c!na}}

\def\dodonapagina#1%
  {\doifelsevalue{\??pg#1\c!optie}\v!dubbelzijdig
     {\doifbothsidesoverruled
        \dododonapagina{#1}%
      \orsideone
        \dododonapagina{#1}%
      \orsidetwo
      \od}
     {\dododonapagina{#1}}}

\def\donapagina
  {\doifsomething\paginasoort
     {\processcommacommand[\paginasoort]\dodonapagina}}

% Dit wordt eigenlijk nooit en moet worden vervangen door 
% het meer algemene mechanisme.

\def\dosoortpagina[#1]%
  {\edef\desoortpagina{#1}% 
   \ifx\desoortpagina\empty \else
     \@EA\doglobal\@EA\addtocommalist\@EA{\desoortpagina}\paginasoort
     \ifselecteren
       \fullexpandtwoargsafter\doifcommon\desoortpagina\selectie
         {\global\geselecteerdtrue}%
     \fi
     \gdef\voorpagina{\dovoorpagina}%
     \gdef\napagina  {\donapagina  }%
   \fi}

\def\soortpagina
  {\dosingleargument\dosoortpagina}

\def\dokoppelpagina[#1][#2]%
  {\getparameters
     [\??pg]
     [\c!voor=,
      \c!na=,
      \c!optie=,
      #2]%
   \def\docommando##1%
     {\getparameters
        [\??pg##1]
        [\c!voor=\@@pgvoor,
         \c!na=\@@pgna,
         \c!optie=\@@pgoptie]}%
   \processcommalist[#1]\docommando}%

\def\koppelpagina
  {\dodoubleargument\dokoppelpagina}

\def\doverwerkpagina[#1][#2]%
  {\processaction
     [#2]
     [ \v!ja=>\global\verwerkentrue,
      \v!nee=>\global\verwerkenfalse]%
   \gdef\selectie{#1}%
   \global\selecterentrue
   \global\geselecteerdfalse}

\def\verwerkpagina
  {\dodoubleargument\doverwerkpagina}

\def\resetselectiepagina
  {\ifselecteren
     \doifbothsidesoverruled
       \global\geselecteerdfalse
     \orsideone
     \orsidetwo
       \global\geselecteerdfalse
     \od
   \fi}

\newif\ifregistertextareas 
\newif\iftracetextareas

\newbox\registertextbox

% \def\registeredtextarea#1#2#3% #1=lower-dp #2=correct-ht #3=box 
%   {\hbox{\box#3}}

\def\enabletextarearegistration{\global\registertextareastrue}

\def\registeredtextarea#1#2#3% #1=lower-dp #2=correct-ht #3=box 
  {\hbox\bgroup
     \ifregistertextareas \ifx\registerMPtextarea\undefined \else 
       \setbox\registertextbox\null
       \wd\registertextbox\wd#3%
       \ht\registertextbox\ht#3%
       \dp\registertextbox\dp#3%
       \ifcase#1\or % 1
         \setbox\registertextbox\hbox{\lower\dp\strutbox\box\registertextbox}%
       \fi
       \ifcase#2\or % 1 
         \setbox\registertextbox\hbox{\raise\topskip\hbox{\lower\ht\strutbox\box\registertextbox}}%
         \dp\registertextbox\dp\strutbox
       \fi
       \dp\registertextbox\dp\strutbox % needed 
      %\setbox\registertextbox\hbox
      %  {\iftracetextareas\gray\boxrulewidth2pt\ruledhbox\fi
      %   {\registerMPtextarea{\box\registertextbox}}}%
       \setbox\registertextbox\hbox
         {\registerMPtextarea{\box\registertextbox}}%
       \smashbox\registertextbox
       \box\registertextbox
     \fi \fi 
     \box#3%
   \egroup}

\protect \endinput 
