refactored for documenting, packaging, tests and some bug fixes