Code clean up and minor bug fixes