Code cleanup and some small fixes