library(e1071)
library(pixmap)

readFaceImages <- function(file) {

	x <- scan(file, what=character())
	x <- substring(x, 35)

	Y <- sapply(x, function(z) strsplit(z, "_", fixed=TRUE)[[1]])
	Y <- t(Y)
	Y <- Y[, 2:4]
	colnames(Y) <- paste("Y", 1:3, sep="")
	Y <- data.frame(Y)

	images <- sapply(
		x,
		function(file) {
			image <- read.pnm(file)
			as.vector(t(attr(image, "grey")))
		}
	)
	images <- t(images)

	list(images=images, Y=Y)
}

list1 <- readFaceImages("straightrnd_train.list")
list2 <- readFaceImages("straightrnd_test1.list")

trainingData <- cbind(data.frame(list1$images), list1$Y[3])

m <- svm(Y3 ~ ., data=trainingData, kernel="linear")
print(m)

t1 <- table(predict(m), list1$Y[[3]])
print(t1)
cat("Accuracy on training set: ", 100 * sum(diag(t1)) / sum(t1), "%\n", sep="")

testData <- data.frame(list2$images)
t2 <- table(predict(m, testData), list2$Y[[3]])
print(t2)
cat("Accuracy on test set: ", 100 * sum(diag(t2)) / sum(t2), "%\n", sep="")
