some bug fixes and split script into bash and R parts so can multicore