Fixed a number of out of bounds accesses.

Visual Studio's static code analyser found a number of out of bounds array accesses. This commit fixes a number of them as well as a few other problems the analyser brought up.

This also fixes #1 in the issue tracker.