Bug fixes and mods

Fixed a few bugs, and modified the code a bit, hopefully to be more
efficient.