refactors most of the code