Added some better comments and reorg of code to improve readability