incorporated changes from karthik and naim, fixes #170, should be close to submit