Why are you using 2 nested functions here? Wouldn't a flat function work just as well and be less complex?