big refactoring, optimization and reformatting