Importing dave's original version
Ran perltidy to make it more legible.