General code cleanup

This pull request contains two commits:

1) Remove trailing whitespace in files, including one file converted from dos EOLs
2) General code cleanup

The changes in 2) are best viewed as a diff against 1).

I will add a few line comments for clarity and spots where things might have been correct but someone more familiar with the code would have a better idea; and I will happily revert any bits that shouldn't be changed.