fixed buffer access and some small opimizations