#!/usr/bin/python

from scipy import misc
from pylab import *
ion()
import sys
import ezca
import time
import os


e = ezca.Ezca()

# reference image in visibile light
reference = '/ligo/data/camera/PR2_scrapper_illuminator_on_newzoom_H1 PR2 (h1cam08)_2018-07-24-18-40-46.tiff'
# where new images are saved
img_dir = '/ligo/data/camera/' 

# read the reference image
img = misc.imread(reference)


while (True):
    # snap an image and save it with 'temp' name
    e['VID-CAM08_FILE'] = 'temp'
    e['VID-CAM08_SNAP'] = 1
    time.sleep(0.2)
    # list all images like temp* and wait until a new one is available
    files = []
    while len(files) == 0:
        files = os.listdir(img_dir)
        files = [f for f in files if 'temp' in f]
        time.sleep(0.1)
    # load the new image and then remove it
    try:
        time.sleep(0.3)
        img2 = misc.imread(img_dir + files[-1])
        os.remove(img_dir + files[-1])
    except:
        print("Error!")
        time.sleep(0.3)
        img2 = misc.imread(img_dir + files[-1])
        os.remove(img_dir + files[-1])
        
    # plot
    clf()
    imshow(img, cmap='gray')
    imshow(img2, alpha=0.5, cmap='Reds')
    title(files[-1][22:-5])
    axis('off')
    show()
    draw()
    # pause
    time.sleep(.1)
