Except as otherwise stated, the code is copyright 2014 Juris Breidaks, Martins Liberts