better recursive code - still very hacky