Bug fixes and PEP8 compliant (except for line len)