lots of minor logic/syntax fixes