Should've written this in ruby ;-) Sorry, but bash is ugly!