I totally agree on the fact that this should be done in a more efficient way.
However my actual knowledge don't allow me do fix this easily, so why not improve this later, given that it's functionnal.