Huge refactoring.
Partially working but data got inserted twice. Need further investigation.