added some more safeguards
code cleanup part I