lot of (untested) bug fixes! props Jonas Lundman