# Recipe 41: Blend two pictures

def blendPictures(blendfactor1, blendfactor2):
  pic1 = makePicture(getMediaPath("thailand-06.jpg"))
  pic2 = makePicture(getMediaPath("thailand-07.jpg"))
  # The size of both pictures is 533 x 400 pixels

  canvas = makeEmptyPicture(982,453)

  # Step 1: Copy first 400 columns of picture 1 (with big boat)
  sourceX = 1
  for targetX in range(1, 450):
    sourceY = 1
    for targetY in range(1,getHeight(pic1)+1):
      color = getColor(getPixel(pic1, sourceX, sourceY))
      setColor(getPixel(canvas, targetX, targetY + 53), color)
      sourceY = sourceY + 1
    sourceX = sourceX + 1

  # Step 2: Copy the overlapping (blending) columns
  overlap = getWidth(pic1) - 450
  sourceX = 1
  for targetX in range (450, getWidth(pic1)):
    sourceY = 1
    for targetY in range(1, getHeight(pic2)+54):
      if sourceY < 54: #if the second picture isnt overlapping the first only copy pixels from the second
        pixelpic2color = getColor(getPixel(pic2, sourceX, sourceY))
        setColor(getPixel(canvas, targetX, targetY), pixelpic2color)
      elif sourceY > (getHeight(pic2)): #if the first picture isnt overlapping the second only copy pixels from the first
        pixelpic1color = getColor(getPixel(pic1, sourceX + 450, sourceY - 53))
        setColor(getPixel(canvas, targetX, targetY), pixelpic1color)
      else: #if the pictures are overlapping then blend thier pixels and copy the blended pixels
        pixelPic1 = getPixel(pic1, sourceX+450, sourceY - 53)
        pixelPic2 = getPixel(pic2, sourceX, sourceY)
        newRed =   blendfactor1*getRed(pixelPic1) + blendfactor2*getRed(pixelPic2)
        newGreen = blendfactor1*getGreen(pixelPic1) + blendfactor2*getGreen(pixelPic2)
        newBlue =  blendfactor1*getBlue(pixelPic1) + blendfactor2*getBlue(pixelPic2)
        color = makeColor(newRed, newGreen, newBlue)
        setColor(getPixel(canvas, targetX, targetY), color)
      sourceY = sourceY + 1
    sourceX = sourceX + 1

  # Step 3: The rest of picture 2
  sourceX = overlap
  for targetX in range(450+overlap, 450+getWidth(pic2)):
    sourceY = 1
    for targetY in range(1,getHeight(pic1)+1):
      color = getColor(getPixel(pic2, sourceX, sourceY))
      setColor(getPixel(canvas, targetX, targetY), color)
      sourceY = sourceY + 1
    sourceX = sourceX + 1

  show(canvas)
  return canvas

