Port py implemenation to perl. Needs testing.
cleanup
Bugfixes