Fix some bugs, make it a bit more robust