Fixed performance issue. Some refactoring as well.