added a function to query the images or add them if not available and move commit() into the loop