bug fixes by Kuan-Chung Chiu <buganini at gmail dot com>. Tested by me in production for several days at work.