re-factored the code to vectorize as much as possible.