code refactoring, move variables to top and reformat ifdefs