#! /usr/bin/env python3
from __future__ import print_function
import os
import sys
import DR
import Cmm
import utsusemi.ana.Reduction.BaseCommandsInEla as BC

#####################
# modify here
####################
Ei = 30.04
delta_hw = 0.2
hw_min = -5.0
hw_max = 28.0
maskfile = "mask.txt"
normFactor = 1000000.0
XtalParam = "XtalParam.xml"
savePathDir = "./data"
gonioValueAtZero = 31.032
#########################

argv = sys.argv
print("len(argv)={}".format(len(argv)))

listFileName = ""
if len(argv) == 2:
    if os.path.exists(argv[1]):
        listFileName = argv[1]
        print("AngleList={}".format(listFileName))
    else:
        raise UserWarning("Not found file=%s" % (argv[1]))
else:
    print("Usage::")
    print("        $ ./%s <filename of runlist>" % (argv[0]))
    print("        ")
    print("        $ python %s <filename of runlist>" % (argv[0]))
    sys.exit(0)

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 + ")")

paramDic = {"normFactor": normFactor, "gonio": gonioValueAtZero}
AngleList, condsDict = BC.LoadRunListToExtract(listFileName, paramDic, mergeAngles=True)

for angle_key in AngleList:
    angle = float(angle_key)
    runNos = condsDict[angle_key][0]
    norm = condsDict[angle_key][1]
    print("==============[ %s:%8.3f,%10.5f ]" % (runNos, angle, norm))
    DAT = DR.GetDataOfMonochroEi3(runNos, Ei, delta_hw, "%g %g" % (hw_min, hw_max), MaskFile=maskfile, NormFactor=norm)
    savePath = os.path.join(savePathDir, ("Ang_%s.vbin" % (angle_key)))  # save file name "Ang_123.450.vbin"
    Cmm.VisContMOutputFileByPhi(DAT, XtalParam, angle, savePath)
    del DAT
