I'd probably break out the functionality in your anonymous functions into a set of named functions that do very discrete things, both for readability and for maintenability. It's very hard to figure out just by reading this file exactly what the function does or doesn't do, and when.