Uff... a lot of code to be written there. It could be much simpler than that...