Made refactor and fixed some small bugs