More refactor and fixed minor bugs