Working version with output length control