#############################################################################################
# Loads membership vectors processed using external tools.
# 
# 01/2016 Vincent Labatut
#############################################################################################
source("src/define-constants.R")



#############################################################################################
# Loads the partition estimated by the external tools (their file format needs a specific
# conversion processing).
#
# f.name: the path and name of the file or folder to load (depends on the format).
# algo.name: code representing the concerned (external) partitioning algorithm.
# keep.tmp: whether or not to keep the original files generated by the algorithm.  
#
# returns: the corresponding partition as a membership vector.
#############################################################################################
load.external.partition <- function(f.name, algo.name, keep.tmp)
{	
#	if(startsWith(algo.name,COMDET.ALGO.ILS) || startsWith(algo.name,COMDET.ALGO.GRASP))
#		result <- load.mestrado.partition(f.name, algo.name, keep.tmp)
	
	if(algo.name == CORCLST.ALGO.ExCC)
		result <- load.ExCC.partition(f.name)
	
#	else if(startsWith(algo.name,COMDET.ALGO.KMBS))
#		result <- load.KMBS.partition(f.name, algo.name)
	
	else
	{	# TODO treat other external tools here
	}
	
	return(result)
}





################################################################################
# Loads the partition estimated by the ExCC tool.
# 
# file.name: the path and name of the file to load.
#
# returns: the corresponding partition as a membership vector.
###############################################################################
load.ExCC.partition <- function(part.folder)
{	
	ExCC.output.file <- file.path(part.folder, ExCC.RESULT.FILENAME)
	
	# open and read the file
#	print(file.name)
	con <- file(ExCC.output.file, "r")
	lines <- readLines(con, warn = FALSE)
	close(con)
	
	
	# process the file content
	i <- 1
	line <- lines[i]
	res <- list()
	
	# TODO: change here if the result file has more information than just the partition
	# in that case, put this line: while(line!="")
	while(!is.na(line)) # line!=""
	{  # process current line
		#print(line)
		line <- strsplit(x=line, "[", fixed=TRUE)[[1]][2]
		line <- strsplit(x=line, "]", fixed=TRUE)[[1]][1]
		
		# we increment by 1 at the end because C++ starts counting from 0
		nodes <- as.integer(strsplit(x=line,", ", fixed=TRUE)[[1]]) + 1
		
		res[[length(res)+1]] <- nodes
		
		# process next line
		i <- i + 1
		line <- lines[i]  
	}
	
	
	# build the membership vector
	mx <- max(unlist(res))
	membership <- rep(NA,mx)
	for(i in 1:length(res))
	{  nodes <- res[[i]]
		membership[nodes] <- i 
	}
	
#	# record the partition using the internal format
#	write.table(x=membership, file=partition.file, row.names=FALSE, col.names=FALSE)
	
	return(membership)
}


