optimized and cleaned up code