Some time ago I have thinking about something similar, you can see code snippet in Java for my proposition here: