fixed a lot of bugs, but there is still an infinite loop. Check comments in code