From 6f3b36f0d1f8fa8f476a72c34d80166fd95ed39e Mon Sep 17 00:00:00 2001
From: Robert Alessi <alessi@robertalessi.net>
Date: Tue, 2 Feb 2021 08:33:43 +0100
Subject: bugfix: divs needed to be processed twice and in 'overlapping' mode
 for the TEI output to validate

---
 ekdosis.dtx | 28 ++++++++++++++++++++++------
 1 file changed, 22 insertions(+), 6 deletions(-)

diff --git a/ekdosis.dtx b/ekdosis.dtx
index 5f5eab3..53eda98 100644
--- a/ekdosis.dtx
+++ b/ekdosis.dtx
@@ -8898,7 +8898,7 @@ local function close_ekddivs_in_between(str)
    end
    for ndivi = 1, maxdepth
    do
-      str = string.gsub(str, "(<div .-depth%=\")("..ndivi..")(\".->)(.-)(<div .-depth%=\")(%d)(\".->)",
+      str = string.gsub(str, "(<div [^%>]-[Dd]epth%=\")("..ndivi..")(\".->)(.-)(<div [^%>]-depth%=\")(%d)(\".->)",
 			function(bdivi, ndivi, edivi, between, bdivii, ndivii, edivii)
 			   local firstdiv = ndivi
 			   local lastdiv = ndivii
@@ -8915,11 +8915,17 @@ local function close_ekddivs_in_between(str)
 				 firstdivindex = firstdivindex - 1
 			      end
 			   end
+			   bdivii = string.gsub(bdivii, "depth", "Depth")
 			   return string.format("%s%s%s%s%s%s%s%s",
-						bdivi, ndivi, edivi, between, closedivs, bdivii, ndivii, edivii)
+						bdivi, ndivi, edivi, between,
+						closedivs, bdivii, ndivii, edivii)
       end)
    end
-   str = string.gsub(str, "(<div.-)(%sdepth%=\"%d\")(.->)", "%1%3")
+   return str
+end
+
+local function clean_ekddivs(str)
+   str = string.gsub(str, "(<div.-)(%s[Dd]epth%=\"%d\")(.->)", "%1%3")
    used_ndivs = {}
    return str
 end
@@ -8927,7 +8933,7 @@ end
 local function close_ndivs_in_between(str)
    for ndivi = 1, 6
    do
-      str = string.gsub(str, "(<div)("..ndivi..")(.->)(.-)(<div)([1-6])(.->)",
+      str = string.gsub(str, "(<[Dd]iv)("..ndivi..")(.->)(.-)(<div)([1-6])(.->)",
 			function(bdivi, ndivi, edivi, between, bdivii, ndivii, edivii)
 			   local firstdiv = ndivi
 			   local lastdiv = ndivii
@@ -8944,11 +8950,17 @@ local function close_ndivs_in_between(str)
 			   	 firstdivindex = firstdivindex - 1
 			      end
 			   end
+			   bdivii = string.gsub(bdivii, "div", "Div")
 			   return string.format("%s%s%s%s%s%s%s%s",
-						bdivi, ndivi, edivi, between, closedivs, bdivii, ndivii, edivii)
-			
+						bdivi, ndivi, edivi, between,
+						closedivs, bdivii, ndivii, edivii)
    end)
    end
+   return str
+end
+
+local function clean_latexdivs(str)
+   str = string.gsub(str, "(<Div)([1-6])(.->)", "<div%2%3")
    used_ndivs = {}
    return str
 end
@@ -8973,9 +8985,13 @@ local function textotei(str)
    then
       str = close_ekddivs_at_end(str)
       str = close_ekddivs_in_between(str)
+      str = close_ekddivs_in_between(str)
+      str = clean_ekddivs(str)
    else
       str = close_ndivs_at_end(str)
       str = close_ndivs_in_between(str)
+      str = close_ndivs_in_between(str)
+      str = clean_latexdivs(str)
    end
    return str
 end
-- 
cgit v1.2.3