Rearranged JS a bit to accommodate testing and added new tests.