Issue #6: Merge Duanjun's patch and fix bugs