
	
/****************************************************
Import 
****************************************************/
class Conversion_MSA112: MSA112_UIFrame
{
number DefUpsample
number DefScale
number DefSpatOrigin
string DefScaleUnit
number DefDispersion
number DefEnergyOrigin
string DefEnergyUnit
number showHDF5
 
number t
number runningBinary, runningVelox, runningJeol
	
TagGroup CreateProgress(object self)
	{
	TagGroup Dialog = DLGCreatedialog("")
		TagGroup Upper = DLGCreatedialog("")
		Upper.DLGTableLayout(3,1,0)
	Upper.DLGAddElement(DLGcreateLabel("  "+MSA112_Version()+"    ").DLGIdentifier("Version"))
	Upper.DLGAddElement(self.InfoButton(20,210))
	Upper.DLGAddElement(self.settingsButton(20,210,"Settings"))
		TagGroup Lower = DLGCreatedialog("")
		Lower.DLGTableLayout(2,1,0)
	Lower.DLGAddElement(DLGcreateLabel("                    ").DLGAnchor("East").DLGIdentifier("Message"))
	Lower.DLGAddElement(DLGcreateLabel("hold ALT for info"))	

	Dialog.DLGAddElement(Upper)
	Dialog.DLGAddElement(Lower)
	Dialog.DLGAddElement(DLGcreateProgressBar("P bar").DLGfill("X"))
	
	return Dialog
	}
	
TagGroup CreateImportFrame(object self)
	{
	TagGroup DialogAll = DLGCreateDialog("")

	TagGroup DialogImport =DLGCreateBox("import")
	DialogImport.DLGTableLayout(2,4,0)

	DialogImport.DLGAddElement(DLGCreateLabel("                binning").DLGanchor("east"))	
	DialogImport.DLGAddElement(DLGCreateIntegerField(4,2).DLGIdentifier("upsampling").DLGIdentifier("upsampling").DLGanchor("West"))	
	
	DialogImport.DLGAddElement(DLGCreateLabel("Velox (.emd):").DLGanchor("East"))
	DialogImport.DLGAddElement(DLGCreatePushButton("import","RunVelox").DLGIdentifier("runVelox"))

	DialogImport.DLGAddElement(DLGCreateLabel("JEOL (.pts):").DLGanchor("East"))
	DialogImport.DLGAddElement(DLGCreatePushButton("import","RunJeol").DLGIdentifier("runJeol"))
	
	DialogImport.DLGAddElement(DLGCreateLabel("raw data:").DLGanchor("East"))
	DialogImport.DLGAddElement(DLGCreatePushButton("import","RunBinary").DLGIdentifier("runBinary"))
			
			
	TagGroup DialogCalibrate = DLGCreateBox("calibrate")
	DialogCalibrate.DLGTableLayout(3,5,0)
	
	DialogCalibrate.DLGAddElement(DLGCreateLabel("scale ").DLGanchor("west"))
	DialogCalibrate.DLGAddElement(DLGCreateLabel("origin").DLGanchor("west"))
	DialogCalibrate.DLGAddElement(DLGCreateLabel("units").DLGanchor("west"))
	
	DialogCalibrate.DLGAddElement(DLGCreateRealField(1,8,5).DLGIdentifier("scale"))
	DialogCalibrate.DLGAddElement(DLGCreateIntegerField(50,4).DLGIdentifier("origin"))
	DialogCalibrate.DLGAddElement(DLGCreateStringField("nm",8).DLGIdentifier("scaleUnits"))
	
	DialogCalibrate.DLGAddElement(DLGCreateLabel("dispersion").DLGanchor("west"))
	DialogCalibrate.DLGAddElement(DLGCreateLabel("origin").DLGanchor("west"))
	DialogCalibrate.DLGAddElement(DLGCreateLabel("units").DLGanchor("west"))
	
	DialogCalibrate.DLGAddElement(DLGCreateRealField(1,8,5).DLGIdentifier("dispersion"))
	DialogCalibrate.DLGAddElement(DLGCreateIntegerField(50,4).DLGIdentifier("Eorigin"))
	DialogCalibrate.DLGAddElement(DLGCreateStringField("eV",8).DLGIdentifier("dispersionUnits"))

	DialogCalibrate.DLGAddElement(DLGCreateLabel("").DLGanchor("west"))
	DialogCalibrate.DLGAddElement(DLGCreateLabel("").DLGanchor("west"))
	DialogCalibrate.DLGAddElement(DLGCreatePushButton("calibrate","Calibrate"))
			
	DialogAll.DLGAddElement(self.CreateProgress())
	DialogAll.DLGAddElement(DialogImport)	
	DialogAll.DLGAddElement(DialogCalibrate)
	
	return DialogAll
	}
	
object init(object self,string Package,string Name)
	{
	self.MSA112_initUIFrame(self.CreateImportFrame(),Package,Name)
	
