Check buffer length and refactor for nicer code