# replace_bytes.py
#
# Use this python script to modify camera RAW files camera model name to 
# a model name supported by DxO PL7
#
# For example to modify Sony A9iii RAW files so that DxO PL5 will think they are A9ii files
# use the string replacement of '-9M3' -> '-9M2'
# You will need to check the RAW files from both model cameras to determine what actual values are 
# to be used.

import os, fnmatch

# Directory with Original RAW files - we make copies we dont change the originals
sourceFolder = '/Users/duncangroenewald/Pictures/2024/2024-01/2024-01-25/103MSDCF/'

# Subfolder to put modified RAW files
# Prefix '0-' so the folder appears at the top of the list
destinationSubfolder = '0-Edited'

# Extension of RAW files to process
pattern = "*.ARW"

# Camera model name to change in RAW file
# The string must be identical lenght or file may be corrupted
model = '-9M3'
modelTo = '-9M2'

# Path 
path = os.path.join(sourceFolder, destinationSubfolder) 

if not os.path.exists(path): 
    print("The folder ' + path + ' does not exist so creating it")
    try:  
        os.mkdir(path)  
    except OSError as error:  
        print(error)  
else: 
    print("The folder ' + path + ' exists")
    

listOfFiles = sorted(os.listdir(sourceFolder))


modelFrom = ''.join(hex(ord(c))[2:] for c in model)
modelToUse = ''.join(hex(ord(c))[2:] for c in modelTo)


# '-9M3' -> '-9M2'
source_str = modelFrom
replace_str = modelToUse

for file in listOfFiles:
    if fnmatch.fnmatch(file, pattern):
        sourceFilePath = os.path.join(sourceFolder, file)
        targetFilePath = os.path.join(path, file)
        if os.path.exists(targetFilePath): 
            print('File ' + targetFilePath + ' exists, skipping.')
            continue
        else:
            print('Modifying ' + sourceFolder + '/' + file)

            with open(sourceFilePath, 'rb') as f:
                content = f.read().hex()
#           print(source_str + " in " + file + ":       ", source_str in content)
            content = content.replace(source_str, replace_str)
         
            with open(targetFilePath, 'wb') as f:
                f.write(bytes.fromhex(content))
    else:
        print('Not ARW file')


        

