fixing a bug & refactoring code