#!/usr/bin/Rscript --silent
# This script is the splitted cluster step from frame_proc
rem <- function(...) invisible(T)
rem( '
set opt0="%~F0"
shift
Rscript.exe %opt0% "%0" "%1" "%2" "%3" "%4" "%5" "%~F6" "%~F7","%~F8","%~F9"
EXIT /B
rem ')
### above=BAT, below=R
library(fpc)
library(optparse)

cluster_cells_k = function(qdata, OPTIMALK, algo) {
	algorithms = c("Hartigan-Wong", "Lloyd", "Forgy", "MacQueen")
	algorithm = algorithms[algo]
	clus <- kmeans(qdata, OPTIMALK, algorithm = algorithm, iter.max=100000, nstart=10)
	return(clus)
}

option_list <- list(
	make_option(c("-v", "--verbose"), action="store_true", default=FALSE,
	help="Print extra output [default=false]"),
	make_option(c("-a", "--algo"), type="integer", default=1,
	help="1 - Hartigan-Wong, 2 - Lloyd, 3 - Forgy, 4 - MacQueen [default %default]",
	metavar="number"),
	make_option(c("-m", "--time"), type="integer", default=0,
	help="minutes from start [default %default]",
	metavar="number"),
	make_option(c("-k", "--optimalk"), type="integer", default=2,
	help = "Optimal k [default %default]")
)
opt_parser <- OptionParser(usage = "usage: %prog [options]", option_list = option_list, description = "Post-proc object table", epilogue = "Send feedback to mackoel@gmail.com")
flaggs <- parse_args(opt_parser, args = commandArgs(trailingOnly = TRUE), print_help_and_exit = TRUE, positional_arguments = TRUE)
opts <- flaggs$options
args <- flaggs$args
infile <- args[1]
outfiles <- unlist(strsplit(args[2], ",", fixed=TRUE))
outfilecsv <- outfiles[1]
filenm <- outfiles[2]
qdata <- read.csv(infile)
wdata <- qdata[,c("xmean", "ymean")]
cl <- cluster_cells_k(wdata, opts$optimalk, opts$algo)
qdata <- cbind(qdata, cell=cl$cluster)
png(filename = basename(filenm), width = 300, height = 300, units = "px", pointsize = 12)
colours <- rainbow(opts$optimalk)
plot(qdata[qdata$cell == 1,]$xmean, 1024 - qdata[qdata$cell == 1,]$ymean, xlim = c(0,1024), ylim = c(0,1024), type = 'p', pch = 1, col = colours[1], main = "Cells", xlab = "Column", ylab = "Row", asp = 1)
for (i in 2:opts$optimalk) {
	lines(qdata[qdata$cell == i,]$xmean, 1024 - qdata[qdata$cell == i,]$ymean, type='p', pch=i, col=colours[i])
}
res <- dev.off()
write.csv(file=outfilecsv, qdata, row.names=F)

