Code refactoring, bug fixing and perltidy'ing