Fix a few bugs and add better commenting.