import sys
import os

def patch_file(filename, new_value):
    # Position 9 (0-indexed offset)
    OFFSET = 9
    
    if not os.path.exists(filename):
        print(f"Error: File '{filename}' not found.")
        sys.exit(1)

    try:
        # Open in read+write binary mode
        with open(filename, 'r+b') as f:
            # Move pointer to byte 9
            f.seek(OFFSET)
            
            # Read the current byte
            original_byte = f.read(1)
            
            # Check if file is long enough
            if not original_byte:
                print(f"Error: File is too short (less than {OFFSET + 1} bytes).")
                sys.exit(1)
            
            # Convert original byte to integer for display
            original_val = int.from_bytes(original_byte, "little")
            
            # SHOW the original value
            print(f"Original value at byte {OFFSET}: {hex(original_val)}")
            
            # Move back to position 9 to overwrite
            f.seek(OFFSET)
            
            # Write the new value
            f.write(bytes([new_value]))
            print(f"New value written: {hex(new_value)}")

    except ValueError:
        print("Error: Invalid input value.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    if len(sys.argv) == 3:
        # Command line mode
        target_file = sys.argv[1]
        val_str = sys.argv[2]
        
        try:
            # Handle hex (0xFF) or int (255) inputs
            patch_val = int(val_str, 16) if val_str.startswith('0x') else int(val_str)
            patch_file(target_file, patch_val)
        except ValueError:
            print("Error: Value must be an integer or hex string.")
            
    else:
        # Interactive mode
        target_file = input("Enter filename: ").strip('"').strip("'")
        val_input = input("Enter new value (int or hex): ")
        
        try:
            patch_val = int(val_input, 16) if val_input.startswith('0x') else int(val_input)
            patch_file(target_file, patch_val)
        except ValueError:
            print("Invalid number format.")