bug hunt and code cleanup