Refactors and fixed some bugs