Fix #524 plus some bugs