restructured and optimized code