Some bug fixing and refactor; yay! refactor