Added output writing subroutine