clean up the code a bit; fix bugs; add comments