refactored code out of main.cc