def populateCategory(cat = None):
    '''
    Populate a category with uncategorized images and images from parent categories
    '''
    galleries = []
    categories = []
    uncatStats = 0
    recatStats = 0
    wikipedia.output(u'Working on ' + cat.title())
    #Find gallery with the same name
    if wikipedia.Page(wikipedia.getSite(), cat.titleWithoutNamespace()).exists():
    	galleries.append(cat.titleWithoutNamespace())
    #Find hint
    hint = findGalleryHint(cat.get())
    if not hint == u'':
        galleries.append(hint)
    
    # Get the current categories
    categories = imagerecat.getCurrentCats(cat)

    if galleries:
        imagesInGalleriesGenerator = getImagesInGalleriesAndCategories(galleries, categories)
	for image in imagesInGalleriesGenerator:
	    if image.categories():
	        #The image contains categories
		recatStats = recatStats + replaceCategory(image, categories, cat.titleWithoutNamespace())
	    else:
	        #No categories
		uncatStats = uncatStats + addCategory(image, cat.titleWithoutNamespace())

    #Remove the template, leave stats.
    removePopulateCategoryTemplate(cat, uncatStats, recatStats)
def replaceCategory (image = None, parents = [], newcat = u''):
    '''
    Remove all parent categories and add newcat
    '''
    result = 0
    newcats = []
    if not newcat == u'':    
        currentCats = imagerecat.getCurrentCats(image)
	workingCategories = currentCats
	workingCategories.append(newcat)
	# Adding parents if the category filter is lagging.
	# The bot often works on new categories. In these cases the filter does know the parent categories
	workingCategories = workingCategories + parents
        for cat in imagerecat.applyAllFilters(workingCategories):
	    #Now remove those parents again
	    if cat not in parents:
                newcats.append(cat)
	if not(set(currentCats)==set(newcats)):
	    newtext = wikipedia.removeCategoryLinks(image.get(), image.site()) + u'\n'
	    for category in newcats:
	        newtext = newtext + u'[[Category:' + category + u']]\n'
	    comment = u'Moving image to (a subcategory of) [[Category:' + newcat + u']] and trying to filter categories'
	    wikipedia.output(image.title())
	    wikipedia.showDiff(image.get(), newtext)
	    image.put(newtext, comment)
            result = 1
    return result