#!/usr/bin/env python3
"""
Manual hex analysis - search for 16-byte blocks that look like MIFARE data
"""

def analyze_for_mifare_blocks(filename):
    """Look for 16-byte MIFARE sector data"""
    with open(filename, 'rb') as f:
        data = f.read()
    
    print(f"\n{'='*70}\nAnalyzing: {filename}\n{'='*70}")
    
    # Skip the Saleae header (first 100 bytes typically)
    start_offset = 100
    
    # Look for blocks that might contain ASCII or structured data
    candidates = []
    
    for offset in range(start_offset, len(data) - 16):
        block = data[offset:offset+16]
        
        # Check for interesting patterns:
        # 1. Contains some ASCII printable characters
        ascii_count = sum(1 for b in block if 32 <= b < 127)
        
        # 2. Not all same value
        unique_vals = len(set(block))
        
        # 3. Not all zeros or all FFs
        if unique_vals > 2 and ascii_count >= 4:
            hex_str = ' '.join(f'{b:02x}' for b in block)
            ascii_str = ''.join(chr(b) if 32 <= b < 127 else '.' for b in block)
            candidates.append((offset, hex_str, ascii_str, ascii_count))
    
    # Sort by ASCII count
    candidates.sort(key=lambda x: x[3], reverse=True)
    
    print(f"\n[+] Found {len(candidates)} interesting 16-byte blocks:\n")
    for i, (offset, hex_str, ascii_str, count) in enumerate(candidates[:20]):
        print(f"{offset:08x}  {hex_str}")
        print(f"          [{ascii_str}] ({count} ASCII chars)\n")

def search_for_uid_pattern(filename):
    """Search for UID-like 4-byte sequences"""
    with open(filename, 'rb') as f:
        data = f.read()
    
    print(f"\n[*] Searching for UID patterns in {filename}...")
    
    # Common MIFARE Classic UIDs start with certain manufacturer bytes
    # and typically have some structure
    for offset in range(100, len(data) - 4):
        if data[offset] in [0x04, 0x08, 0x09]:  # Common NXP/Philips manufacturer codes
            uid_candidate = data[offset:offset+4]
            # Check if the rest looks reasonable (not all same, not all 0xFF)
            if len(set(uid_candidate)) >= 3:
                uid_hex = ''.join(f'{b:02x}' for b in uid_candidate)
                print(f"  Offset {offset:08x}: {uid_hex}")

# Analyze all channels
for i in range(4):
    filename = f"extracted/digital-{i}.bin"
    analyze_for_mifare_blocks(filename)
    search_for_uid_pattern(filename)
