--- invisimail.module.orig	2009-03-10 10:08:00.000000000 -0700
+++ invisimail.module	2009-03-10 10:14:29.000000000 -0700
@@ -105,6 +105,12 @@ function invisimail($string, $format) {
   // so we'll set a global variable
   $GLOBALS['invisimail_format'] = $format;
 
+  // First fix addresses that are already linked
+  $pattern = "!<a([^>]+?)href=[\"']mailto:([^\"']+?)[\"'](.*?)>(.*?)</a>!is";
+  $string = preg_replace_callback($pattern, 'invisimail_callback2', $string);
+
+  $pattern = "!(^|<p>|<td>|<li>|<br />|[ \n\r\t\(])([A-Za-z0-9._-]+@[A-Za-z0-9._-]+\.[A-Za-z]{2,4})([.,]?)(?=(</p>|</td>|</li>|<br />|[ \n\r\t\)]|$))!i";
+
   return preg_replace_callback($pattern, 'invisimail_callback', $string);
 }
 
@@ -117,6 +123,23 @@ function invisimail_callback($matches) {
 }
 
 /**
+ * Calls the encode function on existing mailto: links
+ */
+function invisimail_callback2($matches) {
+  $format = $GLOBALS['invisimail_format'];
+  $js = variable_get('invisimail_js_'.$format, FALSE);
+  $link = variable_get('invisimail_link_'.$format, FALSE);
+  $attribs = $matches[1] . $matches[3];
+  $text = null;
+  // If the text is not the email address we don't want it encoded
+  if ($matches[2] != trim($matches[4])) {
+    $text = $matches[4];
+  }
+
+  return invisimail_ascii_encode($matches[2], $js, $link, $text, $attribs);
+}
+
+/**
  * This function does the actual encoding. 
  *
  * @param $string
@@ -127,10 +150,12 @@ function invisimail_callback($matches) {
  *   Optional: A boolean which set whether the result includes a mailto link.
  * @param $text
  *   Optional: The text to be used for the link.
+ * @param $attribs
+ *   Optional: Any additional attributes for the anchor tag
  * @return
  *   An ascii encoded email address. 
  */
-function invisimail_ascii_encode($string, $js = FALSE, $link = FALSE, $text = NULL) {
+function invisimail_ascii_encode($string, $js = FALSE, $link = FALSE, $text = NULL, $attribs = '') {
   if ($text == NULL) {
     $text = $string;
   }
@@ -152,11 +177,15 @@ function invisimail_ascii_encode($string
   }
   
   if ($link && !$js) {
+    // If text for link is empty, use encoded email address
+    $linkText = $text == null ? $encode : $text;
     // ascii in this next line is "mailto:"
-    $output .= "<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;$encode\">$text</a>";
+    $output .= "<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;$encode\"$attribs>$linkText</a>";
   }
   elseif ($link && $js) {
-    $output .= "<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;'+'$encode'+'\">'+'$text'+'</a>";    
+    $attribs = str_replace("'", "\\'", $attribs);
+    $linkText = $text == null ? $encode : str_replace("'", "\\'", $text);
+    $output .= "<a href=\"&#109;&#97;&#105;&#108;&#116;&#111;&#58;'+'$encode'+'\"$attribs>'+'$linkText'+'</a>";
   }
   else {
     $output .= $encode;
@@ -241,4 +270,4 @@ function _invisimail_settings($format) {
   );
   
   return $form;
-}
\ No newline at end of file
+}
