Refactor code to allow batch processing