Fix Coverity bug 603941: Negative array index read

Signed-off-by: Philippe Saint-Pierre <stpere@gmail.com>
CID 991761: potential double close (and white space fix)
CID 1108469: Use after free
Fix Coverity bug 1108392: Stray semicolon

Signed-off-by: Philippe Saint-Pierre <stpere@gmail.com>