%D \module
%D   [       file=mtx-context-copy,
%D        version=2008.11.10, % about that time i started playing with this
%D          title=\CONTEXT\ Extra Trickry,
%D       subtitle=Copying Files,
%D         author=Hans Hagen,
%D           date=\currentdate,
%D      copyright={PRAGMA ADE \& \CONTEXT\ Development Team}]
%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=copy [options] list-of-files
%
% --interaction         : add hyperlinks
%
% end help

\continuewhenlmtxmode

\input mtx-context-common.tex

\setupexternalfigures
  [directory=]

\definepapersize
  [fit]
  [width=\figurewidth,
   height=\figureheight]

\setuplayout
  [page]

\doif {\getdocumentargument{interaction}} {yes} {
    \setupinteraction
      [state=start]
    \setupexternalfigures
      [interaction=yes]
}

\doif {\getdocumentargument{tracelinks}} {yes} {
    \enabletrackers[figures.links]
%     \enabletrackers[refer*]
%     \enabletrackers[dest*]
}

\starttexdefinition CopyPages #1

    \filterpages[#1][all][alternative=page]

\stoptexdefinition

\starttexdefinition CopyEntry #1#2#3#4

    \doifelsesomething {#4} {
        \setupinteraction
          [state=start]
        \setupexternalfigures
          [interaction={#4}]
        \writestatus
            {filter pages}
            {file #1, first page #2, last page #3, interaction '#4'}

    } {
        \setupinteraction
          [state=stop]
        \setupexternalfigures
          [interaction=]
        \writestatus
            {filter pages}
            {file #1, first page #2, last page #3}
    }

    \filterpages[#1][#2:#3][alternative=page]

\stoptexdefinition

\starttext

% return {
%     comment = "tugboat 137",
%     list    = {
%         {
%             filename    = "tb137complete",
%             first       = 1,
%             last        = 1,
%             interaction = "all"
%             pageoffset  = -1,
%
%         },
%         {
%             filename    = "issue",
%             first       = 2,
%             last        = 123,
%             interaction = "all"
%         },
%         {
%             filename    = "issue",
%             first       = 124,
%             last        = 125,
%             interaction = "all"
%             pageoffset  = -1,
%         },
%     },
% }

\startluacode

    local find = string.find

    if #document.files == 0 then
        context("no files given")
    elseif document.arguments.template then
        local filename = file.addsuffix(document.files[1],"lua")
        local template = table.load(filename)
        if template then
            local list = template.list
            if type(list) == "table" then
                for i=1,#list do
                    local entry       = list[i]
                    local filename    = entry.filename or ""
                    local first       = tonumber(entry.first) or 1
                    local last        = tonumber(entry.last)  or "*"
                    local interaction = entry.interaction or ""
                    local pageoffset  = tonumber(entry.pageoffset)
                    local minheight   = tonumber(entry.minheight)
                    if interaction ~= "" then
                        if pageoffset then
                            interaction = interaction .. ",pageoffset:" .. pageoffset
                        end
                        if minheight then
                            interaction = interaction .. ",minheight:" .. minheight
                        end
                    end
                    context.CopyEntry(filename,first,last,interaction)
                end
            end
        else
            logs.report("copy","invalid or missing template file")
        end
    else
        if document.arguments.pattern then
            document.files = dir.glob(document.arguments.pattern)
        end
        for i=1,#document.files do
            local filename = document.files[i]
            if not find(filename,"^mtx%-context%-") and not find(filename,"^context%-extra") then
                logs.report("copy",filename)
                context.CopyPages(filename)
            end
        end
    end

\stopluacode

\stoptext

% def copyoutput
%     copyortrim(false,'copy')
% end

% def trimoutput
%     copyortrim(true,'trim')
% end

% def copyortrim(trim=false,what='unknown')
%     if job = TEX.new(logger) then
%         prepare(job)
%         job.cleanuptemprunfiles
%         files =  if @commandline.option('sort') then @commandline.arguments.sort else @commandline.arguments end
%         if files.length > 0 then
%             if f = File.open(job.tempfilename('tex'),'w') then
%                 scale = @commandline.checkedoption('scale')
%                 begin
%                     scale = (scale.to_f * 1000.0).to_i if scale.to_i < 10
%                 rescue
%                     scale = 1000
%                 end
%                 scale = scale.to_i
%                 paperoffset = @commandline.checkedoption('paperoffset', '0cm')
%                 f << "\\starttext\n"
%                 files.each do |filename|
%                     result = @commandline.checkedoption('result','texexec')
%                     begin
%                         if (filename !~ /^texexec/io) && (filename !~ /^#{result}/) then
%                             report("copying file: #{filename}")
%                             f <<  "\\getfiguredimensions\n"
%                             f <<  "  [#{filename}]\n"
%                             f <<  "  [scale=#{scale},\n"
%                             f <<  "   page=1,\n"
%                             f <<  "   size=trimbox\n" if trim
%                             f <<  "]\n"
%                             f <<  "\\definepapersize\n"
%                             f <<  "  [copy]\n"
%                             f <<  "  [width=\\figurewidth,\n"
%                             f <<  "   height=\\figureheight]\n"
%                             f <<  "\\setuppapersize\n"
%                             f <<  "  [copy][copy]\n"
%                             f <<  "\\setuplayout\n"
%                             f <<  "  [page]\n"
%                             f <<  "\\setupexternalfigures\n"
%                             f <<  "  [directory=]\n"
%                             f <<  "\\copypages\n"
%                             f <<  "  [#{filename}]\n"
%                             f <<  "  [scale=#{scale},\n"
%                             f <<  "   marking=on,\n" if @commandline.option('markings')
%                             f <<  "   size=trimbox,\n" if trim
%                             f <<  "   offset=#{paperoffset}]\n"
%                         end
%                     rescue
%                         report("wrong specification")
%                     end
%                 end
%                 f << "\\stoptext\n"
%                 f.close
%                 job.setvariable('interface','english')
%                 job.setvariable('simplerun',true)
%                 # job.setvariable('nooptionfile',true)
%                 job.setvariable('files',[job.tempfilename])
%                 job.processtex
%             else
%                 report("no files to #{what}")
%             end
%         else
%             report("no files to #{what}")
%         end
%         job.cleanuptemprunfiles
%     end
% end
