Fix several medium impact CID issues V2

Updated version of pull request #330
- incorporated comments
- dropped some no longer needed patches
- merged two patches into one