
ia.markov.blanket = function(target, data, nodes, alpha, extra.args = list(),
    whitelist, blacklist, start = character(0), test, max.sx = ncol(data),
    debug = FALSE) {

  nodes = nodes[nodes != target]
  whitelisted = nodes[sapply(nodes,
          function(y) { is.whitelisted(whitelist, c(target, y), either = TRUE) })]
  mb = start
  to.add = ""

  # growing phase
  if (debug) {

    cat("----------------------------------------------------------------\n")
    cat("* learning the markov blanket of ", target, ".\n", sep = "")

    if (length(start) > 0)
      cat("* initial set includes '", paste(mb, collapse = " "), "'.\n", sep = "")

  }#THEN

  # whitelisted nodes are included by default (if there's a direct arc
  # between them of course they are in each other's markov blanket).
  # arc direction is irrelevant here.
  mb = unique(c(mb, whitelisted))
  nodes = nodes[nodes %!in% mb]
  # blacklist is not checked, not all nodes in a markov blanket must be
  # neighbours.

  # phase I (stepwise forward selection)
  repeat {

    # stop if there are no nodes left, or if we cannot add any more nodes
    # because the conditioning set has grown too large.
    if (length(nodes) == 0 || is.null(nodes))
      break

    if (length(mb) > max.sx) {

       if (debug)
         cat("  @ limiting conditioning sets to ", max.sx, " nodes.\n", sep = "")

      break

    }#THEN

    # get an association measure for each of the available nodes.
    if (debug)
      cat("  * checking nodes for association.\n")

    association = indep.test(nodes, target, sx = mb, test = test, data = data,
                    extra.args = extra.args, alpha = alpha, debug = debug)

    # stop if there are no candidates for inclusion.
    if (all(association > alpha))
      break
    # get the one which maximizes the association measure.
    to.add = names(which.min(association))

    if (debug) {

      cat("    @ ", to.add, " included in the markov blanket (p-value: ",
        association[to.add], ").\n", sep = "")
      cat("    > markov blanket (", length(mb) + 1, " nodes) now is '",
        paste(c(mb, to.add), collapse = " "), "'.\n", sep = "")

    }#THEN

    if (association[to.add] <= alpha) {

      mb = c(mb, to.add)
      nodes = nodes[nodes != to.add]

    }#THEN

  }#REPEAT

  # phase II (backward selection)
  if (debug)
    cat("  * checking nodes for exclusion.\n")

  # whitelisted nodes are neighbours, they cannot be removed from the markov
  # blanket; the last node added in phase I will never be removed, because
  # the tests for inclusion and removal are identical.
  fixed = c(to.add, whitelisted)
  fixed = fixed[fixed != ""]

  pv = roundrobin.test(x = target, z = mb, fixed = fixed, data = data,
         test = test, extra.args = extra.args, alpha = alpha, debug = debug)

  return(intersect(mb, c(names(pv[pv < alpha]), fixed)))

}#IA.MARKOV.BLANKET

