Refactor code. Fix bugs