#!/usr/bin/env ipescript 
-- -*- lua -*-
----------------------------------------------------------------------
-- Extract page labels
----------------------------------------------------------------------
--
-- When using several Ipe figures stored in a single Ipe PDF document
-- from a Latex document, it is convenient to refer to the figures by
-- label.
--
-- This Lua script extracts the page labels.
--
-- In your Ipe document, label the pages by giving them a section
-- heading. 
--
-- Running this script as "ipescript page-labels figures.pdf" will
-- extract the page labels, and save them as a tex file "figuresLabels.tex".
--
-- In your Latex document, use "\input{figuresLabels}" in the preamble.
-- 
-- You can then use "\includegraphics[page=\ipeFigXXX]{figures}" to include
-- the page with label XXX.
--
----------------------------------------------------------------------

if #argv ~= 1 or argv[1]:sub(-4) ~= ".pdf" then
  io.stderr:write("Usage: ipescript page-labels <figures.pdf>\n")
  return
end

local figname = argv[1]
local texname = figname:sub(1, -5) .. "Labels.tex"

local doc = assert(ipe.Document(figname))

local f = io.open(texname, "w")
f:write("%% Generated by ipescript page-labels " .. figname .. "\n")
f:write("%% Do not edit\n")
local pdfPage = 1
for i, p in doc:pages() do
  local t = p:titles()
  if t.section then
    local label = t.section:gsub("[^%a]", "")
    if label ~= "" then
      io.stderr:write("Defining label '" .. label .. "' for page " .. i .. " (" .. pdfPage .. ")\n")
      f:write("\\newcommand{\\ipeFig" .. label .. "}{" .. pdfPage .. "}\n")
    end
    for v = 1,p:countViews() do
      local vlabel = p:viewName(v):gsub("[^%a]", "")
      if vlabel ~= "" then
	io.stderr:write("Defining label '" .. label .. vlabel .. "' for view " .. v ..  
			" on page " .. i .. " (" .. pdfPage + v - 1 .. ")\n")
	f:write("\\newcommand{\\ipeFig" .. label .. vlabel .. "}{" .. pdfPage + v - 1 .. "}\n")
      end
    end
  end
  pdfPage = pdfPage + p:countViews()
end
f:close()
