Code reorganised and optimized