Complete refactoring and added comments and doc