Code cleanup and fixing minor bug