from JascApp import *

def ScriptProperties():
    return {
        'Author': 'Victor Reijs',
        'Copyright': '2005',
        'Description': 'Optimization with color scale',
        'Host': 'Paint Shop Pro',
        'Host Version': '8.10'
        }

import math
import sys
import sitecustomize
from scipy import *
from scipy.optimize import fmin_bfgs
import _winreg
import Image
import ImageWin


version=0.4
numbercolors=8
numberprimcolors=3
threshold=3
#should be 2.8
black=0
darkgrey=1
grey=2
white=3
blue=4
green=5
yellow=6
red=7
patch=['black','darkgrey','grey','white','blue','green','yellow','red']
primkleur=['red','green','blue']
ok=[1,1,1,1,1,1,1,1]
bmifrao1bmp=[(41, 37, 33), (63, 56, 53), (107, 97, 92), (228, 226, 222), (81, 64, 107), (107, 131, 82), (236, 207, 71), (158, 58, 42)]
gemetenkleur=[(41, 37, 33), (63, 56, 53), (107, 97, 92), (228, 226, 222), (81, 64, 107), (107, 131, 82), (236, 207, 71), (158, 58, 42)]
gammakleuren=[[47,46,47],[62,65,61],[116,114,114],[238,233,232],[65,62,116],[0,144,75],[245,211,0],[207,65,60]]
endkleur=[[47,46,47],[62,65,61],[116,114,114],[238,233,232],[65,62,116],[0,144,75],[245,211,0],[207,65,60]]
doelkleur=[[47,46,47],[62,65,61],[116,114,114],[238,233,232],[65,62,116],[0,144,75],[245,211,0],[207,65,60]]
ifrao1994sRGB=[[47,46,47],[62,65,61],[116,114,114],[238,233,232],[65,62,116],[0,144,75],[245,211,0],[207,65,60]]
ifrao2001sRGB=[[35,35,38],[63,65,65],[124,122,121],[235,234,240],[81,79,129],[0,150,82],[237,216,20],[194,67,53]]
ifrao1994Adobe=[[50,50,51],[65,67,64],[115,114,113],[236,233,231],[66,64,114],[77,142,80],[235,210,43],[179,67,62]]
ifrao2001Adobe=[[40,40,42],[66,67,67],[123,121,120],[234,233,240],[82,80,127],[84,148,87],[230,214,56],[169,68,56]]
gbi=[0.45455,0.45455,0.45455]
gbbmifrao1bmp=[0.44,0.50,0.51]
gb=[0.45455,0.45455,0.45455]
ge=[2.2,2.2,2.2]
colormatrixi=[1.,0.,0.,0.,1.,0.,0.,0.,1.]
colormatrixbmifrao1bmp=[2,-0.01,0.06,-1.06,1.11,-0.22,0.08,-0.09,1.25]
colormatrix=[1.,0.,0.,0.,1.,0.,0.,0.,1.]
gamma=0

#http://www.vallis.org/software/Simplex.py
#http://pylab.sourceforge.net/
#http://pylab.sourceforge.net/packages/optimize.py
#http://www.ifi.uio.no/~inf3330/scripting/doc/python/SciPy/tutorial/node11.html
#http://www.scipy.org/

