merged with chao's code