From d60e584fd104a46dcc8b59f4d18dd50548526310 Mon Sep 17 00:00:00 2001
From: Robert Alessi <alessi@robertalessi.net>
Date: Tue, 28 Apr 2020 10:48:14 +0200
Subject: close_divs_in_between() obviously needed a for loop, not a recursion

---
 ekdosis.dtx | 23 ++++++++++++++++++-----
 1 file changed, 18 insertions(+), 5 deletions(-)

(limited to 'ekdosis.dtx')

diff --git a/ekdosis.dtx b/ekdosis.dtx
index 5c142e2..5ec9df1 100644
--- a/ekdosis.dtx
+++ b/ekdosis.dtx
@@ -1874,12 +1874,25 @@ local function close_divs_at_end(str)
 end
 
 local function close_divs_in_between(str)
-   for i = 0, 9
+   for ndivi = 0, 9
    do
-      str = string.gsub(str, "(<div"..i..".->)(.-)(<div"..i..".->)", function(divi, between, divii)
-			   between = close_divs_in_between(between)
-			   return string.format("%s%s</div%s>%s", divi, between, i, divii)
-      end)
+      str = string.gsub(str, "(<div)("..ndivi..")(.->)(.-)(<div)(%d)(.->)",
+			function(bdivi, ndivi, edivi, between, bdivii, ndivii, edivii)
+			   firstdiv = tonumber(ndivi)
+			   lastdiv = tonumber(ndivii)
+			   local closedivs = ""
+			   if firstdiv >= lastdiv
+			   then
+			      while firstdiv >= lastdiv
+			      do
+				 closedivs = closedivs.."</div"..firstdiv..">"
+				 firstdiv = firstdiv - 1
+			      end
+			   end
+			   return string.format("%s%s%s%s%s%s%s%s",
+						bdivi, ndivi, edivi, between, closedivs, bdivii, ndivii, edivii)
+			
+   end)
    end
    return str
 end
-- 
cgit v1.2.3