def measure(Environment,x,y,dropper):
    App.Do( Environment, 'Eyedropper', {
            'Point': (x,y), 
            'SampleSize': dropper, 
            'Material': App.Constants.MaterialRef.Foreground, 
            'ActiveLayerOnly': App.Constants.Boolean.false, 
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Silent, 
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })
    Material = App.Do( Environment, 'GetMaterial', {
          'IsPrimary': App.Constants.Boolean.true,
         'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Silent, 
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }})
    App.Do( Environment, 'PaintBrush', {
            'BrushTip': {
                'BrushVariance': {
                    'SizeVariance': App.Constants.VarianceMethod.None, 
                    'SizeJitter': 0, 
                    'OpacityVariance': App.Constants.VarianceMethod.None, 
                    'OpacityJitter': 0, 
                    'DensityVariance': App.Constants.VarianceMethod.None, 
                    'DensityJitter': 0, 
                    'RotationVariance': App.Constants.VarianceMethod.None, 
                    'RotationJitter': 0, 
                    'ThicknessVariance': App.Constants.VarianceMethod.None, 
                    'ThicknessJitter': 0, 
                    'FadeRate': 100, 
                    'ColorBlendVariance': App.Constants.VarianceMethod.None, 
                    'ColorBlendJitter': 0, 
                    'HueVariance': App.Constants.VarianceMethod.None, 
                    'HueJitter': 0, 
                    'SaturationVariance': App.Constants.VarianceMethod.None, 
                    'SaturationJitter': 0, 
                    'LightnessVariance': App.Constants.VarianceMethod.None, 
                    'LightnessJitter': 0, 
                    'PositionJitter': 0, 
                    'UseScaledPositionJitter': App.Constants.Boolean.false, 
                    'ImpressionsPerStep': 1
                    }, 
                'Shape': App.Constants.BrushShape.Rectangular,
                'CustomBrush': None, 
                'Size': dropper*2+1, 
                'Hardness': 100, 
                'Density': 100, 
                'Rotation': 0, 
                'Thickness': 100, 
                'Step': 25
                }, 
            'Brush': {
                'Opacity': 100, 
                'ContinuousPaint': App.Constants.Boolean.false, 
                'WetLookPaint': App.Constants.Boolean.false, 
                'BlendMode': App.Constants.BlendMode.Normal
                }, 
            'PrimaryMaterial': App.Constants.MaterialRef.Foreground, 
            'ForegroundMaterial': {
                'Color': (0,0,0), 
                'Pattern': None, 
                'Gradient': None, 
                'Texture': None, 
                'Identity': u'Material'
                }, 
            'BackgroundMaterial': {
                'Color': (97,82,57), 
                'Pattern': None, 
                'Gradient': None, 
                'Texture': None, 
                'Identity': u'Material'
                }, 
            'Stroke': [
                (App.Constants.PathEntryInterpretation.Absolute,(x,y),0)
            ], 
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Default, 
                'RandomSeed': 3236927, 
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })

    return Material['Color']

def averagesigma(array):
    x=0
    x2=0
    avsig=[0,0]
    n=len(array)
    for i in range (0,n):
       x=x+array[i]
       x2=x2+array[i]*array[i]
    avsig[0]=x/n
    avsig[1]=sqrt((x2-x*x/n)/(n-1) )
    return avsig


def setupcard(Environment):
    print"*************"
    global gemetenkleur

    ImageInfo = App.Do( Environment, 'ReturnImageInfo',)
    heightsquare=ImageInfo['Height']
    widthsquare=ImageInfo['Width']
    stepx=[0,0,0]
    stepy=[0,0,0]
    dropper=[0,0,0]
    patchsidex=widthsquare/5.
    patchsidey=heightsquare/2.
    stepx[0]=patchsidex/2.
    stepx[1]=patchsidex
    stepx[2]=patchsidex
    stepy[0]=patchsidey/2.
    stepy[1]=patchsidey/2.
    stepy[2]=patchsidey
    for i in range(0,3):
       dropper[i]=math.floor((stepy[i]/3.-0.5)/2)
       if dropper[i]>5:
          dropper[i]=5
       if dropper[i]<2:
          print >> sys.stderr,'***WARNING: patches in row ',i+1,' are small, should at least (15*15), but is (',math.floor(stepx[i]),',',math.floor(stepy[i]),')'
          dropper[i]=2

    row=0
    column=5.
    patchy=stepy[row]/2
    allblackpatches=[0,0,0,0,0]
    allwhitepatches=[0,0,0,0,0]
    for column2 in range(0,5):
       patchx=((column2*2)+0.5)*stepx[row]
       patchc=measure (Environment,patchx,patchy,dropper[row])
       allwhitepatches[column2]=patchc[0] * 0.299 + patchc[1] *0.587 + patchc[2] * 0.114 
    for column2 in range(0,5):
       patchx=((column2*2+1)+0.5)*stepx[row]
       patchc=measure (Environment,patchx,patchy,dropper[row])
       if column2==column-1:
           gemetenkleur[0]=patchc
       allblackpatches[column2]=patchc[0] * 0.299 + patchc[1] *0.587 + patchc[2] * 0.114 
    print "All black patches: ",allblackpatches       
