-----------------------------------------------------------------------
--
-- Copyright (c) 2010 VINAS
-- All rights reserved.
--
-- This sample FVX script is not supported by VINAS and VINAS provides
-- no warranties or assurances about its fitness or merchantability.
-- It is provided at no cost and is for demonstration purposes only.
--
--                                      created on fri. feb. 4, 2011
--                                      modified on wed. jun. 20, 2018
-----------------------------------------------------------------------

-----------------------------------------------------------------------
--- function  UpdatePara2               ---- 該当パラメータの更新 -----
---                                     ---- restart file を指定して --
---                                     ----  任意パラメータを上書き --
---                                   ----   version 2 : 2009/01/27  --
---    ostype: 1: Windows,  2:Linux                               -----
---   orgFile: 更新ターゲットとなる restart file                  -----
---   Keyword: 設定パラメータを表すキーワード                     -----
---  charPath: 上書きする文字列                                   -----
-----------------------------------------------------------------------
	function UpdatePara2(ostype, orgFile, Keyword, charPatch)


	if (ostype == 1) then               ---- Windows であれば "copy"
		CommandString="copy "..orgFile.." ".."tmp"
	elseif (ostype == 2) then           ---- Linux であれば  "cp"
		CommandString="cp -f "..orgFile.." ".."tmp"
	end
	execute (CommandString)             ---- ファイルのコピー

	----                                ---- Row count
	fp_orig=openfile("tmp","r")
	nRow=0
	repeat
		ny=read(fp_orig,"*l")
		if (ny ~= nil) then
			nRow=nRow+1
		end
	until (ny == nil)
	closefile(fp_orig)
	print("nRow", nRow)

	----                                ---- store parameter line characters
	charString={}
	fp_orig=openfile("tmp","r")
	for i=1, nRow do
		charString[i]=read(fp_orig, "*l")
	end
	closefile(fp_orig)

	----                                ----  substitute for target parameter
	fp_upd =openfile(orgFile,"w")
	nKeyword=strlen(Keyword)
	for i=1, getn(charString) do
		print(charString[i])

		charTmp=strsub(charString[i], 1, nKeyword)
		print(charTmp)

		if( charTmp == Keyword )then
			write(fp_upd, Keyword.." "..charPatch, "\n")
		else
			write(fp_upd, charString[i], "\n")
		end

	end
	closefile(fp_upd)

	return 0
	end -- function UpdatePara2()

-----------------------------------------------------------------------
-----------------------------------------------------------------------


-----------------------------------------------------------------------
--- function  ReadPlotsArray            ---- Streamline の        -----
---                                     ---- 軌跡座標列を配列格納 -----
---      strFileName: Streamline export data file name            -----
-----------------------------------------------------------------------
	function ReadPlotsArray(strFileName)

	Xarray={}
	Yarray={}
	Zarray={}

	fp_tmp=openfile(strFileName, "r")
	for i=1, 7 do                       ---- ヘッダ部の読み飛ばし
		nTmp=read(fp_tmp,"*l")
	end
	nPlots=read(fp_tmp,"*l")
	print("nPlots: "..nPlots)

	for i=1, nPlots do                  ---- 点の数だけ 読み込む loop
		Xarray[i]=read(fp_tmp,"*n")
		Yarray[i]=read(fp_tmp,"*n")
		Zarray[i]=read(fp_tmp,"*n")
		Duration=read(fp_tmp,"*n")
		CurScalar=read(fp_tmp,"*n")
	end

	closefile(fp_tmp)

	return nPlots, Xarray, Yarray, Zarray
	end -- function ReadPlotsArray()

-----------------------------------------------------------------------
-----------------------------------------------------------------------

