Restructure and clean up existing code