Overall refactor and bug fix