Finally getting it right. Original solution was correct in intent, but had a bug