complete code re-write