#FUNCTION TO CHECK FOR / INSTALL / REQUIRE THE PACKAGE
######################################################################
installLoadPkg<-function(
	quotedPackageName="devtools",
	prefLibPath=.libPaths()[length(.libPaths())],
	myGetDependencies=TRUE,
	faveMirrorIndex=1
	) {
	#A. If its not already there...
	if(!any(search()==paste0("package:",quotedPackageName))) {
#	if(length(grep(quotedPackageName,search()))==0) {

		 #	1. get list (as matrix) from all paths
		myPackages<-installed.packages(lib.loc=NULL)

		#	2. search list for what you want
		doIHavePackage<-any(myPackages[,1]==quotedPackageName)
		#doIHavePackage<-grep(quotedPackageName,myPackages[,1])
		print("var doIHavePackage:")
		print(doIHavePackage)

		#	3. if you dont have the package...
		if(doIHavePackage==FALSE) {
		#if(length(doIHavePackage)==0) {
		
			#	a. spcify the mirror
			#		i. get list
			theMirrors<-getCRANmirrors(all = FALSE, local.only = FALSE)
			#		ii. find your fave
			#preferredMirrorString<-faveMirrorString #saras preference is often "USA (TX)"
			thePrefMirror=faveMirrorIndex 
			#thePrefMirror<-which(theMirrors[,"Name"]==preferredMirrorString)
			#print(theMirrors[(thePrefMirror-2):(thePrefMirror+2),])
			#		iii. set it as preferred
			options(repos=theMirrors$URL[thePrefMirror])
			print(getOption("repos"))
			
			#	b. get the package and its dependencies
			install.packages(pkgs=quotedPackageName, 
				lib=prefLibPath, 
				repos = getOption("repos"),
				dependencies = myGetDependencies
			)
		}
		
		#	4. now require the package
		myCmd<-paste0("didILoad<-library(",quotedPackageName,",quietly=F,logical.return=T,verbose=T,warn.conflicts=T)")
		print(myCmd)
		eval(parse(text=myCmd))
		print("Loaded packages:")
		print(search())
	
	#B. If it IS already there...
	} else {
		whichOne<-grep(quotedPackageName,search())
		print(paste0("- - - - - - - - ",quotedPackageName," already in search path as #",whichOne," - - - - - - - -")) 
		print(search())
		print("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -")
	}
		
}
