Multiple bug fixes, dryed up code a bit