diff --git a/cdn.basic.css.inc b/cdn.basic.css.inc
new file mode 100644
index 0000000..30c1e50
--- /dev/null
+++ b/cdn.basic.css.inc
@@ -0,0 +1,131 @@
+<?php
+
+/**
+ * @file
+ * Overrides of Drupal's CSS aggregation system. Ensures that files referenced
+ * by CSS files are also served from the CDN, according to the CDN module's
+ * CSS aggregation rules.
+ */
+
+
+/**
+ * Mostly based on drupal_get_css().
+ */
+function _cdn_css_aggregate(&$vars) {
+  $output = '';
+  $prefix = $suffix = '<!-- CSS aggregated by CDN module. -->' . "\n";
+
+  $css = $vars['css'];
+
+  $no_module_preprocess = '';
+  $no_theme_preprocess = '';
+
+  $preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
+  $directory = file_directory_path();
+  $is_writable = is_dir($directory) && is_writable($directory) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC);
+
+  foreach ($css as $media => $types) {
+    // If CSS preprocessing is off, we still need to output the styles.
+    // Additionally, go through any remaining styles if CSS preprocessing is on and output the non-cached ones.
+    foreach ($types as $type => $files) {
+      if ($type == 'module') {
+        // Setup theme overrides for module styles.
+        $theme_styles = array();
+        foreach (array_keys($css[$media]['theme']) as $theme_style) {
+          $theme_styles[] = basename($theme_style);
+        }
+      }
+      foreach ($types[$type] as $file => $preprocess) {
+        // If the theme supplies its own style using the name of the module style, skip its inclusion.
+        // This includes any RTL styles associated with its main LTR counterpart.
+        if ($type == 'module' && in_array(str_replace('-rtl.css', '.css', basename($file)), $theme_styles)) {
+          // Unset the file to prevent its inclusion when CSS aggregation is enabled.
+          unset($types[$type][$file]);
+          continue;
+        }
+        // Only include the stylesheet if it exists.
+        if (file_exists($file)) {
+          if (!$preprocess || !($is_writable && $preprocess_css)) {
+            // If a CSS file is not to be preprocessed and it's a module CSS file, it needs to *always* appear at the *top*,
+            // regardless of whether preprocessing is on or off.
+            if (!$preprocess && $type == 'module') {
+              $no_module_preprocess .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. file_create_url($file) .'" />'."\n";
+            }
+            // If a CSS file is not to be preprocessed and it's a theme CSS file, it needs to *always* appear at the *bottom*,
+            // regardless of whether preprocessing is on or off.
+            else if (!$preprocess && $type == 'theme') {
+              $no_theme_preprocess .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. file_create_url($file) .'" />'."\n";
+            }
+            else {
+              $output .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. file_create_url($file) .'" />'."\n";
+            }
+          }
+        }
+      }
+    }
+
+    if ($is_writable && $preprocess_css) {
+      // Prefix filename to prevent blocking by firewalls which reject files
+      // starting with "ad*".
+      $query_string = variable_get('css_js_query_string', '0');
+      $filename = 'css_'. md5(serialize($types) . $query_string . 'cdn') .'.css';
+      $preprocess_file = _cdn_build_css_cache($types, $filename);
+      $output .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. file_create_url($preprocess_file) .'" />'."\n";
+    }
+  }
+
+  $vars['styles'] = $prefix . $no_module_preprocess . $output . $no_theme_preprocess . $suffix;
+}
+
+function _cdn_build_css_cache($types, $filename) {
+  $data = '';
+
+  // Create the css/ within the files folder.
+  $csspath = file_create_path('css');
+  file_check_directory($csspath, FILE_CREATE_DIRECTORY);
+
+  if (!file_exists($csspath .'/'. $filename)) {
+    // Build aggregate CSS file.
+    foreach ($types as $type) {
+      foreach ($type as $file => $cache) {
+        if ($cache) {
+          $contents = drupal_load_stylesheet($file, TRUE);
+          // Return the Drupal path to where this CSS file originated from.
+          $base = dirname($file) .'/';
+          _cdn_build_css_path(NULL, $base);
+          // Prefix all paths within this CSS file, ignoring external and absolute paths.
+          $data .= preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', '_cdn_build_css_path', $contents);
+        }
+      }
+    }
+
+    // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
+    // @import rules must proceed any other style, so we move those to the top.
+    $regexp = '/@import[^;]+;/i';
+    preg_match_all($regexp, $data, $matches);
+    $data = preg_replace($regexp, '', $data);
+    $data = implode('', $matches[0]) . $data;
+
+    // Create the CSS file.
+    file_save_data($data, $csspath .'/'. $filename, FILE_EXISTS_REPLACE);
+  }
+  return $csspath .'/'. $filename;
+}
+
+function _cdn_build_css_path($matches, $base = NULL) {
+  static $_base;
+  // Store base path for preg_replace_callback.
+  if (isset($base)) {
+    $_base = $base;
+  }
+
+  // Prefix with base and remove '../' segments where possible.
+  $path = $_base . $matches[1];
+  $last = '';
+  while ($path != $last) {
+    $last = $path;
+    $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
+  }
+
+  return 'url('. file_create_url($path) .')';
+}
diff --git a/cdn.fallback.inc b/cdn.fallback.inc
index 5b56076..8e76397 100644
--- a/cdn.fallback.inc
+++ b/cdn.fallback.inc
@@ -21,7 +21,7 @@
  * @param &$theme_registry
  *   The entire cache of theme registry information, post-processing.
  */
