Implementing this in Perl would be cleaner IMO.