fixed a bunch of bugs and extensively tested it