Reformatted code and improved finalising of data.