Refactored large parts. Not complete yet.