fix some bugs via timwintle's excellent fork