code refactore, seems to be working finally