Clean up and reorganize code