Refacto

Completely refactored the code. and added lots of comments.