fixed several bugs and working on vectorized code