fixed record count in writing
some cleanup