code cleanup, documentation and additional error hhandling