New completely re-written version: major bugfixes + detailed comments