diff --git a/xmlsitemap.generate.inc b/xmlsitemap.generate.inc
index c6b564a..15f4d6a 100644
--- a/xmlsitemap.generate.inc
+++ b/xmlsitemap.generate.inc
@@ -73,20 +73,29 @@ function _xmlsitemap_get_memory_usage($start = FALSE) {
  *
  * This function just makes a guess. It does not take into account
  * the currently loaded modules.
+ *
+ * @return int
+ *   The newly-calculated memory limit.
  */
 function _xmlsitemap_get_optimal_memory_limit() {
   $optimal_limit = &drupal_static(__FUNCTION__);
   if (!isset($optimal_limit)) {
-    // Set the base memory amount from the provided core constant.
-    $optimal_limit = parse_size(DRUPAL_MINIMUM_PHP_MEMORY_LIMIT);
-
-    // Add memory based on the chunk size.
-    $optimal_limit += xmlsitemap_get_chunk_size() * 500;
-
-    // Add memory for storing the url aliases.
-    if (variable_get('xmlsitemap_prefetch_aliases', 1)) {
-      $aliases = db_query("SELECT COUNT(pid) FROM {url_alias}")->fetchField();
-      $optimal_limit += $aliases * 250;
+    // Start with the current limit.
+    $current_limit = @init_get('memory_limit');
+    if ($current_limit == -1) {
+      $optimal_limit = $current_limit;
+    }
+    else {
+      $optimal_limit = ($current_limit) ? parse_size($current_limit) : parse_size(DRUPAL_MINIMUM_PHP_MEMORY_LIMIT);
+    
+      // Add memory based on the chunk size.
+      $optimal_limit += xmlsitemap_get_chunk_size() * 500;
+
+      // Add memory for storing the url aliases.
+      if (variable_get('xmlsitemap_prefetch_aliases', 1)) {
+        $aliases = db_query("SELECT COUNT(pid) FROM {url_alias}")->fetchField();
+        $optimal_limit += $aliases * 250;
+      }
     }
   }
   return $optimal_limit;
@@ -102,7 +111,7 @@ function _xmlsitemap_get_optimal_memory_limit() {
 function _xmlsitemap_set_memory_limit($new_limit = NULL) {
   $current_limit = @ini_get('memory_limit');
   if ($current_limit && $current_limit != -1) {
-    if (!is_null($new_limit)) {
+    if (is_null($new_limit)) {
       $new_limit = _xmlsitemap_get_optimal_memory_limit();
     }
     if (parse_size($current_limit) < $new_limit) {
