Refactor, error handling, formatting