Fix some logic errors, make printf safe, tidy up file.