fixed several bugs; got loop running in constant space