Fixed indexing for file writing