refactoring & performance improvement

Huge code refactoring and plenty of performance improvement