just realized that 1 db query could avoid 500 lines of code....