Cleaned up the code and added mode selection.