If the sequence of the last 3 numbers is not important (does not appear to be), then this appears to be relatively trivial. Unfortunatley, like the OP , I can only do this in ruby.
I'll attempt to do it tonight, and reply to you on here when its done.