put_input <- function(path, typecode=1:2,
                      initial_cases=matrix(1L, 2, 2),
                      susceptibles=matrix(30L, 2, 2),
                      proportionalities=matrix(c(.001, .005), 2, 2, byrow=TRUE),
                      latent_periods=matrix(1, 2, 2), max_time=100,
                      maxinftime=matrix(c(-1L, -1L), 2, 2, byrow=TRUE),
                      alphas=matrix(3, 2, 2), betas=matrix(.67, 2, 2),
                      nreps=2L, jump=0L, obn=rep(0L, 2)){
  s <- new(simo.SimSet)
  for(i in 1:nrow(initial_cases)){
    p <- new(simo.SimInput)
    p$type <- typecode
    p$max_time <- max_time
    p$initial_cases <- as.integer(initial_cases[i,])
    p$susceptibles <- as.integer(susceptibles[i,])
    p$proportionalities <- proportionalities[i,]
    p$latent_periods <- latent_periods[i,]
    p$alphas <- alphas[i,]
    p$betas <- betas[i,]
    p$maxinftime <- maxinftime[i,]
    p$obn <- obn[i]
    replicate(nreps, s$add("siminput", p))
  }
  s$jump <- jump
  s$serialize("simo-in.pb")
}

get_output <- function(path="simo-out.pb", clean=TRUE, path2="simo-in.pb") {
  con <- file(path, open="rb")
  message <- read(simo.SimOutput, con)
  close(con)
  if (clean) {
    unlink(path)
    unlink(path2)
  }
  with(message, data.frame(obn, outbreak_id, type, latent_start,
                           infective_start, isolated_start, recovered_start))
}

prep_sim <- function(){
  require(RProtoBuf)
  readProtoFiles(package="EpiGLM")
}

run_sim <- function(..., workdir=tempfile("simo_dir_")){
  dir.create(workdir, recursive=TRUE)
  original_dir <- getwd()
  setwd(workdir)
  on.exit(setwd(original_dir))  
  put_input(...)
  script <- system.file(file.path("simo", "simo.py"), package="EpiGLM")
  foo <- system(paste(script, "2>&1"), intern=TRUE)
  if (is.null(attributes(foo))) {
    get_output() } else {
      print(foo)
      print(system("uname -a", intern=TRUE))
    }
}
