[Issue #336] code cleanup and bug fixes