Start refactoring, did only first function and removed global vars