First complete version. Refactored, cleaned.