moved buffer length check to appropriate part of loop