refactore code and fixing for bugs

refactore code and fixing for bugs