## A localized relationship illustrates why multiscale scanning is useful.
local({
  set.seed(12345)
  n <- 500
  x <- runif(n)
  y <- runif(n)
  local_signal <- x > 0.25 & x < 0.50
  y[local_signal] <- 0.12 + 0.76 * (x[local_signal] - 0.25) / 0.25 +
    rnorm(sum(local_signal), sd = 0.055)
  y <- pmin(1, pmax(0, y))
  structure <- fes(
    x,
    y,
    K1 = 4,
    K2 = 4,
    M = 4,
    return.details = TRUE
  )
  result <- structure$p.value
  print(structure)

  old_parameters <- graphics::par(no.readonly = TRUE)
  old_parameters$new <- FALSE
  on.exit(graphics::par(old_parameters))
  graphics::layout(matrix(c(1, 2), nrow = 1L), widths = c(1.35, 1))

  graphics::par(mar = c(4, 4, 3.2, 1), mgp = c(2.2, 0.7, 0))
  graphics::plot(
    x[!local_signal],
    y[!local_signal],
    pch = 16,
    cex = 0.58,
    col = grDevices::adjustcolor("#7F8C8D", alpha.f = 0.34),
    xlab = "X",
    ylab = "Y",
    main = "Dependence in a local window",
    bty = "n",
    las = 1,
    panel.first = graphics::grid(col = "#ECECEC", lty = 1)
  )
  graphics::rect(0.25, 0, 0.50, 1,
                 border = grDevices::adjustcolor("#D95F02", alpha.f = 0.7),
                 lwd = 2, lty = 2)
  graphics::points(
    x[local_signal],
    y[local_signal],
    pch = 21,
    cex = 0.82,
    col = "#8C2D04",
    bg = grDevices::adjustcolor("#F16913", alpha.f = 0.62)
  )
  graphics::legend(
    "topright",
    legend = c("Background", "Local signal"),
    pch = c(16, 21),
    col = c("#7F8C8D", "#8C2D04"),
    pt.bg = c(NA, "#F16913"),
    bty = "n",
    cex = 0.78
  )

  graphics::par(mar = c(4, 4, 3.2, 1), mgp = c(2.2, 0.7, 0))
  evidence <- -log10(pmax(result, .Machine$double.xmin))
  graphics::barplot(
    evidence,
    col = grDevices::hcl.colors(length(evidence), "Viridis"),
    border = NA,
    ylab = expression(-log[10](italic(p))),
    main = "Global evidence",
    las = 1,
    ylim = c(0, max(evidence, -log10(0.05)) * 1.12)
  )
  graphics::abline(h = -log10(0.05), col = "#D7191C", lty = 2, lwd = 1.5)

  ## A compact structure map summarizes the strongest significant windows.
  graphics::layout(1)
  graphics::par(mar = c(4, 4, 3.3, 1), mgp = c(2.2, 0.7, 0))
  plot(
    structure,
    max.windows = 10,
    main = "Where the local relationship occurs"
  )

  ## The red-outlined heatmap windows locate the strongest evidence.
  invisible(fes(
    x,
    y,
    K1 = 4,
    K2 = 4,
    M = 4,
    plot.it = TRUE,
    plot.sidak = TRUE,
    plot.scale = TRUE
  ))
})
