Major refactoring. There are still a few missing/broken features.