# TODO: Add comment
# 
# Author: E.Korsching Jun 18, 2014
###############################################################################


# source all functions of the 0function folder and its subfolders
#  or a folder without subfolders


source.folder <- function(fp=NULL, sub=T, reg.exp="^0functions$", start.search="/home"){
	# source() all R files of a folder (if requested also recursive) in the present workspace
	# fp : get folder path, if none, the folder 'reg.exp' will be searched for starting in the 'start.search' folder
	# sub : flag : T : source also subfolders to 'reg.exp', F : only 'reg.exp' folder level
	
	# search for folder 'reg.exp' in all subfolders of 'start.search' or take the given ('fp')
	if(is.null(fp)){
		fp <- dir(path=start.search, pattern=reg.exp, all.files=F, full.names=T, recursive=T, ignore.case=F, include.dirs=T, no..=F)
	}
	
	# generate a list of subfolders or not
	if(sub){
		proj.dirs <- list.dirs(path=fp, full.names=T, recursive=sub)
		proj.dirs.len <- length(proj.dirs)
		if(proj.dirs.len==0){ cat("\n no project subfolders in path \n") }
	}else{
		proj.dirs <- fp
		proj.dirs.len <- 1
	}
	
	# source all *.r *.R files
	nf <- 0		# file counter
	for(i in 1:proj.dirs.len){
		# filter on files with *.R or *.r  on that folder level (not recursive)
		all.r.source <- list.files(path=proj.dirs[i],	# if(proj.dirs.len==1){ proj.dirs }else{ proj.dirs[i] }
				pattern="([.]R$|[.]r$)", all.files=F, full.names=T, recursive=F, ignore.case=F, include.dirs=F) #, no..=F)
		all.r.source.len <- length(all.r.source)
		
		# work on that list of files
		if(all.r.source.len>0){
			for(j in 1:all.r.source.len){
				cat("\n",all.r.source[j])		# print entry
				source(file=all.r.source[j], local=F, echo=F, print.eval=F, verbose=F,
						prompt.echo=getOption("prompt"), max.deparse.length=150, chdir=FALSE,
						encoding=getOption("encoding"), continue.echo=getOption("continue"),
						skip.echo=0, keep.source=getOption("keep.source"))
				nf <- nf+1
			}
		}
	}
	
	#
	cat("\n\n sourced ",nf," files\n")
	return()
}


#source.folder(fp=NULL, sub=F, reg.exp="^0functions$", start.search="/home")
#source.folder(fp="/home/korschi/eclipseR/0functions/tdifferential", sub=T)



