added documentation and some better scoping