BiDi support

Hi, please review. I tried following the coding standard. This contains BiDi functionality that seems sufficient for most purposes.