Patched with bugfixes post unit testing and perltidy prettyfied.