Buffer issues

@trustin could you please review and if you think it is ok I would merge it into 4.0 and master.