rebuilt r code using functions for all discrete processes to improve memory recovery