refactor and add debug codes.