Optimisation

rewrote most of the functions