#!/usr/bin/python
# timelapse motion detection, file organisation part
# 1.10.2009 by Nick Fankhauser
# Requires motion_detect (compiled from motion_detect.c) in PATH

import os,time,shutil,sys
start_hour,end_hour=6,21
period='night'
target_dir='/home/nyk/lumistat'
if not os.path.isdir(target_dir): os.mkdir(target_dir)
threshold=int(sys.argv[1])
motion_detect=lambda x,y : int(os.popen('motion_detect %s %s' % (x,y)).read().strip())
hour=lambda x : int(time.strftime('%H',time.gmtime(int(digits_only(x))+7200)))
if period=='day': day_hour=lambda x : hour(x)>start_hour and hour(x)<end_hour
else: day_hour=lambda x : hour(x)<start_hour or hour(x)>end_hour

def digits_only(s):
 zahlen=map(str,range(10)) # all numbers
 rs=''
 for c in str(s):
  if c in zahlen: rs+=c
 return rs

fl=filter(lambda x:'.jpg'==x[-4:],os.listdir('.'))
fl2=filter(day_hour,fl)
fl2.sort()
print '%d images found, %d during %s' % (len(fl),len(fl2),period)
for i in range(len(fl2)-1):
 n1,n2=fl2[i],fl2[i+1]
 dc=motion_detect(n1,n2)
 if dc>threshold and dc<100: 
  print '%s -> %s = %d' % (n1,n2,dc)
  shutil.copy(n1,target_dir)
  shutil.copy(n2,target_dir)