Complete overhaul

added all tests which uncovered a whole range of bugs