Index: /home/scott/core/comm/comm/html/sites/all/modules/contrib/similarity/classes/similarity_taxonomy.inc
index 0276ef6..4eb9f58 100644
--- a/html/sites/all/modules/contrib/similarity/classes/similarity_taxonomy.inc
+++ b/html/sites/all/modules/contrib/similarity/classes/similarity_taxonomy.inc
@@ -33,35 +33,25 @@ class similarity_taxonomy extends similarity_node {
     
     // set limits
     $last = variable_get($this->machine_name . '_cron_last', 0);
-    $last = 0;
+    $args[] = $last;
     $limit = $this->node_limit; // very basic right now
 
-    $args[] = $last;
     $args = array_merge($args, $this->types);
     $result = db_query_range('SELECT n.nid, n.changed FROM {node} n WHERE n.changed > %d AND ' . $type_string . ' ORDER BY changed ASC', $args, 0, $limit);
 
     $last_changed = 0;
-    
-    // The SQL
-    $cooccurance_sql = "SELECT t2.nid, COUNT(t2.tid) as count FROM {term_node} t1 JOIN {term_node} t2 ON t2.tid = t1.tid AND t2.nid <> t1.nid WHERE t1.nid = %d GROUP BY t2.nid";
-    $total_sql = "SELECT COUNT(tid) FROM {term_node} WHERE nid = %d";
+    db_query_temporary("SELECT nid, COUNT(tid) as count FROM {term_node} GROUP BY nid", 'term_counts');
     while ($changed_obj = db_fetch_object($result)) {
-      $other_result = db_query($cooccurance_sql, $changed_obj->nid);
+      db_query_temporary("SELECT t.nid, SQRT(tc.count * COUNT(t.tid)) AS mag FROM {term_node} t JOIN term_counts tc ON tc.nid = %d WHERE t.nid <> %d GROUP BY nid", $changed_obj->nid, $changed_obj->nid, 'denom_sim');
       
-      // Need a way to handle this in SQL somewhere
-      $target_count = db_result(db_query($total_sql, $changed_obj->nid));
-      while ($term_row = db_fetch_object($other_result)) {
-        if ($term_row->count) {
-          $other_count = db_result(db_query($total_sql, $term_row->nid));
-          $denom = sqrt($target_count * $other_count);
-          $this->save_similarity($changed_obj->nid, $term_row->nid, ($term_row->count / $denom));
-        }
-      }
-    }
-    // then insert
-    $this->write_similarities();
-    if ($last_changed > 0 ) {
-      variable_set($this->machine_name . '_cron_last', $last_changed);
+      db_query("INSERT INTO {". $this->machine_name . "_similarity} ".
+               "SELECT IF(t1.nid > t2.nid, t1.nid, t2.nid) as nid1, IF(t1.nid > t2.nid, t2.nid, t1.nid) as nid2, COUNT(t2.nid) / s.mag as sim " .
+               "FROM {term_node} t1 JOIN {term_node} t2 ON t2.tid = t1.tid AND t2.nid <> t1.nid JOIN {denom_sim} s ON s.nid = t2.nid WHERE t1.nid = %d GROUP BY nid1, nid2 HAVING sim > %d " .
+               "ON DUPLICATE KEY UPDATE score=VALUES(score)", $changed_obj->nid, ($this->min_sim / 100));
+      db_query("DROP TABLE {denom_sim}");
+      $last_changed = $changed_obj->changed;
     }
+    
+    variable_set($this->machine_name . '_cron_last', $last_changed);
   }
 }
\ No newline at end of file
