Refactored. 
Bugs to be fixed