Refactor and cleanup the whole code