Tidied, commented, made more efficient