major refactoring and proper exception handling