
\startluacode
    document.foundsection = { first = 0, last  = 0 }

    function document.loadsection(filename,reference)
        local data = job.loadother(file.addsuffix(filename,"tuc"))
        if data then
            local lists = data.structures.lists.collected
            local pages = data.structures.pages.collected
            if lists and pages then
                for i=1,#lists do
                    local li = lists[i]
                    if li.references.reference == reference then
                        local first = 1
                        local last  = pages[#pages].number
                        local level = li.metadata.level
                        first = li.references.realpage
                        for j=i+1,#lists do
                            local lj = lists[j]
                            if lj.metadata.level == level then
                                last = lj.references.realpage - 1
                                break
                            end
                        end
                        document.foundsection.first = first
                        document.foundsection.last  = last
                    end
                end
            end
        end
    end
\stopluacode

% it depends what interface one wants ... we could have
%
% \externalfigure[crap.pdf][section=<reference>] % takes from crap
%
% but we need more inpiut and discussion for that

\starttexdefinition DoWithSection #1#2
    \startpagemakeup
        \externalfigure[#1.pdf][page=#2]
    \stoppagemakeup
\stoptexdefinition

\starttexdefinition LoadSectionsA #1#2
    \ctxlua{document.loadsection("#1","#2")}
    \doifnot{\cldcontext{document.foundsection.first}} {0} {
        \dostepwiserecurse
            {\cldcontext{document.foundsection.first}}
            {\cldcontext{document.foundsection.last}}
            {1}
            {
                \DoWithSection{#1}{\recurselevel}
            }
    }
\stoptexdefinition

\starttexdefinition spaces LoadSectionsB #1#2
    \ctxlua{
        document.loadsection("#1","#2")
        if document.foundsection.first > 0 then
            for i=document.foundsection.first,document.foundsection.last do
                context.DoWithSection("#1",i)
            end
        end
    }
\stoptexdefinition

\starttext

    \LoadSectionsA{crap}{chapter:3}

    \LoadSectionsB{crap}{chapter:2}

\stoptext
