improve logic and reduce number of db calls