cleanup: added header comments, moved around some code