import fnmatch
import glob
import os
import struct

MAX = 100


def isDCM(filename):
    with open(filename, 'rb') as infile:
        header = infile.read(132)
    if ord(header[0]) == 8:
        return True
    if header[-4:] == 'DICM':
        return True
    print ":".join("{:02x}".format(ord(c)) for c in header), filename
    print header[-4:]
    exit()
    
    
    
def check_accuray():
    ACCURAY_PATIENTS = '/shares/mnt/ntuh-cks/accuray/database/patients/'
    count = 0
    for patient in glob.glob("%s/*" % ACCURAY_PATIENTS):
        print patient
        for ct in glob.glob("%s/ct/patient/*" % patient):
            for CTMR in glob.glob("%s/*" % ct):
                for fullpath in glob.glob("%s/*" % CTMR):
                    if fullpath.endswith('import.list'):
                        continue
                    if isDCM(fullpath):
                        continue
                    count += 1
                    exit()
    
        if count >= MAX:
            exit()
    #     break
    

def isNII(filename):
    with open(filename, 'rb') as infile:
        header = infile.read(132)
        
    sizeof_hdr = struct.unpack('i', header[0:4])[0]
    
    if sizeof_hdr == 348:
        return True
    

    print ":".join("{:02x}".format(ord(c)) for c in header), filename
    print sizeof_hdr
    exit()
    

def check_accuray_nii():
    CONVERTED_PATIENTS = '/shares/mnt/ntuh-cks/accuray_nii/'
    count = 0
    for patient in glob.glob("%s/*" % CONVERTED_PATIENTS):
        print patient
        for ct in glob.glob("%s/*.nii" % patient):
            if isNII(ct):
#                 print("%s OK" % ct)
                continue
            count += 1
            exit()
    
        if count >= MAX:
            exit()
    #     break

def isISO(filename):
    with open(filename, 'rb') as infile:
        header = infile.read(32774)
    
    if header[-5:] in ('BEA01', 'CD001'):
        return True
        
    print ":".join("{:02x}".format(ord(c)) for c in header[-5:]), filename
#     exit()


def check_iso():
    ISO_PATIENTS = '/shares/mnt/ntuh-cks/ISO/'
    count = 0
    
    for path, dirs, files in os.walk(os.path.abspath(ISO_PATIENTS)):
        for filename in fnmatch.filter(files, '*.iso'):
            if 'RECYCLE' in path:
                continue
#             print os.path.join(path, filename)
            if isISO(os.path.join(path, filename)):
                continue
            count += 1
#             exit()
    
        if count >= MAX:
            exit()
    #     break


# check_accuray()
# check_accuray_nii()
# check_iso()
# print isDCM('/shares/mnt/ntuh-cks/accuray/database/patients/JOU_1920628/ct/patient/case2011.10.18.12.54.38/MR/IM1')

