big refactoring and small bug fix