BEGIN
  DECLARE v_threads_running INT;
  DECLARE v_sleep INT;
  DECLARE v_called_by_user VARCHAR(50);
  DECLARE v_mysql_version VARCHAR(20);
  DECLARE sql_logging BOOLEAN;
  SELECT @@sql_log_bin into sql_logging;
  SELECT user() into v_called_by_user;
  SELECT version() into v_mysql_version;
  SELECT COUNT(1) INTO v_threads_running FROM information_schema.processlist WHERE USER = 'system user';
  IF v_threads_running = 1 
 THEN
    SET @cmd = CONCAT('CHANGE MASTER TO MASTER_LOG_FILE = "',
    CONCAT('mysql-bin-changelog.', LPAD('1' + curr_master_log, 6, '0')), '",
    MASTER_LOG_POS = 4');
    STOP SLAVE;
    PREPARE rds_set_master FROM @cmd;
    EXECUTE rds_set_master;
    DEALLOCATE PREPARE rds_set_master;
    START SLAVE;
    SELECT 'Master Log Position has been set to start of next log' AS Message;
    SELECT sleep(2) INTO v_sleep;
    SELECT COUNT(1) INTO v_threads_running FROM information_schema.processlist WHERE USER = 'system user';
    SET @@sql_log_bin=off;
    IF v_threads_running = 2 THEN
      SELECT 'Slave is running normally' AS Message;
      INSERT into mysql.rds_history(called_by_user, action, mysql_version, master_log_file, master_log_pos) values (v_called_by_user,'next_master_log:OK', v_mysql_version, CONCAT('mysql-bin-changelog.', LPAD('1' + curr_master_log, 6, '0')),4);
      commit;
    ELSE
      SELECT 'Slave has encountered a new error. Please use SHOW SLAVE STATUS to see the error.' AS Message;
      INSERT into mysql.rds_history(called_by_user, action, mysql_version, master_log_file, master_log_pos) values (v_called_by_user,'next_master_log:ERR', v_mysql_version, CONCAT('mysql-bin-changelog.', LPAD('1' + curr_master_log, 6, '0')),4);
      commit;
    END IF;
    SET @@sql_log_bin=sql_logging;
  elseif v_threads_running = 2 
  THEN
     SELECT 'Slave is running normally.  No errors detected to skip.' AS Message;
  elseif v_threads_running = 0 
  THEN
     SELECT 'Slave is down or disabled.' AS Message;
  END IF;
END