added 3-channels support to optimized version