Added error alerts and some code refactoring