replaced ugly iteration with ugly recursion