Updated select to be more robust and fault tolerant.

Added comments to insert so it's not as terrible to work with next time.

Moved some code around so that it's not so terrible to read.