##################################
#                                #
# Last modified 2025/02/11       # 
#                                #
# Georgi Marinov                 #
#                                # 
##################################

import sys
import string
import os
import math
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 

def combine_images(columns, space, images, outfilename):

    rows = len(images) // columns
    if len(images) % columns:
        rows += 1
    width_max = max([Image.open(image).width for image in images])
    height_max = max([Image.open(image).height for image in images])
    background_width = width_max*columns + (space*columns)-space
    background_height = height_max*rows + (space*rows)-space + 20
    background = Image.new('RGBA', (background_width, background_height), (255, 255, 255, 255))
    x = 0
    y = 20
    for i, image in enumerate(images):
        img = Image.open(image)

        draw = ImageDraw.Draw(background)
        fontsize=50
        font = ImageFont.truetype("CALIBRI.TTF",fontsize)

        x_offset = int((width_max-img.width)/2)
        y_offset = int((height_max-img.height)/2)
        background.paste(img, (x+x_offset, y+y_offset))
        print x,y
        sublabel = 'pattern_' +  outfilename.split('.pattern_')[-1].split('.n_')[0] + ', n=' + outfilename.split('.pattern_')[-1].split('.n_')[-1].split('.')[0] + '; subpattern_' +  image.split('subpattern_')[-1].split('.ns')[0] + ', ns=' + image.split('subpattern_')[-1].split('.ns_')[-1].split('.')[0]
        draw.text((x, y-20),sublabel,(0,0,0),font=font)
        x += width_max + space
        if (i+1) % columns == 0:
            y += height_max + space
            x = 0
    background.save(outfilename)

def run():

    if len(sys.argv) < 3:
        print 'usage: python %s config columns' % sys.argv[0]
        sys.exit(1)

    config = sys.argv[1]
    Ncols = int(sys.argv[2])

    PNGfilesDict = {}

    linelist = open(config)
    for line in linelist:
        if line.startswith('#'):
            continue
        fields = line.strip().split('\t')
        label = fields[0]
        PNG = fields[1]
        if PNGfilesDict.has_key(label):
            pass
        else:
            PNGfilesDict[label] = []
        PNGfilesDict[label].append(PNG)

    for label in PNGfilesDict.keys():
        print label
        PNGfilesDict[label].sort()
        combine_images(columns=Ncols, space=50, images=PNGfilesDict[label], outfilename=label + '.png')

run()

