Code clean-up and bugfixes