remove dead code, improve comments, add sanity-checks and defensive programming