improved code for bwt encoder