Character encoding fixes and much refactoring