Refactored and error handling (sorry for not commmiting in the middle of this)