Working decoding algorithm. Deciphering works as well