sobs <- 10

hbtreatments <- read.csv("hbtreatments.csv")
hbmetadata <- read.csv("hbmetadata.csv")
hbmatrices <- read.csv("hbmatrices.csv")
hbdata <- read.csv("hbdata.csv")

fktreatments <- read.csv("fktreatments.csv")
fkmetadata <- read.csv("fkmeta.csv")
fkmatrices <- read.csv("fkmatrices.csv")
fkdata <- read.csv("fkpdata.csv")

hbtreatments <- rbind(hbtreatments, fktreatments)
hbmetadata <- rbind(hbmetadata, fkmetadata)
hbmatrices <- rbind(hbmatrices, fkmatrices)
hbdata <- rbind(hbdata, fkdata)

hbmetadata <- hbmetadata[which(hbmetadata$game == "prisoner's dilemma"),]
exps <- unique(hbmetadata$experiment)
hbtreatments <- hbtreatments[which(hbtreatments$experiment %in% exps),]
hbtreatments <- hbtreatments[which(hbtreatments$supergame_ending < 1),]
hbdata <- hbdata[which(hbdata$match_period >= sobs),]
#hbdata <- hbdata[which(hbdata$match_period <= 30),]

exps <- unique(hbtreatments$experiment)
hbmetadata <- hbmetadata[which(hbmetadata$experiment %in% exps),]

get_matrix <- function(experiment, payoff_treatment){
	matrix_row <- hbmatrices[which(hbmatrices$experiment == experiment),]
	matrix_row <- matrix_row[which(matrix_row$payoff_treatment == payoff_treatment),]
	matrix <- rep(0,4)
	for(ii in 1:4) {
		matrix[ii] <- matrix_row[1, paste("X", ii, sep = "")]
	}
	bot <- matrix[4]
	for(ii in 1:4) matrix[ii] <- matrix[ii] - bot
	defl <- matrix[1]
	matrix <- matrix/defl
	matrix <- 100 * matrix
	return(matrix)
}

get_matrices <- function(){
	matrices <- matrix(0, nrow(hbtreatments), 4)
	for(ii in 1:nrow(hbtreatments)){
		matrices[ii,] <- get_matrix(hbtreatments$experiment[ii], hbtreatments$payoff_treatment[ii])
	}
	return(matrices)
}

get_deltas <- function(){
	deltas <- rep(0, nrow(hbtreatments))
	for(ii in 1:nrow(hbtreatments)){
		deltas[ii] <- hbtreatments$supergame_ending[ii]
	}
	return(deltas)
}

matrices <- get_matrices()
deltas <- get_deltas()

get_welfare <- function(ii){
	experiment <- hbtreatments$experiment[ii]
	treatment <- hbtreatments$treatment[ii]
	udata <- hbdata[which(hbdata$experiment == experiment),]
	udata <- udata[which(udata$treatment == treatment),]
	sessions <- unique(udata$session)
	for(jj in 1:NROW(sessions)){
		vdata <- udata[which(udata$session == sessions[jj]),]
		matches <- unique(vdata$match_period)
		if(NROW(matches) < 5) return(-2001)
	}
	return(1)
}


make_report <- function(ii, ct){
	ewelf <- get_welfare(ii)
	#for there are cases where there are fewer than 15 match periods
	if(ewelf != -2001){
		mat <- matrices[ii,]
		print(paste(hbtreatments$experiment[ii], hbtreatments$treatment[ii], deltas[ii]))
		ct <- ct + 1
		print(mat)
	}
	return(ct)
}

report_all <- function(){
	ct <- 0
	for(ii in 1:nrow(hbtreatments)) ct <- make_report(ii, ct)
	print(ct)
}
	
report_all()

