% engine=luatex

%D \module
%D   [       file=mtx-context-arrange,
%D        version=2009.03.21,
%D          title=\CONTEXT\ Extra Trickry,
%D       subtitle=Arrange Files,
%D         author=Hans Hagen,
%D           date=\currentdate,
%D      copyright=\PRAGMA]
%C
%C This module is part of the \CONTEXT\ macro||package and is
%C therefore copyrighted by \PRAGMA. See mreadme.pdf for
%C details.

%D This is a \TEXEXEC\ features that has been moved to \MKIV.

% begin help
%
% usage: context --extra=arrange [options] list-of-files
%
% --sort                  : sort filenames first
% --paperoffset=dimension : left-top-offset
% --noduplex              : singlesided (doublesided is default)
% --backspace=dimension   : extra left offset
% --topspace=dimension    : extra top offset
% --marking               : add cutmarks
% --addempty=list         : add empty pages at/after (comma separated list)
% --printformat           : 2UP, etc
%
% end help

\doifdocumentargument {paperoffset} {
    \definepapersize
      [offset=\getdocumentargument{paperoffset}]
}

\doifdocumentargumentelse {noduplex} {yes} {
    \setuppagenumbering
        [alternative=doublesided]
    \setdocumentargument{sided}{doublesided}
} {
    \setdocumentargument{sided}{singlesided}
}

\setdefaultdocumentargument {textwidth} {0cm}
\setdefaultdocumentargument {backspace} {0cm}
\setdefaultdocumentargument {topspace}  {0cm}

\setuplayout
    [backspace=\getdocumentargument{backspace},
     topspace=\getdocumentargument{topspace},
     width=middle,
     height=middle,
     location=middle,
     header=0pt,
     footer=0pt]

\doifdocumentargument {marking} {yes} {
    \setuplayout
        [marking=on]
}

\startluacode
    local printformat = document.arguments.printformat or ""
    if printformat == "" then
        printformat = "normal"
    elseif string.find(printformat,".*up") then
        printformat = "2UP,\\v!rotated"
    elseif string.find(printformat,".*down") then
        printformat = "2DOWN,\\v!rotated"
    elseif string.find(printformat,".*side") then
        printformat = "2SIDE,\\v!rotated"
    end
    document.setargument("printformat",printformat)
\stopluacode

\setuparranging
  [\getdocumentargument{sided},
   \getdocumentargument{printformat}]

\starttext

\startluacode
    local format = string.format
    local fprint = function(...) tex.sprint(tex.ctxcatcodes,format(...)) end

    if #document.files > 0 then
        if document.arguments.sort then
            table.sort(document.files)
        end
        local emptypages = document.arguments.addempty or ""
        local textwidth = document.arguments.textwidth or "0cm"
        for _, filename in ipairs(document.files) do
            if not string.find(filename,"^mtx%-context%-") then
                fprint("\\insertpages[%s][%s][width=%s]",filename,emptypages,textwidth)
            end
        end
    else
        fprint("no files given")
    end
\stopluacode

\stoptext

