# Original Bopbun code and synthetic scores: CC0-1.0.
library(ggplot2)
library(patchwork)
out <- dirname(normalizePath(sub('^--file=', '', grep('^--file=', commandArgs(), value=TRUE)[1])))
d <- expand.grid(column=1:3, row=1:3)
d$score <- c(2,5,8,3,7,4,9,1,6)
write.csv(d, file.path(out,'synthetic.csv'), row.names=FALSE)
p <- ggplot(d,aes(column,row,fill=score)) +
  geom_tile(colour='white',linewidth=0.7) +
  geom_text(aes(label=score),colour='black',size=4) +
  scale_fill_gradient(low='#eef6f4',high='#54aaa2',limits=c(0,9),guide='none') +
  scale_x_continuous(breaks=1:3,labels=c('X1','X2','X3'),expand=c(0,0)) +
  scale_y_continuous(breaks=1:3,labels=c('Y1','Y2','Y3'),expand=c(0,0)) +
  coord_fixed() + labs(x='Column',y='Row') +
  theme_minimal(base_size=12) + theme(panel.grid=element_blank())
plots <- lapply(LETTERS[1:4],function(s) p + labs(title=paste('Panel',s)))
before <- wrap_plots(plots,ncol=2)
no_x <- theme(axis.text.x=element_blank(),axis.ticks.x=element_blank(),axis.title.x=element_blank())
no_y <- theme(axis.text.y=element_blank(),axis.ticks.y=element_blank(),axis.title.y=element_blank())
after <- wrap_plots(plots[[1]]+no_x,plots[[2]]+no_x+no_y,
                    plots[[3]],plots[[4]]+no_y,ncol=2)
ggsave(file.path(out,'before.png'),before,width=7,height=6,units='in',dpi=200,bg='white')
ggsave(file.path(out,'after.png'),after,width=7,height=6,units='in',dpi=200,bg='white')
ggsave(file.path(out,'after.pdf'),after,width=7,height=6,units='in',bg='white',timestamp=FALSE)
# Inspect non-empty axis/title grobs in each constituent ggplot.
pdf(NULL) # Supply a metrics device without creating a default Rplots.pdf.
visible <- function(plot,name) {
  g <- ggplotGrob(plot)
  ids <- which(g$layout$name==name)
  any(vapply(g$grobs[ids],function(x) !inherits(x,'zeroGrob'),logical(1)))
}
final <- list(plots[[1]]+no_x,plots[[2]]+no_x+no_y,plots[[3]],plots[[4]]+no_y)
check <- do.call(rbind,lapply(1:4,function(i) data.frame(panel=LETTERS[i],
  x_axis=visible(final[[i]],'axis-b'),y_axis=visible(final[[i]],'axis-l'),
  x_title=visible(final[[i]],'xlab-b'),y_title=visible(final[[i]],'ylab-l'))))
# Axis containers can remain even when text/ticks are blank. Check resolved themes too.
check$x_text <- vapply(final,function(x) !inherits(x$theme$axis.text.x,'element_blank'),logical(1))
check$y_text <- vapply(final,function(x) !inherits(x$theme$axis.text.y,'element_blank'),logical(1))
write.csv(check,file.path(out,'axis-check.csv'),row.names=FALSE)
invisible(dev.off())
sink(file.path(out,'session-info.txt')); print(sessionInfo()); sink()
print(check)
