A lot of refatoring, fixing bug #3