Code cleanup and restructure