Fixed various problems described in bug 1030473.
Optimized performance and style following suggestions reported by cppcheck:
1. Used !xxxx.empty() instead of xxxx.size(), because it can be faster. xxxx.size() can take linear time while xxxx.empty() is guaranteed to take constant time.
2. Defensive programming: Reordered array-out-of-bound condition checks such as '(a[i] && i < 10)' to '(i < 10 && a[i])'. That way the array will not be accessed, because the index is checked first.. Fixes: . Approved by Daniel van Vugt, Sam Spilsbury.