rename function
move helper functions to top of function
remove redundant variable
add explanation