[SPARK-4409] Incorporated mengxr's code