added debug output and fixed small bugs - testing needed