incorporating @jaimefrio's vectorized version