Preparation for GUI. Some debugging and refactoring.