# TODO: Add comment
# 
# Author: E.Korsching 07.12.2011
###############################################################################



enumeration.search.dep.ssq.f90 <- function(x, refset, testset, method="Pearson", output="boot.raw.col", ssqflag=1){
	# R: original data set, calculating all global ssq for a distribution
	# Fortran dll: enumeration of all permutations, calculate all global ssq, fortan output in files
	# input: x - dataframe - table of data, col names: variables, row names: patients, genes, etc.
	#   refset: reference columns, testset: test columns, method: L2 (Euclidean), Pearson, Spearman
	# output: see proximity.bootstrap.sampling()
	# (!) doing a full enumeration -> check if appropriate
	
	# ini
	nr <- length(testset)
	nc <- length(refset)
	
#	nre <- factorial(nr)	# will be done in Fortran
	
	# compile similarity table
	anzSamplings <- 0	# no sampling/bootstrap	 only original matrix
	z <- proximity.bootstrap.sampling(x, refset=refset, testset=testset, anzSamplings=anzSamplings, method=method, output=output)
	if(is.null(z)){ stop("\n errors in fn: proximity.bootstrap.sampling") }
	erg <- 1	# flag, return value: ok := 0 ; error := 1
	
	# Fortran definitions
	mode(z) <- 'single'				# as.integer() assignment destroys the matrix structure (results in a vector)
	mode(nr) <- 'integer'
	mode(nc) <- 'integer'
	anzSamplings <- anzSamplings+1			# number of samplings/bootstraps plus original set
	mode(anzSamplings) <- 'integer'
	mode(erg) <- 'integer'
	mode(ssqflag) <- 'integer'					# flag: '1': ssq in x, '2': ssq in y
	
	# Fortran call (very early code)
#	dyn.load("/home/korschi/on3/eclipseR/searchdep08/Release_Intel64/searchdep08.so")		# intel f
	dyn.load("/home/korschi/on3/eclipseR/searchdep08/gf/lib_sd08_01.so")					# gnu f
	f.back <- .Fortran("workflow",
				x=z,
				nr=nr,
				nc=nc,
				anzBoots=anzSamplings,
				erg=erg,
				ssqflag=ssqflag
		)
#	dyn.unload("/home/korschi/on3/eclipseR/searchdep08/Release_Intel64/searchdep08.so")		# intel f
	dyn.unload("/home/korschi/on3/eclipseR/searchdep08/gf/lib_sd08_01.so")					# gnu f
	
	return(f.back$erg)	# return flag
}

#3628800 rows -works
#enumeration.search.dep.ssq.f90(He589.c, refset=c(1,5,3,2,12,13), testset=c(4,6:11,14:16), method="Pearson", output="")



#factorial(7);factorial(8);factorial(9);factorial(10)		#5040,40320,362880,3628800 rows



