 packageExpand = function(packagelist,fl) {
   res = NULL
   for (i in c(1:length(packagelist))) {
     s = packagelist[i]
     ls = nchar(s)
     spos = which(substr(fl,1,ls) == s,arr.ind=T)
     lspos = length(spos)
     if (lspos > 0)
       {
       fullname = fl[spos]
       if (grepl('*.gz',fullname)) {
            row = paste(ps,fullname,pe,sep='')
            res = append(res,row)
            }
       }
     }
   return(res)
 }

 getPackages = function(packs)
   {
   packages = unlist(tools::package_dependencies(packs, available.packages(),
         which=c("Depends", "Imports"), recursive=TRUE))
   packages = union(packs, packages)
   packages
   }

 ourargs = commandArgs(TRUE)
 if(length(ourargs)==0){
       print("No arguments supplied.")
    }else{
    for(i in 1:length(ourargs)){
        eval(parse(text=ourargs[[i]]))
    }
 }

 unesc = function(x) {
   res = x
   res = gsub('__lt__','<',res)
   res = gsub('__gt__','>',res)
   return(res)
 }

 our_packages = strsplit(ourpackages," ")[[1]]
 ps=unesc(xmlprefix)
 pe="?raw=true</package>"

 print(paste('tardir=',tardir,'xmlprefix=',xmlprefix,'ourpackages=',ourpackages,'OUTPATH=',OUTPATH))


 setRepositories(ind=1:2)
 chooseBioCmirror(ind=7,graphics=F) # canberra - use eg 1 for FredHutch
 chooseCRANmirror(ind=5,graphics=F) # Melbourne - use 96 for texas

 ifreq = function(pkg='DESeq2') {
 if(require(package=pkg,character.only = T)){
   print(paste(pkg,"is loaded correctly"))
 } else {
   print(paste("trying to install",pkg))
   install.packages(pkg)
   if(require(package=pkg,character.only = T)){
   print(paste(pkg,"installed and loaded correctly"))
   } else {
     stop(paste("Could not install",pkg))
   }
 }
 }

 ifreq(pkg="BiocInstaller")
 ifreq(pkg="pkgDepTools")
 ifreq(pkg="Biobase")

 print.noquote('Greetings! The R you have chosen is using the following repositories:')
 print.noquote(biocinstallRepos())
 packages = getPackages(our_packages)
 download.packages(pkgs=packages,destdir=tardir, type="source", repos=biocinstallRepos())
 flist = list.files(tardir)
 allDeps = makeDepGraph(biocinstallRepos(), type="source", keep.builtin=F, dosize=F)
 res = NULL
 for (i in c(1:length(our_packages))) {
   package = our_packages[i]
   io = getInstallOrder(package, allDeps, needed.only=FALSE)
   ares = packageExpand(packagelist=io$packages,fl=flist)
   res = append(res,ares)
   }
 ures = unique(res)
 tout = "savedeps.xml"
 write.table(ures,file=tout,quote=F,sep="\t",row.names=F,col.names=F)
 write.table(ures,file=OUTPATH,quote=F,sep="\t",row.names=F,col.names=F)
 print.noquote(res)
 sessionInfo()
 print.noquote(date())