Refactor and some bug fixing