<?php
//STANDARD PLUGIN STUFF GOES HERE

register_activation_hook(__FILE__, 'myplugin_activate');

if('error_scrape' == $_GET['action']) {
  echo 'This is <em>not</em> a fatal error, <strong>this plugin was still activated</strong>, but with a warning:<br />
This is the first time you are activating this plugin, but several tables already exist in the database.  Does another plugin use these tables?  If not, and you are sure they can be used by this plugin, please deactivate and reactivate this plugin, and we will make sure these tables follow this plugin\'s structure.<br />
These are the tables already in the database:<br />'.get_option('myplugin_activate_error');
  delete_option('myplugin_activate_error');
  die();
}

function myplugin_activate() {
  global $wpdb;

  //defines $version, $tables, and $data
  require_once(ABSPATH . 'wp-content/plugins/myplugin/includes/schema.php');
  require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

  $current_tables = $wpdb->get_col('SHOW TABLES');
  $current_version = get_option('myplugin_version');

  $error = '';
  foreach($tables AS $table=>$sql) {
    if(!$current_version && in_array($table, $current_tables)) {
      $error .= $table.'<br />';
    }
    elseif(!$current_version) {
      dbDelta($sql);
      if(isset($data[$table])) {
        $wpdb->query($data[$table]);
      }
    }
    elseif($current_version != $version) {
      dbDelta($sql);
    }
  }

  if($current_version != $version) {
    if(!$current_version) {
      add_option('myplugin_version', $version);
    }
    else {
      update_option('myplugin_version', $version);
    }
  }

  if($error) {
    add_option('myplugin_activate_error', $error);
    //trigger a fatal error
    trigger_error('', E_USER_ERROR);
  }
}
?>