Whoa. This line is doing a LOT of things, and it's very difficult to read. The docstring helps (a lot, actually), but can you split this into multiple lines, and add some comments to explain each step?