Major refactoring and removing global variables (g_*)