fixed some encoding bugs, now writing to file as well.