Modularize, add some comments, and some minor changes