Final functions implementation. Fully tested. (couple of spaces added for readability)