restructured the code and added exception handling