refactored main and found other bugs