Code cleanup and improvements suggested by @zjonsson