restructure to reduce globalsand increase code reuse; add test for nested elements