Further refactoring
Further refactoring and error checks