working version but need optimisation