if not modules then modules = { } end modules ['core-env'] = {
    version   = 1.001,
    comment   = "companion to core-env.mkiv",
    author    = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
    copyright = "PRAGMA ADE / ConTeXt Development Team",
    license   = "see context related readme files"
}

-- maybe this will move to the context name space although the
-- plurals are unlikely to clash with future tex primitives
--
-- if tex.modes['xxxx'] then .... else .... end

local rawset = rawset

local P, C, S, lpegmatch, patterns = lpeg.P, lpeg.C, lpeg.S, lpeg.match, lpeg.patterns
local gmatch = string.gmatch

local context              = context
local ctxcore              = context.core

local texgetintegervalue   = token.getinteger -- todo

local allocate             = utilities.storage.allocate
local setmetatableindex    = table.setmetatableindex
local setmetatablenewindex = table.setmetatablenewindex
local setmetatablecall     = table.setmetatablecall

local createtoken          = token.create
local expandmacro          = token.expandmacro

local isdefined            = tokens.isdefined

texmodes                   = allocate { }  tex.modes        = texmodes
texsystemmodes             = allocate { }  tex.systemmodes  = texsystemmodes
texconstants               = allocate { }  tex.constants    = texconstants
texconditionals            = allocate { }  tex.conditionals = texconditionals
texifs                     = allocate { }  tex.ifs          = texifs
texisdefined               = allocate { }  tex.isdefined    = texisdefined

local implement            = interfaces.implement

-- we could use the built-in tex.is[count|dimen|skip|toks] here but caching
-- at the lua end is not that bad (and we need more anyway)

local cache = tokens.cache

-- we can have a modes cache too

local commandcodes  = tokens.commands

local iftrue        <const> = cache["iftrue"].index

local conditioncode <const> = commandcodes.if_test
local integercode   <const> = commandcodes.integer

-- local dimencode     <const> = commandcodes.register_dimension
-- local countcode     <const> = commandcodes.register_integer
-- local tokencode     <const> = commandcodes.register_toks
-- local skipcode      <const> = commandcodes.register_glue
-- local muskipcode    <const> = commandcodes.register_mu_glue
--
-- local types = {
--     [dimencode]     = "dimen",
--     [countcode]     = "count",
--     [tokencode]     = "token",
--     [skipcode]      = "skip",
--     [muskipcode]    = "muskip",
--  -- [attributecode] = "attribute",
--     [conditioncode] = "condition",
--     [integercode]   = "integer",
-- }

-- setmetatableindex(texmodes, function(t,k)
--     local m = modes[k]
--     if not m then
--         local n = "mode>" .. k
--         m = function() return texgetintegervalue(n) == 1 end
--         rawset(modes,k,m)
--     end
--     return m()
-- end)

-- setmetatableindex(texsystemmodes, function(t,k)
--     local m = systemmodes[k]
--     if not m then
--         local n = "mode>*" .. k
--         m = function() return texgetintegervalue(n) == 1 end
--         rawset(modes,k,m)
--     end
--     return m()
-- end)

do

    local modes       = { }
    local systemmodes = { }

    local texiscount  = tex.iscount
    local texgetcount = tex.getcount

    local boolean_value <const> = tokens.values.boolean

    local function nomode()
        return false
    end

    setmetatableindex(texmodes, function(t,k)
        local m = modes[k]
        if not m then
            local n = "mode>" .. k
            local i = texiscount(n)
            if i then
                m = i and function() return texgetcount(i) == 1 end or nomode
                rawset(modes,k,m)
            else
                return false
            end
        end
        return m()
    end)

    setmetatableindex(texsystemmodes, function(t,k)
        local m = systemmodes[k]
        if not m then
            local n = "mode>*" .. k
            local i = texiscount(n)
            if i then
                m = i and function() return texgetcount(i) == 1 end or nomode
                rawset(systemmodes,k,m)
            else
                return false
            end
        end
        return m()
    end)

    local c_trialtypesetting <const> = texiscount("mode>*trialtypesetting")

    context.settrialtypesettingmethod(function()
     -- return texsystemmodes.trialtypesetting
        -- upto three times faster:
        return texgetcount(c_trialtypesetting) == 1
    end)

    implement {
        name      = "ifmode",
        public    = true,
        usage     = "condition",
        arguments = "argument",
        actions   = function(m)
            return boolean_value, texmodes[m]
        end
    }

    implement {
        name      = "ifsystemmode",
        public    = true,
        usage     = "condition",
        arguments = "argument",
        actions   = function(m)
            return boolean_value, texsystemmodes[m]
        end
    }

--     local settings_to_array = utilities.parsers.settings_to_array

--     local cache = setmetatableindex(function(t,k)
--         local v = settings_to_array(k)
--         if #v < 2 then
--             v = false
--         end
--         t[k] = v
--         return v
--     end)

    local cache = utilities.parsers.hashes.settings_to_list

    implement {
        name      = "ifmodes",
        public    = true,
        usage     = "condition",
        arguments = "argument",
        actions   = function(m)
            local c = cache[m]
            local n = #c
            if n > 1 then
                for i=1,n do
                    if texmodes[c[i]] then
                        return boolean_value, true
                    end
                end
                return boolean_value, false
            else
                return boolean_value, texmodes[m]
            end
        end
    }

    implement {
        name      = "ifallmodes",
        public    = true,
        usage     = "condition",
        arguments = "argument",
        actions   = function(m)
            local c = cache[m]
            if c then
                for i=1,#c do
                    if not texmodes[c[i]] then
                        return boolean_value, false
                    end
                end
                return boolean_value, true
            else
                return boolean_value, texmodes[m]
            end
        end
    }

