Corrected some bugs and granulated the code