tested and cleaned
working solution to loop (but not recursive, thus lengthy)