infile.segmented <- commandArgs(trailingOnly=TRUE)[1]
infile.raw <- commandArgs(trailingOnly=TRUE)[2]
outdir <- commandArgs(trailingOnly=TRUE)[3]
#excluded <- ifelse(is.na(commandArgs(trailingOnly=TRUE)[4]), .001, as.numeric(commandArgs(trailingOnly=TRUE)[4]))
width <- ifelse(is.na(commandArgs(trailingOnly=TRUE)[4]), 1500, as.numeric(commandArgs(trailingOnly=TRUE)[4]))
height <- ifelse(is.na(commandArgs(trailingOnly=TRUE)[5]), 500, as.numeric(commandArgs(trailingOnly=TRUE)[5]))

segdata <- read.table(infile.segmented, header=TRUE)
rawdata <- read.table(infile.raw, header=TRUE)
cellnames <- colnames(segdata[-(1:5)])

# Bin numbers of the starts, ends, and middles of segments
ends <- cumsum(segdata$n.probes)
starts <- c(1, ends[-length(ends)])
middles <- (starts + ends)/2
# Bin numbers at which segment begins
chrom.starts <- starts[c(TRUE, diff(segdata$chrom)==1)]
# Vector of length equal to the number of bins, indicating the segment number
# of each bin
segnums <- rep(1:nrow(segdata), segdata$n.probes)

for (cellname in cellnames)
{
  #ylim <- quantile(rawdata[,cellname], probs=c(excluded/2, 1-excluded/2))
  ylim <- c(-3,5)
  # Segmentation, as value for each bin
  seg.est <- rep(segdata[,cellname],segdata$n.probes)
  # Height of each segment number on the plot
  label.heights <- segdata[,cellname] + .05 * (ylim[2]-ylim[1])
  # Make plot
  png(sprintf('%s/%s.png', outdir, cellname), width=width, height=height)
  tryCatch({
    plot(rawdata[,cellname], col=ifelse(segnums%%2==0, 'cyan', 'orange'),
         ylim=ylim, main=cellname, xlab='bin number', ylab='log2 ratio');
    lines(seg.est);
    abline(v=chrom.starts, col='grey90');
    text(middles, label.heights, 1:length(middles), cex=1.3)
  }, finally=dev.off())
}