Various bug fixes, improvements and refactorings, and lots of comments have been added.