Updated with proper organization of code