Cleaned up code, minor bugfixes.