#    print "All white patches: ",allwhitepatches  
    avgsigblack=averagesigma(allblackpatches) 
    avgsigwhite=averagesigma(allwhitepatches)     
    print '[Average,sigma] of black and white patches: ', avgsigblack," ",avgsigwhite
    if avgsigblack[0]/(0.001+avgsigblack[1])<10:
       print >> sys.stderr,'***WARNING: The variation of black patches is more than 10% of its average value (', round(avgsigblack[1]/avgsigblack[0]*100),' [%])'    
 
    if avgsigwhite[0]/(0.001+avgsigwhite[1])<10:
       print >> sys.stderr,'***WARNING: The variation of white patches is more than 10% of its average value (', round(avgsigwite[1]/avgsigwhite[0]*100),' [%])'    
 
    row=1
    for column in range(3,6):
       patchy=stepy[row-1]+stepy[row]/2
       patchx=((column-1)+0.5)*stepx[row]
       gemetenkleur[6-column]=measure (Environment,patchx,patchy,dropper[row])
    row=2
    for column in range(2,6):
       patchy=stepy[row-1]+stepy[row-2]+stepy[row]/2
       patchx=((column-1)+0.5)*stepx[row]
       gemetenkleur[column+2]=measure (Environment,patchx,patchy,dropper[row])
    return


#calculate a gamma function
def detergamma(x):
  return 255*math.pow(float(x)/255,gamma)

#display picture
def displaypic(pix,titletext):
     w2=ImageWin.ImageWindow(pix,title=titletext)
     w2.mainloop() # this will block until the window is closed
     return

def optimummaking():

 global gamma

#read picture
 imbegin = Image.open(imagelocation)
 
 #displaypic(imbegin,"Original")

# just a sample color matrix (I kept the off-set zero (the last
# 'column' with zeros)
 colormat= (colormatrixopt[0],colormatrixopt[3],colormatrixopt[6],0,	
        colormatrixopt[1],colormatrixopt[4],colormatrixopt[7],0,	
        colormatrixopt[2],colormatrixopt[5],colormatrixopt[8],0)
 	   

#bring picture in linear space, assume it was near sRGB
#first split it in the three bands, to be able to do
#different gamma on each band
 splitted= imbegin.split()
 gamma=1/gbopt[0]
 Rrr=Image.eval(splitted[0], detergamma)
 gamma=1/gbopt[1]
 Ggg=Image.eval(splitted[1], detergamma)
 gamma=1/gbopt[2]
 Bbb=Image.eval(splitted[2], detergamma)

#make it one RGB picture
 combined=Image.merge("RGB",(Rrr,Ggg,Bbb))

#do a color matrix transform
 converted = combined.convert("RGB", colormat)
#bring back into sRGB space
 gamma=1/ge[0]
 imend=Image.eval(converted, detergamma)

 imend.save(optimumloc)
 return


def optfunction(xx):
    gemeten=gemetenkleur[:]
    gammakleuren=gammakleur(gemetenkleur,xx[9:12])
    transposekleur= matrixkleur(gammakleuren,xx[0:9],0)
    endkleur=gammakleur(transposekleur,ge)
    y=verschil(endkleur,doelkleur)
    return y

def test(mat,n):
    errorteller=0
    for testprim in range(0,numberprimcolors):
      errorteller=errorteller+testcolor(mat[testprim],n,primkleur[testprim])
    return errorteller

def testcolor(color,n,m):
    if color<=threshold:
     print >> sys.stderr,'***WARNING: ',m, ' channel of ',n,' patch is underexposed: ',color
     return 1
    if color>=255-threshold:
     print >> sys.stderr,'***WARNING: ',m, ' channel of ',n,' patch is overexposed: ',color
     return 1
    return 0
    
def testinggemetenkleur():
    okteller=0
    for patchcolor in range(0,askingcolors):
      teller=test(gemetenkleur[patchcolor],patch[patchcolor])
      if teller>1:
        ok[patchcolor]=0
        print >> sys.stderr,'***ERROR: ',patch[patchcolor],' patch removed from optimization: ',teller
      else:
        okteller=okteller+1
    if okteller==0:
        print >> sys.stderr,'***ERROR: No proper color patches available to optimize'
        stopscript()
    if okteller<6:
        print >> sys.stderr,'***WARNING: Only ',okteller,' color patches take part in optimization'      
    return

