Code reorganization

Grouped listeners and added comments to most blocks of code.