end

do

    local namespace = interfaces.getnamespace("setup")

    implement {
        name      = "ifsetups",
        public    = true,
        usage     = "condition",
        arguments = "argument",
        actions   = function(m)
            return boolean_value, isdefined(namespace .. m)
        end
    }

end

-- also a call method

local report = logs.reporter("system")

setmetatablenewindex(texmodes,        function(t,k) report("you cannot set the %s named %a this way","mode",       k) end)
setmetatablenewindex(texsystemmodes,  function(t,k) report("you cannot set the %s named %a this way","systemmode", k) end)
setmetatablenewindex(texconstants,    function(t,k) report("you cannot set the %s named %a this way","constant",   k) end)
setmetatablenewindex(texconditionals, function(t,k) report("you cannot set the %s named %a this way","conditional",k) end)
setmetatablenewindex(texifs,          function(t,k) end)

-- if we really need performance we can have a dedicated cache for each
-- kind of variable ... maybe we no longer have to cache anyway (in lmtx)

setmetatableindex(texconstants, function(t,k)
    return cache[k].command == integercode and texgetintegervalue(k) or 0
end)

do

    setmetatableindex(texconditionals, function(t,k) -- 0 == true
        return cache[k].command == integercode and texgetintegervalue(k) == 0
    end)

    -- We can't use tex.setintegervalue because overload protection
    -- kicks in; we have to use proper assignments.

    local hash = table.setmetatableindex(function(t,k)
        local v = createtoken(k)
        t[k] = v
        return v
    end)

 -- local settrue  = createtoken("settrue")
 -- local setfalse = createtoken("setfalse")

 -- function tex.setconditional(name,v)
 --     expandmacro(v and settrue or setfalse,hash[name])
 -- end

    local conditionaltrue  = createtoken("conditionaltrue")
    local conditionalfalse = createtoken("conditionalfalse")

    function tex.setconditional(name,v)
        expandmacro(hash[name],v and conditionaltrue or conditionalfalse)
    end

end

setmetatableindex(texifs, function(t,k)
    local c = cache[k]
    return c.command == conditioncode and c.index == iftrue
end)

tex.isdefined = isdefined

-- function tex.type(name)
--     return types[cache[name].command] or "macro"
-- end

function context.setconditional(name,value)
    if value then
        ctxcore.settruevalue(name)
    else
        ctxcore.setfalsevalue(name)
    end
end

function context.setmode(name,value)
    if value then
        ctxcore.setmode(name)
    else
        ctxcore.resetmode(name)
    end
end

function context.setsystemmode(name,value)
    if value then
        ctxcore.setsystemmode(name)
    else
        ctxcore.resetsystemmode(name)
    end
end

context.modes        = texmodes
context.systemmodes  = texsystemmodes
context.conditionals = texconditionals
-------.constants    = texconstants
-------.ifs          = texifs

do

    local sep = S("), ")
    local str = C((1-sep)^1)
    local tag = P("(") * C((1-S(")" ))^1) * P(")")
    local arg = P("(") * C((1-S("){"))^1) * P("{") * C((1-P("}"))^0) * P("}") * P(")")

    local pattern = (
         P("lua") * tag        / ctxcore.luasetup
      +  P("xml") * arg        / ctxcore.setupwithargument -- or xmlw as xmlsetup has swapped arguments
      + (P("tex") * tag + str) / ctxcore.texsetup
      +             sep^1
    )^1

    implement {
        name      = "autosetups",
        actions   = function(str) lpegmatch(pattern,str) end,
        arguments = "string"
    }

end

do

    -- This is a slow variant, no namespace needed.

 -- function tex.getmeasure(name,asdimen)
 --     local value = token.getexpansion("\\tointeger\\measured{"..name.."}")
 --     if asdimen then
 --         return value .. "sp"
 --     else
 --         return tonumber(value)
 --     end
 -- end

    local getmacro          = tokens.getters.macro
    local getdimensionvalue = tex.getdimensionvalue

    -- This is not that much needed because one will seldom fetch a measure at the Lua end
    -- although I will probably use it for availablehsize and a like (for which this value
    -- getter is meant). Anyway, we save some runtime by using:

    local measures = setmetatableindex(function(t,k)
        local v = getmacro("??measure") .. k
        t[k] = v
        return v
    end)

    -- A Lua lookup plus extracting the cs from the token is a bit slower than a TeX lookup
    -- by string whuch directly gives the token. So we don't benefit from:

    -- local measures = table.setmetatableindex(function(t,k)
    --     local v = token.create(getmacro("??measure") .. k)
    --     t[k] = v
    --     return v
    -- end)

    -- The 'asdimen' feature is not that much needed in Lua but is provided anyway. There
    -- is no need to use 'pt' here.

    function tex.getmeasure(name,asdimen)
     -- local value = getdimensionvalue(namespace..name)
        local value = getdimensionvalue(measures[name])
        if asdimen then
            return value .. "sp"
        else
            return value
        end
    end

end
