#pragma rtGlobals=3		// Use modern global access method and strict wave access.
#pragma IgorVersion = 6.2
#pragma ModuleName = PearlPmscoImport

// copyright (c) 2018 Paul Scherrer Institut
//
// Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//   http:///www.apache.org/licenses/LICENSE-2.0
//
// Please acknowledge the use of this code.

/// @file
/// @brief data import/export procedures for multiple scattering calculations.
/// @ingroup ArpesPackage
///
///
///
/// @author matthias muntwiler, matthias.muntwiler@psi.ch
///
/// @copyright 2018 Paul Scherrer Institut @n
/// Licensed under the Apache License, Version 2.0 (the "License"); @n
///   you may not use this file except in compliance with the License. @n
///   You may obtain a copy of the License at
///   http://www.apache.org/licenses/LICENSE-2.0
///

/// @namespace PearlPmscoImport
/// @brief data import/export procedures for multiple scattering calculations.
///
/// PearlPmscoImport is declared in @ref pearl-pmsco-import.ipf.


/// save waves in a PMSCO scan data file.
///
/// @warning experimental. this function is work in progress.
///
/// cases
/// - phd scan: separate energy, theta, phi, alpha, intensity waves
/// - hemi scan: separate energy, theta, phi, intensity waves
/// - polar/azi scan: intensity wave, angle is in x scale
///
/// options
/// - sigma wave
///
/// the data arguments are strings and can be 
/// @arg		the name of an existing wave
///			(optionally including a path relative to the specified source folder),
/// @arg		the string representation of a constant numeric value,
/// @arg 		a dimension specifier ("x", "y", "z" or "t") 
///			referring to the dimension scale of the intensity wave, or
/// @arg		an empty string if the corresponding axis should not be saved.
///
/// wave names can include a path relative to the specified source data folder.
/// by default, the function looks in the folder specified by the sdfr argument.
///
/// @param pathname		name of igor symbolic path to destination folder.
///						prompt user if empty.
///
/// @param filename		requested file name.
///						prompt user if empty.
///						@note the extension should include the symbols of
///						the included parameters in the order "etpais".
///						if the intensity wave contains a modulation function,
///						".modf" should be inserted before the extension.
///						in interactive mode, igor tends to override the file extension
///						with a standard one like ".txt".
///
/// @param energy		energy specification. see description above.
///
/// @param theta			theta specification. see description above.
///
/// @param phi			phi specification. see description above.
///
/// @param alpha			alpha specification. see description above.
///
/// @param intensity		name of intensity (or modulation) wave.
///						this parameter is mandatory and must refer to an existing wave.
///
/// @param sigma		sigma specification. see description above.
///
/// @param sdfr			source data folder reference.
///						default: current data folder.
///
/// @return				file name
///
function /s pmsco_save_scan(pathname, filename, energy, theta, phi, alpha, intensity, sigma, [sdfr])
	string pathname
	string filename
	string energy
	string theta
	string phi
	string alpha
	string intensity
	string sigma
	dfref sdfr

	//string fileext
	//fileext = StringFromList(ItemsInList(filename, ".") - 1, filename, ".")
	
	dfref savedf = GetDataFolderDFR()
	dfref tempdf = NewFreeDataFolder()

	if (ParamIsDefault(sdfr))
		dfref sdfr = savedf
	endif
	SetDataFolder sdfr
	wave w_intensity = $intensity
	string wavenames = ""
	
	wavenames = save_scan_helper("w_energy", energy, w_intensity, tempdf, wavenames)
	wavenames = save_scan_helper("w_theta", theta, w_intensity, tempdf, wavenames)
	wavenames = save_scan_helper("w_phi", phi, w_intensity, tempdf, wavenames)
	wavenames = save_scan_helper("w_alpha", alpha, w_intensity, tempdf, wavenames)
	wavenames = save_scan_helper("w_intensity", intensity, w_intensity, tempdf, wavenames)
	wavenames = save_scan_helper("w_sigma", sigma, w_intensity, tempdf, wavenames)
	
	setdatafolder tempdf
	save /b /g /m="\n" /p=$pathname wavenames as filename
	setdatafolder savedf
end

/// helper function for save_pmsco_scan()
///
static function /s save_scan_helper(destname, value, template, destdfr, wavenames)
	string destname
	string value
	wave template
	dfref destdfr
	string wavenames
	
	variable err = 0
	if (strlen(value) > 0)
		if (exists(value) == 1)
			duplicate $value, destdfr:$destname
			wave /sdfr=destdfr w=$destname
		else
			duplicate template, destdfr:$destname
			wave /sdfr=destdfr w=$destname
			variable numval = str2num(value)
			string msg
			if (numtype(numval) == 0)
				w = numval
			//elseif (cmpstr(value[0,0], "%") == 0)
			else
				strswitch(value)
					case "x":
						w = DimOffset(template, 0) + DimDelta(template, 0) * p
						break
					case "y":
						w = DimOffset(template, 1) + DimDelta(template, 1) * q
						break
					case "z":
						w = DimOffset(template, 2) + DimDelta(template, 2) * r
						break
					case "t":
						w = DimOffset(template, 3) + DimDelta(template, 3) * s
						break
					default:
						err = 1
						sprintf msg, "invalid %s argument", StringFromList(1, destname, "_")
				endswitch
			endif
		endif
		if (err == 0)
			wavenames = AddListItem(destname, wavenames, ";", inf)
			variable npts = DimSize(w, 0) * max(DimSize(w, 1), 1) * max(DimSize(w, 2), 1) * max(DimSize(w, 3), 1)
			Redimension /n=(npts) w
		else
			abort msg		
		endif
	endif
	return wavenames
end

/// load an xyz cluster file
///
/// load an xyz cluster file into the current data folder
/// the wave names are at (atom types), xx, yy, and zz.
/// at is a text wave containing chemical symbols.
/// existing waves are overwritten.
///
/// @param	pathname		name of igor symbolic path. can be empty (path is taken from filename argument).
///
/// @param	filename			file system path. can be empty (will open dialog).
///
function /s pmsco_load_xyz(pathname, filename)
	string pathname
	string filename

	string cis = "N=at;N=xx;N=yy;N=zz;"
	LoadWave /A /B=cis /J /K=0 /L={0, 2, 0, 0, 0} /V={" ", " ", 0, 0} /O /P=$pathname filename
	wave /t at
	at = unpadstring(at, 32)
end
