Fixed intermediate file opening code to truncate existing files. Minor other refactoring and cleanup.