restart of branch, this is to include changes from trunk
merged fixes from previous instance of branch (r38875:40542), addressing #856 and #586
removed whitespace at the end of lines
formatted code: removed whitespace at end of lines and added some empty lines to increase readability
formatted code: added some empty lines to increase readability
removed compiler warning about missing newline at end of file
fixed signedness of variable and cleaned up whitespace
Test case and possible fix for Issue #1002