streamlined code a bit, added comments