working and optimized sequential code