def findcolor(Environment,patchcolor):
    print 'Pick ',patch[patchcolor],' color patch, and press <OK>'
    Material = App.Do( Environment, 'GetMaterial', {'IsPrimary': App.Constants.Boolean.true})
    gemetenkleur[patchcolor]=Material['Color']
    return

def gammakleur(kleuren,gamma):
    kleurenopbouw=[[47,46,47],[62,65,61],[116,114,114],[238,233,232],[65,62,116],[0,144,75],[245,211,0],[207,65,60]]
    for x in range(0,numbercolors):
        kleur=[0,0,0]
        for y in range(0,numberprimcolors):
#            print kleuren[x][y]," ",gamma[y]
            if gamma[y]<=0:
               gamma[y]=0.0001
#            print kleuren[x][y]," ",gamma[y]

            kleur[y]=255*math.pow(float(kleuren[x][y])/255,float(1/(gamma[y])))
        kleurenopbouw[x]=kleur
    return kleurenopbouw

def verschil(kleurena,kleurenb):
    verschil=0
    teller=0
    for x in range(0,numbercolors):
        if ok[x]==1:
           teller=teller+1
        for y in range(0,numberprimcolors):
            verschil=verschil+math.pow(float(kleurena[x][y]-kleurenb[x][y]),2)*ok[x]
    return math.sqrt(verschil/teller)

def integerkleur(kleuren):
    kleurenopbouw=[[47,46,47],[62,65,61],[116,114,114],[238,233,232],[65,62,116],[0,144,75],[245,211,0],[207,65,60]]
    for x in range(0,numbercolors):
        for y in range(0,numberprimcolors):
            kleurenopbouw[x][y]=math.floor(kleuren[x][y]+0.5)
    return kleurenopbouw


def fixgamma(gamma):
    gammaint=[0,0,0]
    for y in range(0,numberprimcolors):
            gammaint[y]=math.floor((gamma[y]+0.5/100)*100)/100
    return gammaint


def matrixkleur(kleuren,matrix,gamutprinting):
    kleurenopbouw=[[47,46,47],[62,65,61],[116,114,114],[238,233,232],[65,62,116],[0,144,75],[245,211,0],[207,65,60]]
    for x in range(0,numbercolors):
        kleur=[0,0,0]
        teller=0
        valuemin=0
        valuemax=255
        for y in range(0,numberprimcolors):
             kleur[y]=kleuren[x][0]*matrix[3*0+y]+kleuren[x][1]*matrix[3*1+y]+kleuren[x][2]*matrix[3*2+y]
             if kleur[y]<0:
                teller=teller+1
                if kleur[y]<valuemin:
                   valuemin=kleur[y]
                kleur[y]=0
             if kleur[y]>255:
                if kleur[y]>valuemax:
                   valuemax=kleur[y]
                teller=teller+1
                kleur[y]=255
        kleurenopbouw[x]=kleur
        if gamutprinting and teller>0:
            print >> sys.stderr,'***WARNING: ',patch[x],' patch was out of gamut: (',math.floor(valuemin),' ',math.floor(valuemax),')'
    return kleurenopbouw

def initPSP(Environment):
# ShowScriptToolbar
  App.Do( Environment, 'ShowScriptToolbar', {
            'ShowScriptBar': App.Constants.ShowCommands.Show,
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Silent,
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })

  App.Do( Environment, 'SelectTool', { 'Tool': 'Eyedropper' } )

  Version = App.Do(Environment, 'GetVersionInfo')
  minorversion=Version['MajorVersion']

  versie = r'Software\Jasc\Paint Shop Pro %d\General' % (minorversion)
  # open the psp general key
  key = _winreg.OpenKey( _winreg.HKEY_CURRENT_USER, versie )
  # get the currently selected scriptmode in the script droplist.
  val = _winreg.QueryValueEx( key, 'SelectScriptMode' )

  # this is the selected scriptmode
  Mode = val[0]
  if Mode==2:

  # SetExecutionMode
   App.Do( Environment, 'SetExecutionMode', {
             'GeneralSettings': {
                 'ExecutionMode': App.Constants.ExecutionMode.Default,
                 'AutoActionMode': App.Constants.AutoActionMode.Match
                 }
             })


  App.Do( Environment, 'ShowScriptOutput', {
            'ShowScriptOutput': App.Constants.ShowCommands.Show,
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Silent,
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })

  try:
    if App.Do( Environment, 'CountImageColors', {
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Silent, 
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            }) <= 255:

        App.Do( Environment, 'IncreaseColorsTo16Million', {
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Silent, 
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            }) 
  except:
         pass
  return
  

