Need to factor and speed up code