Major refactoring for more readable code