Changed 'printf' to 'fprintf' wherever it makes sense