Fixed many bugs

All these are from PhpStorm inspection.