Bug fixes and slightly cleaner code