Fixes bug 1368154

Also added more unit tests and fixed some pep8 issues.