if not modules then modules = { } end modules ['grph-downsample'] = {
  version   = 1.001,
  comment   = "companion to grph-inc.mkiv",
  author    = "Peter Münster",
  copyright = "PRAGMA ADE / ConTeXt Development Team",
  license   = "see context related readme files"
}

local format = string.format
-- figures.cachepaths.path = "cache" -- should be setup-option
local function sample_down(oldname, newname, resolution)
  local request = figures.current().request
  local width = request.width
  local height = request.height
  if resolution == "" or (not width and not height) then
    print(format("Nothing to do: %s, %s, %s", oldname, newname, resolution))
    return
  end
  local inch = 72.27
  local image = img.scan{filename = oldname}
  local xy = image.xsize / image.ysize
  if not width then
    width = height * xy / 65536
  end
  if not height then
    height = width / xy / 65536
  end
  local xsize = resolution * width / inch
  local ysize = resolution * height / inch
  if xsize < image.xsize or ysize < image.ysize then
    local s = format("gm convert -resize %dx%d %s %s",
                     xsize, ysize, oldname, newname)
    print("Conversion: " .. s)
    os.execute(s)
  else
    print(format("Nothing to do: %s, %s, %s", oldname, newname, resolution))
    print(format("xsize = %d, ysize = %d", xsize, ysize))
  end
end

local formats = {"png", "jpg", "gif"}

for _, s in ipairs(formats) do
  figures.converters[s] = figures.converters[s] or {}
  figures.converters[s]["lowres." .. s] = sample_down
end
