fix bug and code cleanup