fixed bugs and wrote output function
fixed bugs