Tidying the code and adding comments