# -*- coding: utf-8 -*-

import matplotlib.pyplot as plot
from numpy import *
import tomography
import json
import sys

from urllib2 import HTTPError
#from urllib.error import HTTPError

reconPath = "./"

#tomography.createGeomMatrices()

if len(sys.argv)<=1:
	print("please pass some shot numbers as arguments.")
for shot in sys.argv[1:]:
	try:
		print("loading "+shot+"...")
		img_top, img_side = tomography.loadImages(shot)
		img_top, phase_top, img_side, phase_side, frames, shift = tomography.selectFrames(img_top, img_side)
		reconstruction = tomography.getReconstruction_allFrames(img_top, phase_top, img_side, phase_side)
		
		print("saving...")
		nR = 30
		pixely = tomography.getPixels(nR)
		plot.figure(figsize=(3,3), dpi=80)
		for s in range(reconstruction.shape[2]):
			img = zeros((nR*nR,3))
			img[pixely,:] = reconstruction[:,:,s]
			plot.imshow(rot90(img.reshape((nR,nR,3)).clip(min=0,max=1),3),interpolation="nearest")
			plot.savefig(reconPath+"{0}_{1}.png".format(shot,s))

		metadata = {"shift":shift.astype(int),"list":frames.tolist()}
		file = open(reconPath+"{0}_meta.json".format(shot),"w")
		file.write(json.dumps(metadata))
		file.close()
	except HTTPError:
		print("cannot load projection images.")
