Fixed security vulnerability, diagnosed in bug 39883 by Harald

Also improved some formatting, and removed unused code.

Change-Id: I19300e7987fb53aaef414d3a845e59435e6625cb