fixed problem which was previously causing failure and some small optimizations