added some comments, reordered some sections, explicit check on size of data that is read