#! /usr/bin/env python
from __future__ import print_function
import os
import sys
import DR
import Cmm

#####################
# modify here
####################
XtalParam = "XtalParam.xml"
savePathDir = "./data"
#########################

listFileName=""

### Check Arguments
argv = sys.argv
if len(argv)<2 or len(argv)>4:
    print("Usage::")
    print("        $ ./{} <filename of runlist> [<output dir> [<XtalParam>]]".format(argv[0]))
    print("        ")
    print("        $ python {} <filename of runlist> [<output dir> [<XtalParam>]]".format(argv[0]))
    sys.exit(0)

### Check and set run list file
### <filename> <angle>
if len(argv)>1:
    if os.path.exists(argv[1]):
        listFileName=argv[1]
        print("RunList=[]".format(listFileName))
    else:
        raise UserWarning("Not found file= {}".format(argv[1]))

### Check and set output directory
if len(argv)>2 and os.path.exists(argv[2]):
    savePathDir = argv[2]
else:
    raise UserWarning("Not found directory = {}".format(argv[2]))

### Check and set XtalParam file
if len(argv)>3 and os.path.exists(argv[3]):
    XtalParam = argv[3]
else:
    raise UserWarning("Not found XtalParam = {}".format(argv[3]))

### If output directory does not existed
if not os.path.exists(savePathDir):
    print(" savePathDir = {} is not found. Making new ".format(savePathDir))
    try:
        os.makedirs(savePathDir)
    except:
        raise UserWarning("Cannot make new folder(" + savePathDir +")")

### Main loop for conversion
fr = open( listFileName, "r" )
while(True):
    a_line = fr.readline()
    if a_line=="":
        break
    params = a_line.split(" ")
    if len(params)!=2:
        raise UserWarning("Cannot read this format (" + a_line +")")
    root_path = os.path.dirname(params[0])
    if root_path=="":
        root_path = "./"
    Filename = os.path.basename(params[0])
    PhiValue = float( params[1] )
    savePath = os.path.join( savePathDir, "%08.3f.vbin"%(PhiValue))
    print("==============[ %s, %8.3f, saved to %s ]" % (Filename,PhiValue,savePath))
    DAT = Cmm.LoadDataFromDump(path=root_path,filename=Filename)
    Cmm.VisContMOutputFileByPhi(DAT, XtalParam, PhiValue, savePath)
    del DAT

fr.close()
