Fix #1011 and add tests