Change re-nesting code to accurately count sub elements