fixes bugs and refactors code