from datetime import datetime

def set_flag(dorel, arrest_records, **kw):
    if dorel[0] is not None:
        yrrel, morel, darel = dorel
    else:
        yrrel = 9999
    
    
    #check to make sure we got the date of release, otherwise log an error
    for row in arrest_records.itervalues():
        try:
            doa = datetime(row['arryr'], row['arrmo'], row['arrda'])
        except ValueError:
            #log error
            row['follow_up_flag'] = False
            continue
        
        if yrrel == 9999:
            kw['log'].write('afollow_up', [row['id'], row['astate'], yrrel, "No DOREL for subject casenum=%s" % row['casenum']], store=True)
            row['follow_up_flag'] = False
            continue
        
        if doa.year == 9999:
            kw['log'].write('afollow_up', [row['id'], row['astate'], str(doa), "No date of arrest for casenum=%s" % row['casenum']], store=True)
            row['follow_up_flag'] = False
            continue
            
        dorel = datetime(yrrel, morel, darel)
        
        #calculate the amount of time between arrest and release
        time_delta = doa - dorel
        days_delta = int(time_delta.days)
        
        '''if arrest more than 5 years after release then flag for deletion'''
        row['follow_up_flag'] = True if days_delta > (365.25*kw['follow_period']) else False
