simplified to a single recursive function