Fixed compile errors, moved much of computation to helper() function