Rafactoring, bug fixes and unit tests added