Refactoring and big fixes