Pull request to master

Already pushed with revisions (but I'm continuing tidying up the codes to make them more readable)