Fixed a bunch of things

This pull requests fixed both issues that I reported earlier, plus some other things that bothered me. Code should be cleaner *and* more robust now.