fixed some bugs and refactored main function