def UpdateEXIF(Environment,colorspace,verschil):
  App.Do( Environment, 'SelectDocument', {'SelectedImage': 0,   
            'Strict': App.Constants.Boolean.false})
  Info = App.Do( Environment, 'ReturnImageInfo' )
  comment = Info['ExifTitle']
  comment=comment+'File adjusted by optimization software of V. Reijs, (c) 2005 towards '+colorspace+' colorspace. The difference from color card is: ',verschil

  App.Do( Environment, 'ImageInfo', {
            'ExifTitle': comment,
             'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Silent,
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })
  print comment

def stopscript():
            print >> sys.stderr,'***WARNING: Optimization stopped'
            print '*************'
            sys.exit()


def Do(Environment):

  global gemetenkleur
  global doelkleur
  global colormatrixopt
  global askingcolors
  global gbopt
  global optimumloc
  global imagelocation
  global cardloc
  imagelocation=App.ActiveDocument.Name
  optimumloc=imagelocation.split(".")[0]+"-optimum."+imagelocation.split(".")[1]
  cardloc=imagelocation.split(".")[0]+"-card."+imagelocation.split(".")[1]
  

  print ''
  print '*************'
  print >> sys.stderr,'Victor Reijs, (c) 2005, version: ',version
  print >> sys.stderr,'http://www.iol.ie/~geniet/eng/IFRAOcoloropt.htm#Method'
  print 'Original file is at: ',imagelocation
  try:
    imbegin = Image.open(imagelocation)
  except:
    print >> sys.stderr,'***ERROR: File type ',imagelocation.split(".")[1],' not supported'
    stopscript()   
#  print imbegin.mode
  if imbegin.mode<>"RGB":
    print >> sys.stderr,'***ERROR: No RGB bands available in ',imagelocation.split(".")[1],' file'
    stopscript()   
   
  if App.ActiveDocument<>None:
    initPSP(Environment)    
    askingcolors=numbercolors
    App.Do( Environment, 'EnableOptimizedScriptUndo', {                       })
    nogniet=0
    while nogniet==0:
         year ={ 'EnteredText':'1994'}
         if askingcolors==numbercolors:
            year =App.Do( Environment, 'GetString', {'DefaultText': '2001','DialogTitle': 'Question?','Prompt': 'Year of used IFRAO standard scale:\r1994, 2001 or stop?','MaxLength': 4})
         if year[ 'EnteredText' ]=='1994':
            nogniet=1
            keuze=1
         if year[ 'EnteredText' ]=='2001':
            nogniet=1
            keuze=2
         if year['EnteredText']=='stop':
            stopscript()
    print 'IFRAO version year: ',year[ 'EnteredText' ]
    resultfile=0      
    result = App.Do(Environment, 'MsgBox', {'Buttons': App.Constants.MsgButtons.OKCancel,'Icon': App.Constants.MsgIcons.Info,'Text': 'Do you want to pick yourself the color pacthes: press OK\ror auto pick them using a seperate file: press Cancel',})
    while resultfile==0:
      resultfile=1
      if result==1:
        for gekozenkleur in range(0,askingcolors):
         findcolor(Environment,gekozenkleur)
        if askingcolors<>numbercolors:
         gemetenkleur=gemetenkleur
      else:
        resultfile=App.Do( Environment, 'FileOpen', {
            'FileList': [ cardloc ],
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Silent, 
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })
        if resultfile==0:
            resultno = App.Do(Environment, 'MsgBox', {'Buttons': App.Constants.MsgButtons.OKCancel,'Icon': App.Constants.MsgIcons.Info,'Text': '***ERROR: No file explicitly available with color card ("-card" in name).\rDo you want to hand pick: press OK\ror end the optimization: press Cancel'})
            result=1
            if resultno==0:
               stopscript()      
        if resultfile==1:
          App.Do( Environment, 'SelectDocument', {'SelectedImage': 0,   
            'Strict': App.Constants.Boolean.false})
          setupcard(Environment)
    testinggemetenkleur()
    bwvalue=[0,0,0,0,0,0,0,0]
    for i in range(0,8):
           bwvalue[i]=round(gemetenkleur[i][0] * 0.299 + gemetenkleur[i][1] *0.587 + gemetenkleur[i][2] * 0.114 +0.5)
    print 'Black&white values: ',bwvalue
    for i in range(0,3):
       if bwvalue[i]>bwvalue[i+1]:
          ok[i]=0
          print >> sys.stderr,'***ERROR: ',patch[i],' patch removed from optimization, should be darker then ',patch[i+1]
