simplified code and possible parfor bug fix