Python fold function

Refactored python folding. Fixed bugs