Updated logic for writing output to stderr.
Added comments. Removed code cruft. Fixed mispelling..