fix bugs, add more defensive checks