#    ok[0]=0      
    print 'Accepted colorpatches: ',ok
    
    
    App.Do( Environment, 'SelectDocument', {'SelectedImage': -1,   
            'Strict': App.Constants.Boolean.false})


    nogniet=0
    while nogniet==0:
         colorspace = {'EnteredText':"sRGB"}
         if askingcolors==numbercolors:
            colorspace =App.Do( Environment, 'GetString', {'DefaultText': 'sRGB','DialogTitle': 'Question?','Prompt': 'What colorspace is needed:\rsRGB, AdobeRGB or stop?','MaxLength': 9})
         if colorspace[ 'EnteredText' ]=='sRGB':
            nogniet=1
            if keuze==1:
               doelkleur=ifrao1994sRGB
            else:
               doelkleur=ifrao2001sRGB
         if colorspace[ 'EnteredText' ]=='AdobeRGB':
            nogniet=1
            if keuze==1:
               doelkleur=ifrao1994Adobe
            else:
               doelkleur=ifrao2001Adobe
         if colorspace['EnteredText']=='stop':
            stopscript()

    print 'Target colorspace: ',colorspace[ 'EnteredText' ]

#bepalen totaal (door fmin_bfgs of scipy)

    totaal=colormatrix+gb
    xopt = fmin_bfgs(optfunction, totaal, args=(), maxiter=10000)
    colormatrixopt=xopt[0:9]
    gbopt=xopt[9:12]

    print 'Measured colors: ', integerkleur(gemetenkleur)
    verschilbegin=verschil(gemetenkleur,doelkleur)
    print 'Start difference: ',verschilbegin
    print 'Start gamma: ',fixgamma(gbopt)
    gammakleuren=gammakleur(gemetenkleur,gbopt)
    print 'Lineair colors: ', integerkleur(gammakleuren)
    print 'Color matrix: ',colormatrixopt
    transposekleur= matrixkleur(gammakleuren,colormatrixopt,1)
    print 'Transpose colors: ', integerkleur(transposekleur)
    print 'End gamma: ',fixgamma(ge)
    endkleur=gammakleur(transposekleur,ge)
    print 'Final colors: ', integerkleur(endkleur)
    print 'Target colors: ', integerkleur(doelkleur)
    verschilend=verschil(endkleur,doelkleur)
    print 'End difference: ',verschilend
    print 'Difference reduced to ',math.floor(verschilend/verschilbegin*100),'% of start difference'
    
    optimummaking()
    App.Do( Environment, 'FileOpen', {
            'FileList': [ optimumloc ],
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Silent, 
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })
    UpdateEXIF(Environment,colorspace['EnteredText'],round(verschilend+0.5))
    App.Do( Environment, 'FileSave', {
            'FileList': [ optimumloc ],
            'GeneralSettings': {
                'ExecutionMode': App.Constants.ExecutionMode.Silent, 
                'AutoActionMode': App.Constants.AutoActionMode.Match
                }
            })
    print 'Optimized file is at: ',optimumloc

  else:
    print >> sys.stderr,'***ERROR: No picture active'
  print '*************'