	//load tunable parameters
	DefUpsample = self.MSA112P_DefUpsample()
	showHDF5 = self.MSA112P_showHDF5()	
	DefScale = self.MSA112P_DefScale()
	DefSpatOrigin = self.MSA112P_DefSpatOrigin()
	DefScaleUnit = self.MSA112P_DefScaleUnit()
	DefDispersion = self.MSA112P_DefDispersion()
	DefEnergyOrigin = self.MSA112P_DefEnergyOrigin()
	DefEnergyUnit = self.MSA112P_DefEnergyUnit()

	
	MSA112_reset()
	
	//set default visible settings
	try{	//if tool is already opened, objectID mismatch and setting fail
	self.LookUpElement("scale").DLGValue(DefScale)
	self.LookUpElement("origin").DLGValue(DefSpatOrigin)
	self.LookUpElement("scaleUnits").DLGValue(DefScaleUnit)
	self.LookUpElement("dispersion").DLGValue(DefDispersion)
	self.LookUpElement("Eorigin").DLGValue(DefEnergyOrigin)
	self.LookUpElement("dispersionUnits").DLGValue(DefEnergyUnit)
	}
	catch{break;}
	
	}

/*********************Setting****************************/
void Settings(object self)
	{	
	number NumberLines = 8		//number of adjusted parameters
	TagGroup SettingList = DLGCreateBox("Settings").DLGTableLayout(1,NumberLines,1)

	taggroup tg0 =	self.AddSettingsLine_Int(SettingList,self.MSA112P_DefUpsample(),3)
	taggroup tg1 =	self.AddSettingsLine_Check(SettingList,self.MSA112P_showHDF5())
	taggroup tg2 =	self.AddSettingsLine_Real(SettingList,self.MSA112P_DefScale(),6,2)
	taggroup tg3 =	self.AddSettingsLine_Int(SettingList,self.MSA112P_DefSpatOrigin(),5)
	taggroup tg4 =	self.AddAddSettingsLine_Str(SettingList,self.MSA112P_DefScaleUnit(),6)
	taggroup tg5 =	self.AddSettingsLine_Real(SettingList,self.MSA112P_DefDispersion(),6,2)
	taggroup tg6 =	self.AddSettingsLine_Int(SettingList,self.MSA112P_DefEnergyOrigin(),5)
	taggroup tg7 =	self.AddAddSettingsLine_Str(SettingList,self.MSA112P_DefEnergyUnit(),6)
	
	MSA112_reset()
	
	object SettingsFrame = Alloc(UIframe).init(SettingList)
	if(SettingsFrame.Pose())
		{
		defUpsample = self.SettingNumberParameter(tg0)
			self.LookUpElement("upsampling").DLGValue(defUpsample)
		ShowHDF5 = self.SettingNumberParameter(tg1)
		DefScale = self.SettingNumberParameter(tg2)
		DefSpatOrigin= self.SettingNumberParameter(tg3)
		DefScaleUnit = self.SettingStringParameter(tg4)
		DefDispersion = self.SettingNumberParameter(tg5)
		DefEnergyOrigin = self.SettingNumberParameter(tg6)
		DefEnergyUnit= self.SettingStringParameter(tg7)	
		}
	}

	

/*********************Import Binary****************************/
void RunBinary(object self)
	{
	self.MSA112_Info("binary import",340,210,\
	"press this button"+\
	"\nto import binary SI"+\
	"\ndata, for instance" +\
	"\nBruker Esprit" +\
	"\nstored as raw")
	
	if(runningBinary==0)
		{
		self.RunThreadFromDLG("ImportBinary",runningBinary,"runBinary","stopBinary")
		//Thread name (no parameters);GLOBAL thread running number;start/stop button IDENTIFIERS
		}
	}

void StopBinary(object self)
	{
	self.StopThreadFromDLG(runningBinary,"stopBinary")
	//GLOBAL thread running number; start/stop button IDENTIFIERS
	}

void TerminateBinary(object self)
	{
	self.TerminateThreadFromDLG(runningBinary,"runBinary","stopBinary")
	//GLOBAL thread running number; start/stop button IDENTIFIERS
	}	
	
	
void ImportBinary(object self)
	{
self.MSA112_UpdateProgress("running",0)	

	try
	{	
	number upsampling =self.LookUpElement("upsampling").DLGgetValue()
		
	//open binary file
	string baseName
	string Name =  MSA112_OpenBinaryfile(baseName)
result("\nImport "+name)

	//read dimensions
	number width,height,depth,ByteDepth,offset
	
	number dataformat =MSA112_ReadRPLfile(width,height,depth,offset,ByteDepth,Name)
	
	if(dataformat ==0)	//rpl file doesnot exist or unreadable
		{
		//manual input parameters 
			TagGroup ComponentConfirm = DLGCreateDialog("define parameters of binary data:").DLGTableLayout(2,6,0)

			TagGroup widthTags =DLGCreateIntegerField(128,5).DLGIdentifier("width")
					ComponentConfirm.DLGAddElement(DLGCreateLabel("width"))
					ComponentConfirm.DLGAddElement(widthTags)					
			TagGroup heightTags =DLGCreateIntegerField(128,5).DLGIdentifier("height")
					ComponentConfirm.DLGAddElement(DLGCreateLabel("height"))
					ComponentConfirm.DLGAddElement(heightTags)	
			TagGroup depthTags =DLGCreateIntegerField(2048,5).DLGIdentifier("Edepth")
					ComponentConfirm.DLGAddElement(DLGCreateLabel("energy depth"))
					ComponentConfirm.DLGAddElement(depthTags)	
			TagGroup offsetTags =DLGCreateIntegerField(0,5).DLGIdentifier("offset")
					ComponentConfirm.DLGAddElement(DLGCreateLabel("offset"))
					ComponentConfirm.DLGAddElement(offsetTags)	
			TagGroup byteDepthTags =DLGCreateIntegerField(1,5).DLGIdentifier("byteSize")
					ComponentConfirm.DLGAddElement(DLGCreateLabel("byte size"))
					ComponentConfirm.DLGAddElement(byteDepthTags)				
				TagGroup PopUpItem
				dataformat =1 //default spectra-by-spectra
			TagGroup formatPopUp = DLGCreatePopup(PopUpItem,dataformat).DLGIdentifier("format")
				PopUpItem.DLGAddPopupItemEntry("spectrum-by-spectrum")
				PopUpItem.DLGAddPopupItemEntry("plane-by-plane")
					ComponentConfirm.DLGAddElement(formatPopUp.DLGIdentifier("PopUp"))
		
		number left =-20
		number top =80
		if(!MSA112_Confirm(self,ComponentConfirm,"set parameters","Confirm","Cancel",left,top)) 
			{
			result("\ncanceled");
			throw("")
			}	
			
		width =DLGGetValue(widthTags) 
		height =DLGGetValue(heightTags) 
		depth =DLGGetValue(depthTags) 
		offset =DLGGetValue(offsetTags) 
		byteDepth =DLGGetValue(byteDepthTags) 	
		dataformat =DLGGetValue(formatPopUp)	
		}
		
result("\nwidth "+width+" height "+height+" depth "+depth+" offset "+offset+ " byte depth "+ByteDepth)

	//check memory
	MSA112_CheckImportMemory(width,height,depth,ByteDepth)
	
	//open raw file
	number FileID
	object Stream = MSA112_ReadBinaryRawfile(FileID,Name)
	
	//set offset
	Stream.StreamSetPos(0,offset)
	
	//evaluate steps
	number steps = 10 //just divide all on 10 steps, 1 is to show start
	if(upsampling !=1) steps +=10	
	number stepped
	
	number t0 =  getOStickCount()

	//read raw file
	image cube := integerimage("",ByteDepth,0,width,height,depth)
	stepped ++
	

	if(dataFormat ==1)	//spectrum-by-spectrum
		{	
		for(number j=0;j<height;j++)
			{
if(mod(j,steps)==0) self.MSA112_ThreadMarkStart(stepped/steps,"row "+j,"\nrow "+j,t)		
			cube[0,j,0,width,j+1,depth] = MSA112_ReadOneBinaryline(stream,1,depth,width)
				
if(mod(j,steps)==0) {stepped++; self.MSA112_ThreadMarkEnd(runningBinary," ",t);}
			}
		}
	if(dataFormat ==2)	//plane-by-plane
		{
		for(number i=0;i<depth;i++)
			{
if(mod(i,steps)==0) self.MSA112_ThreadMarkStart(stepped/steps,"plane "+i,"\nplane "+i,t)		
			cube[0,0,i,width,height,i+1] = MSA112_ReadOneBinaryplane(stream,1,width,height)
				
			stepped = trunc(i/depth*steps)+1
if(mod(i,steps)==0) self.MSA112_ThreadMarkEnd(runningBinary," ",t)	
			}
		}
	
	closefile(FileID)

	image CubeF
	if(upsampling>1)
		{
		//cube.showimage()	
		CubeF :=self.MSA112_binning(cube,upsampling,upsampling,runningBinary,steps,stepped)		
		}
	else cubeF :=cube
		
	//show cube
	cubeF.ImageSetName(BaseName)
	cubeF.showimage()

	//set SI type
	cubeF.MSA112_setSpectrumType("X-ray")
		
self.MSA112_UpdateProgress("performed",0)	
	}
	catch
		{
self.MSA112_UpdateProgress("stopped",0)
		break
		}
		
self.TerminateBinary()		
	}
	


/*********************Import Velox****************************/
void RunVelox(object self)
	{
	self.MSA112_Info("Velox import",340,150,\
	"press this button"+\
	"\nto import"+\
	"\nVelox SI data")
	
	if(runningVelox==0)
		{
		self.RunThreadFromDLG("ImportVelox",runningVelox,"runVelox","stopVelox")
		//Thread name (no parameters);GLOBAL thread running number;start/stop button IDENTIFIERS
		}
	}


void TerminateVelox(object self)
	{
	self.TerminateThreadFromDLG(runningVelox,"runVelox","dummy")
	//GLOBAL thread running number; start/stop button IDENTIFIERS
	}	

	
	
void ImportVelox(object self)
	{
	
self.MSA112_UpdateProgress("running",0)		
	try
	{
	number upsampling =self.LookUpElement("upsampling").DLGgetValue()
		
//evaluate steps
number stepped, steps = 2 //just one step

	// Open Velox file 
	String filename  = MSA112_OpenVeloxfile()

stepped ++	
self.MSA112_ThreadMarkStart(stepped/steps,"reading... ","\nreading... ",t)

	TagGroup HDF5tags
	image cube :=self.MSA112_ImportVelox(filename,HDF5tags,upsampling,1)
	
	if(ShowHDF5==1) HDF5tags.TagGroupOpenBrowserWindow(0)
	
self.MSA112_ThreadMarkEnd(runningVelox," ",t)	

	//set name and show
	cube.ImageSetName(PathExtractBaseName(filename,0))	
	cube.showimage()
	
	//set SI type
	cube.MSA112_setSpectrumType("X-ray")
	
self.MSA112_UpdateProgress("performed",0)	
	}
	catch
		{
self.MSA112_UpdateProgress("stopped",0)
		break
		}
		
self.TerminateVelox()		
	}
	


/*********************Import Jeol****************************/
void RunJeol(object self)
	{
	self.MSA112_Info("Jeol import",340,180,\
	"press this button"+\
	"\nto import"+\
	"\nJeol SI data")
	
	if(runningVelox==0)
		{
		self.RunThreadFromDLG("ImportJeol",runningJeol,"runJeol","stopJeol")
		//Thread name (no parameters);GLOBAL thread running number;start/stop button IDENTIFIERS
		}
	}


void TerminateJeol(object self)
	{
	self.TerminateThreadFromDLG(runningJeol,"runJeol","dummy")
	//GLOBAL thread running number; start/stop button IDENTIFIERS
	}	

	
	
void ImportJeol(object self)
	{		
self.MSA112_UpdateProgress("running",0)		
	try
	{
	number upsampling =self.LookUpElement("upsampling").DLGgetValue()
	number signalID =2

//evaluate steps
number stepped, steps = 2 //just one step

	// Open Jeol file 
	string fileName
	if (!OpenDialog(fileName)) throw("")	
result("\n"+filename+"#")

stepped ++	
self.MSA112_ThreadMarkStart(stepped/steps,"reading... ","\nreading... ",t)

	image cube :=self.MSA112_ImportJeol(filename,upsampling,signalID)	

	//set name and show
	cube.ImageSetName(PathExtractBaseName(filename,0))	
	cube.showimage()
	
	//set SI type
	cube.MSA112_setSpectrumType("X-ray")
	
self.MSA112_UpdateProgress("performed",0)	
	}
	catch
		{
self.MSA112_UpdateProgress("stopped",0)
		break
		}
		
self.TerminateJeol()		
	}
	
	
	
	
	
void Calibrate(object self)
	{
	self.MSA112_Info("Velox import",100,330,\
	"press this button"+\
	"\nin case you wish"+\
	"\nmanually calibrate"+\
	"\nyour imported data")
	
	number scale = self.LookUpElement("scale").DLGgetValue()
	number dispersion = self.LookUpElement("dispersion").DLGgetValue()
	number origin = self.LookUpElement("origin").DLGgetValue()
	number Eorigin = self.LookUpElement("Eorigin").DLGgetValue()
	string ScaleUnits = self.LookUpElement("scaleUnits").DLGgetStringValue()
	string DispUnits = self.LookUpElement("dispersionUnits").DLGgetStringValue()
		
	image Cube := getFrontImage()

	result("\nscale:"+scale+ScaleUnits+" dispersion:"+dispersion+dispUnits+" EnergyOrigin "+EOrigin)		
	Cube.ImageSetDimensionCalibration(0,origin,scale,scaleUnits,1)
	Cube.ImageSetDimensionCalibration(1,origin,scale,scaleUnits,1)
	Cube.ImageSetDimensionCalibration(2,Eorigin,dispersion,DispUnits,1)
	}
	
}


void createAll()
{
alloc(Conversion_MSA112).init(MSA112_MSApath(),"MSA import") 

}

createAll()
