Wrote the algorithm to create galleries