A lot of refactoring, moved all common parts to functions