Code refactored. Added/fixed inline documentation.