factored code, added documentation