refactored codes into multiple funtions, added Exception class