Major refactoring.
Finished with merge conflicts.
Merged tsauvinen's changes.