To make you code easier to read please indent your lines by four spaces so it preserves your indentation… As it is it is very difficult to read.
From what I can tell with a quick scan this looks overly complicated and brittle. See this posting to see if it shows a way to implement what you are looking for.