# This R profile can be used when a cluster does not allow spawning or a job 
# scheduler is required to launch any parallel jobs. Saving this file as 
# .Rprofile in the working directory or root directory. For unix platform, run
# mpirexec -n [cpu numbers] R --no-save -q
# For windows platform with mpich2, use mpiexec wrapper and specify a working 
# directory where .Rprofile is inside.
# Cannot be used as Rprofile.site because it will not work

# Following system libraries are not loaded automatically. So manual loads are 
# needed.
print("mpiR is started - snow!")

.libPaths(c('~/rpacks', .libPaths()))

library(utils)
library(stats)
library(datasets)
library(grDevices)
library(graphics)
library(methods)
library(snow)
library(snowfall)

if (!library(Rmpi,logical.return = TRUE)){
    warning("Rmpi cannot be loaded")
    q(save = "no")
}

options(error=quote(assign(".mpi.err", FALSE, env = .GlobalEnv)))

if (mpi.comm.size(0) > 1)
    invisible(mpi.comm.dup(0,1))
if (mpi.comm.rank(0) >0){
print("Start Slave")

sink(file="/dev/null")
.First.sys()
slaveLoop(makeMPImaster())
mpi.quit()

} else {
 print("Start Master")

cl<-makeMPIcluster()
cl<-makeMPIcluster()
sfInit()

option<-getFromNamespace( ".sfOption", "snowfall" )
option[['nodes']]<-length(cl)
option[['type']]<-'MPI'
option[['cluster']]<-cl
option[['parallel']]<-TRUE
assignInNamespace(".sfOption",option,"snowfall")

.Last <<- function(){
cl <- getMPIcluster()
if(!is.null(cl))
stopCluster(cl)
mpi.quit()	
}
}
