As this grows more fancy, it seems to be slowing down a bit. Add some light profiling when using the lucid_debug flag to uncover where the slowness is.
There are lots of for loops that can be simplified. But other things to pay attention to are the regular expression matching.