Refactored most of the code
final changes