Second. This whole function needs some more comments to explain what's going on. Also don't be afraid to add whitespace between logical blocks of code to increase readability.