replaced some refs with recursive inner functions