Some code refactor, added better error handling