Altered code to use Drupal's batch mechanism