rm(list=ls())
options(stringsAsFactors=FALSE)
set.seed(1357)

genbars <- function(name, design) {
	df <- data.frame(filename=character(),cond=character(),ratio=double(),height1=double(),height2=double(),index=integer(), dotpos=double())

    tall.distractors <- c(NA,59,61,61,16,93,NA,NA,3,61,76,17,42,NA)
    short.distractors <- c(NA,4,13,15,8,12,NA,NA,3,15,9,14,7,NA)

    for(i in 1:nrow(design)) {
        
        r <- design[i,]

        h <- switch(r$distractors,
            'short'=short.distractors,
            'tall'=tall.distractors,
            rep(NA, 14))
        h[[3]] <- r$height
        h[[3+r$distance]] <- r$height*r$ratio/100
        
        fname <- paste(name,r$ratio,i,".png",sep="-")
        png(filename=file.path(path, fname),width=640,height=640)
        par(mar=c(1,1,1,1), oma=c(4,4,4,4), lwd=3, cex.axis=1.5, mgp=c(3,1,0))
        
        bp <- barplot(h, col=NA, border=TRUE, axes=F, ylim=c(0,100), space = 0)
        axis(2, labels=c(0,100), at=c(0,100), lwd=3, las=1)
        points(x=bp[c(3,3+r$distance)], y=c(3.5,3.5), pch=20, cex=2)
        par(mgp=c(3,2,0))
        axis(1, labels=NA, lwd.ticks=0, lwd=3)
        #axis(1, labels=c('A', 'B'), at=bp[c(4,11)], lwd.ticks=0, lwd=0)
        dev.off()
        df <- rbind(df,c(filename=fname,height1=h[[3]],height2=h[[3+r$distance]],r))
	}

	return(df)
}


path <- "papers/barchartstudy/experiments/Experiment1/"

df <- genbars("stimuli",
    expand.grid(
        ratio = c(17.8, 26.1, 38.3, 46.4, 56.2, 68.1, 82.5),
        height = c(25, 50, 75),
        distance = c(1, 7),
        distractors = c('none','short','tall')
    ))

# rejection sample until we don't get two with/without distractors next to each other
#success <- FALSE
#while(!success) {
#    o <- sample(1:nrow(df),replace=FALSE)
#    x <- df[o,'distractors']
#    success <- all(x[-1] != x[-length(x)])
#}
#df <- df[o,]

df <- df[sample(1:nrow(df),replace=FALSE),]

for (i in 1:nrow(df)){
	file.rename(paste(path,df$filename[i],sep=""), paste(path,i,".png",sep=""))
	df$filename[i] <- paste(i,".png",sep="")
}
write.csv(df, file=file.path(path, "BarData.csv"), row.names=FALSE)

df <- genbars("sample",
    data.frame(
        ratio = c(70, 59, 23.2),
        height = c(75, 25, 100),
        distance = c(1, 7, 1),
        distractors = c('none', 'short', 'tall')
    ))