Modified to simplify loops and attempt to create file as output
Reverted to working version, moved updates elsewhere