added tracking and fixed some bugs in writing the last page