Jajascript refactoring for optimisation. Need to be polished.