refactoring and parallelization (not thoroughly tested)