Refactor code and gallery bugfix