refactoring for threading.. improved performance