some refactoring and cleanup. add command line options