add exit in main and do some refactoring