tools: Fix bugs, add sanity checks