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



enumeration.search.dep.boots.f90 <- function(x, anzSamplings=0, refset, testset, method="Pearson", zz=NULL, sampleonly=F, output="boot.raw.col", ssqflag=1){
	# Create a proximity table (and some more results)
	# Fortran dll: enumerationof all permutations, calculate best ssq for each bootstrap / real sample and bring back list of results
	# input: x - dataframe - table of data,  column names: proteins etc.,  row names: patients etc.
	# refset: reference columns, testset: test columns,   method: L2 (Euclidean), Pearson, Spearman
	# zz: provide an existing 'proximity.bootstrap.sampling()' dataset
	# sampleonly: T: return only the sampling/bootstrap matrix
	# anzSamplings: Number of samplings/bootstraps to be performed, the original data set is included at the first position
	# (!) doing a full enumeration -> check if appropriate
	
	# ini
	nrx <- dim(x)[1]
	ncx <- dim(x)[2]
	nr <- length(testset)
	nc <- length(refset)
	
	PosPerm <- matrix(0,(anzSamplings+1),(nr+1))
	ssq <- matrix(0,(anzSamplings+1),5)
	
	# create a data set or take an existing data set
	if(is.null(zz)){
		z <- proximity.bootstrap.sampling(x, refset=refset, testset=testset, anzSamplings=anzSamplings, method=method, output=output)
		if(is.null(z)){ cat("\n errors in fn: proximity.bootstrap.sampling "); return() }
	}else{		#else use zz as z
		z <- zz
	}
	
	if(sampleonly){ return(z) }		# generate only the sampling/bootstrap matrix as a result; can be later assigned in zz 
	
	#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(PosPerm) <- 'integer'
	mode(ssq) <- 'single'
	mode(ssqflag) <- 'integer'					#flag: '1': ssq in x, '2': ssq in y
	
	#Fortran call
	dyn.load("/home/korschi/on3/eclipseR/searchdep09/gf/lib_sd09_01.so")
	f.back <- .Fortran("workflow",
				x=z,
				nr=nr,
				nc=nc,
				anzBoots=anzSamplings,
				PosPerm=PosPerm,			#row number for min, test factor order vec
				ssq=ssq,					#min ssq, min ssq second way, max ssq,
											# ssq of bootstrap sample with the order giving the min in the original sample,
											# sum of all ssq results - control must be the same result in each sample by a "no replace" sample
				ssqflag=ssqflag
		)
	dyn.unload("/home/korschi/on3/eclipseR/searchdep09/gf/lib_sd09_01.so")
	
	return( list(f.back$PosPerm, f.back$ssq, z) )
}


#aaa1 <- enumeration.search.dep.boots.f90(He589.c,anzSamplings=4,refset=c(1,5,3),testset=c(4,6,14,16),method="cor",zz=aaaz, ssqflag=1)
#aaa2 <- enumeration.search.dep.boots.f90(He589.c,anzSamplings=4,refset=c(1,5,3,2,12,13),testset=c(4,6:11,14:16),method="cor", ssqflag=1)


