fixed bug, need to clean up code and write to output stream