#! /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 = "default"
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("RunList=[]".format(listFileName))
    else:
        raise UserWarning("Not found file=%s" % (argv[1]))
else:
    print("Usage::")
    print("        $ ./{} <filename of runlist>".format(argv[0]))
    print("        ")
    print("        $ python {} <filename of runlist>".format(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}
conds = BC.LoadRunListToExtract(listFileName, paramDic)

for (ScanNo, PhiValue, Norm) in conds:
    # Cmm.CopyData(ScanNo)
    print("==============[ %06d,%8.3f,%10.5f ]" % (ScanNo, PhiValue, Norm))
    savePath = os.path.join(savePathDir, ("S%06d.vbin" % (ScanNo)))
    DAT = DR.GetDataOfMonochroEi2(ScanNo, Ei, delta_hw, hw_min, hw_max, maskfile, Norm)
    Cmm.VisContMOutputFileByPhi(DAT, XtalParam, PhiValue, savePath)
    del DAT