-----------------------------------------------------------------------
---                                                               -----
---                                X                              -----
---                                                               -----
---                                                               -----
---          XX XX XX   XXXX     XXX     XX XX                    -----
---           XX XX X       X      X      XX  X                   -----
---           X  X  X   XXXXX      X      X   X                   -----
---           X  X  X  X    X      X      X   X                   -----
---           X  X  X  X    X      X      X   X                   -----
---           X  X  X  X    X      X      X   X                   -----
---          XXX XX XX  XXXX X   XXXXX   XXX XXX                  -----
---                                                               -----
-----------------------------------------------------------------------





	---- export filename prefix ------
	strPrefix="SectionalView"

	---- marching increment step ------
	mStep=15

	---- streamline setting ------
	seeds={x = { -0.0150822},
			 y = {0.0350822},
			 z = {-0.0108454}}

	seeding_input_table = {
		seed_coord = "XYZ",
		mode = "add",
		seeds = seeds}


	streamline_table = {vector_func = "U",
						scalar_func = "epsilon",
						dataset = 1,
						visibility = "on",
						seeding = seeding_input_table,
						display_seeds = "on",

						calculation_parameters = {
							direction ="forward",
							step = 3,
						--	time_limit =20,
							release_interval =10,
							duration = 3}}

	---- preparing input dataset 
	data_input_table = {
		data_format = "unstructured",
		input_parameters = {
				name = "./FF050_sample.uns",
				options = {
					input_mode = "replace",
					transient = "off"
				},
		}
	}

	---- read dataset
	SampleTableHandle= read_dataset(data_input_table)

	fv_script("RESTART BOUNDARY sample.bnd")
	fv_script("RESTART FORMULA sample.frm")

	---- create streamline
	rake_handle=create_streamline(streamline_table)


	---- export streamline location plots
	strFileName="tmp.lne"
	fv_script("EXPORT STREAM "..strFileName)


	----  storing streamline location plots data
	nPlots, Xarray, Yarray, Zarray=ReadPlotsArray(strFileName)

	print("plots check")
	print("nPlots: "..nPlots)
	for i=1, nPlots do                  ---- 点の数だけ 読み込む loop
		print(Xarray[i].." "..Yarray[i].." "..Zarray[i])
	end
	print("------------------------------")


	----  define so surface table
	iso_table = {
				dataset = 1,
				iso_func = {
					mode = "point_and_normal",
							pt1 = {
								Xarray[1], Yarray[1], Zarray[1]},
							pt2 = {
								Xarray[2], Yarray[2], Zarray[2]},
					},
				scalar_func = "p",
				vector_func = "none",
				visibility = "off",
				display_type = "smooth_shading",
				}

	---- prepare array
	IsoHandle={}
	P_init={}
	P_term={}


	---- define file name for loop history
	fp_output =openfile("./output.log","w")

	write(fp_output, "<- path dist->")
	write(fp_output, "<--------------   norm vect  ------------->")
	write(fp_output, "< epslion s >< epsilon a  >")
	write(fp_output, "< pressure s >< pressure a>")
	write(fp_output, "<-- vort s --><-- vort a -->\n")

	---- initialization for path length
	plength=0.0

	------------------------------------
	---- main loop : start -------------
	------------------------------------

	fv_script("RECORD ON sample.avi")
	for i=1, nPlots-1, mStep do                 ---- 点の数だけ断面を作っていく

		---- set inital point for normal vector
		P_init[1]=Xarray[i]
		P_init[2]=Yarray[i]
		P_init[3]=Zarray[i]

		---- set terminal point for normal vector
		P_term[1]=Xarray[i+1]
		P_term[2]=Yarray[i+1]
		P_term[3]=Zarray[i+1]


		---- calculate step length
		slength=0.0
		for elem=1, 3 do
			slength=slength + (P_term[elem] - P_init[elem])^2
		end
		slength=sqrt(slength)
		plength=plength+slength
		strPathLength=format(" %12.4e ", plength)
		write(fp_output, strPathLength)

		---- calculate and write normal vector
		for elem=1, 3 do
			strNormVecElem=format(" %12.4e ", P_term[elem]-P_init[elem])
			write(fp_output, strNormVecElem)
		end




		---- modify iso_table
		iso_table = {
					iso_func = {
						mode = "point_and_normal",
							pt1 = {
								P_init[1], P_init[2], P_init[3]},
							pt2 = {
								P_term[1], P_term[2], P_term[3]},
						},
					scalar_func = "epsilon",
					scalar_range = {
						use_local = "on",
						},
					visibility = "on",
					display_type = "smooth_shading",
					}

		---- create iso-surface 
		IsoHandle[i]=create_iso(iso_table)


		---------------------------------------------
		----   for "epsilon" as 1st variable    -----
		----       native variable of FV-UNS    -----
		---------------------------------------------

		result=integrate_surface(IsoHandle[i])
		epsilon_Sum=result.sum
		epsilon_Ave=result.average

		strEpsilon=format(" %12.4e  %12.4e ", epsilon_Sum, epsilon_Ave)
		write(fp_output, strEpsilon)



		---------------------------------------------
		----   for "pressure" as 2nd variable   -----
		----    non-native variable of FV-UNS   -----
		---------------------------------------------

		extraction_table=query(IsoHandle[i])
		modify(IsoHandle[i], extraction_table)

		modify(IsoHandle[i],{scalar_func = "pressure"})

		result=integrate_surface(IsoHandle[i])
		P_Sum=result.sum
		P_Ave=result.average

		strPressure=format(" %12.4e  %12.4e ", P_Sum, P_Ave)
		write(fp_output, strPressure)



		---------------------------------------------
		----   for "mag_vort" as 3rd variable   -----
		----    non-native variable of FV-UNS   -----
		---------------------------------------------

		extraction_table=query(IsoHandle[i])
		modify(IsoHandle[i], extraction_table)

		modify(IsoHandle[i],{scalar_func = "mag_vort"})

		result=integrate_surface(IsoHandle[i])
		MV_Sum=result.sum
		MV_Ave=result.average

		strMagVorticity=format(" %12.4e  %12.4e ", MV_Sum, MV_Ave)
		write(fp_output, strMagVorticity)




		---- export current surface data
		-- strExportFile=format(strPrefix.."%3.3d.dat", i)
		-- print(strExportFile)
		-- fv_script("EXPORT ISO "..strExportFile)


		write(fp_output, "\n")

	end

	------------------------------------
	---- main loop : end   -------------
	------------------------------------

	closefile(fp_output)


	fv_script("RECORD OFF")