-function cdn_theme_registry_alter(&$theme_registry) {
+function _cdn_fallback_theme_registry_alter(&$theme_registry) {
   if (isset($theme_registry['page'])) {
     // If CDN's preprocess function is there already, remove it.
     if ($key = array_search('cdn_preprocess_page', $theme_registry['page']['preprocess functions'])) {
diff --git a/cdn.module b/cdn.module
index 3c961b7..bc7e3f7 100644
--- a/cdn.module
+++ b/cdn.module
@@ -287,6 +287,29 @@ function cdn_cdn_unique_file_identifier_info() {
   );
 }
 
+
+/**
+ * Implementation of hook_theme_registry_alter().
+ *
+ * Make CDN's page preprocess function run *after* everything else's, so that
+ * a theme can't call drupal_get_js() and mess everything up.
+ *
+ * @param &$theme_registry
+ *   The entire cache of theme registry information, post-processing.
+ */
+function cdn_theme_registry_alter(&$theme_registry) {
+  // We only need to override CSS aggregation if the advagg module is not in
+  // use; otherwise that module handles that perfectly fine already!
+  $mode = variable_get(CDN_MODE_VARIABLE, CDN_MODE_BASIC);
+  if ($mode == CDN_MODE_BASIC && !module_exists('advagg')) {
+    $theme_registry['page']['preprocess functions'][] = '_cdn_css_aggregate';
+  }
+
+  if (_cdn_load_fallback()) {
+    _cdn_fallback_theme_registry_alter($theme_registry);
+  }
+}
+
 /**
  * Implementation of hook_menu().
  */
@@ -415,14 +438,14 @@ function cdn_theme() {
 function cdn_init() {
   _cdn_prefetch_dns();
 
-  // When the fallback mechanism to alter file URLs (i.e. using the theme
-  // layer) is enabled, load cdn.fallback.inc. But only load it when the
-  // CDN integration is enabled or if testing mode is enabled and the current
-  // user has access to that.
-  $status = variable_get(CDN_STATUS_VARIABLE, CDN_DISABLED);
-  if (($status == CDN_ENABLED || ($status == CDN_TESTING && user_access(CDN_PERM_ACCESS_TESTING)))
-      && variable_get(CDN_THEME_LAYER_FALLBACK_VARIABLE, FALSE) == TRUE
-  ) {
+  // We only need to override CSS aggregation if the advagg module is not in
+  // use; otherwise that module handles that perfectly fine already!
+  $mode = variable_get(CDN_MODE_VARIABLE, CDN_MODE_BASIC);
+  if ($mode == CDN_MODE_BASIC && !module_exists('advagg')) {
+    cdn_load_include('basic.css');
+  }
+
+  if (_cdn_load_fallback()) {
     cdn_load_include('fallback');
   }
 
@@ -655,6 +678,26 @@ function cdn_load_include($basename) {
 //----------------------------------------------------------------------------
 // Private functions.
 
+
+/**
+ * Whether the fallback mechanism should be loaded or not.
+ *
+ * When the fallback mechanism to alter file URLs (i.e. using the theme layer)
+ * is enabled, load cdn.fallback.inc. But only load it when the CDN
+ * integration is enabled or if testing mode is enabled and the current user
+ * has access to that.
+ */
+function _cdn_load_fallback() {
+  $status = variable_get(CDN_STATUS_VARIABLE, CDN_DISABLED);
+  return (
+            ($status == CDN_ENABLED
+             ||
+             ($status == CDN_TESTING && user_access(CDN_PERM_ACCESS_TESTING))
+            )
+             && variable_get(CDN_THEME_LAYER_FALLBACK_VARIABLE, FALSE) == TRUE
+         );
+}
+
 /**
  * Callback for generating a unique file identifier.
  *
