Add type hints and refactor some code