// $BACKGROUND$

	//get ini cube
	image DataCube := getFrontImage()
	string DataName = DataCube.getName()
	
	//check 3D dimensions
	if(DataCube.ImageGetNumDimensions()!=3) 
		{
		OKdialog("wrong format for data cube !!");
		exit(0)
		}
	
	number width,height,Depth 
	DataCube.get3Dsize(width,height,Depth) 
	
	number ScaleX,ScaleY,ScaleE,ScaleI
	number OriginX,OriginY,OriginE,OriginI
	string unitX,unitY,unitE,unitI
	DataCube.ImageGetDimensionCalibration(0,OriginX,ScaleX,unitX,1)
	DataCube.ImageGetDimensionCalibration(1,OriginY,ScaleY,unitY,1)
	DataCube.ImageGetDimensionCalibration(2,OriginE,ScaleE,unitE,1)
	
	//cut in space
	number top,left,bottom,right
	number widthNew,HeightNew
	
	image AvImage := MSA112_MakeMeanImage(DataCube)
	AvImage.showimage()
	imageDisplay dispI = AvImage.ImageGetImageDisplay(0)
	roi Sel  = NewRoi()
	Sel.ROISetRectangle(0,0,height,width) 
	Sel.ROISetColor(0,1,0)
	dispI.ImageDisplayAddRoi(Sel)

	if(MSA112_SetFeatureInImage("Select area by moving ROI.\nClick Cancel if full area is requered.","Cut selected"))
		{
		Sel.ROIGetRectangle(top,left,bottom,right)
		WidthNew = Right - Left
		HeightNew = bottom -top
		OriginX -= left
		OriginY -= top	
		}
	else 
		{
		bottom = height
		right = width
		WidthNew = Width
		HeightNew = Height
		}
//result("\n"+top+" "+left+" "+bottom+" "+right)	
	AvImage.deleteimage()
	
	//cut in energy
	number Estart,Eend=depth/2
	number EstartEv = (Estart-OriginE)*ScaleE
	number EendEv = (Eend-OriginE)*ScaleE	
	number DepthNew
	
	image AvSpec := MSA112_MakeAverageSpectrum(DataCube)
	AvSpec.showimage()
	imageDisplay disp = AvSpec.ImageGetImageDisplay(0)
	roi Range  = NewRoi()
	Range.ROISetRange(0,Depth/2) 
	disp.ImageDisplayAddRoi(Range)	

	if(MSA112_SetFeatureInImage("Select the energy range by moving ROI.\nClick Cancel if the whole range is required.","Cut selected"))
		{
		Range.ROIGetRange(Estart,Eend)
		DepthNew = Eend - Estart 
		OriginE -= Estart
		}
	else 
		{
		Eend = Depth
		DepthNew = Depth
		Range.ROISetRange(0,Depth)
		}
//result("\n"+WidthNew+"x"+HeightNew+"x"+DepthNew)
	AvSpec.deleteimage()

	//create clipped cube
	number type = dataCube.ImageGetDataType()
	image DataCubeRed := MSA112_Make3DImageOfRightType(type,DataName+"_R",WidthNew,HeightNew,DepthNew)
	DataCubeRed = DataCube[left,top,Estart,right,bottom,Eend] 

	//copy all tags
	TagGroup IniTags = DataCube.ImageGetTagGroup()
	TagGroup FinTags = DataCubeRed.ImageGetTagGroup()
	TagGroupCopyTagsFrom(FinTags,IniTags)
	
	number IntScale
	Getnumber("Rescale intensity",1,IntScale)
result("\nmultiplied by "+IntScale)	
	DataCubeRed *=IntScale
	
	//Calibration
//result("\n"+OriginX+" "+OriginY+" "+OriginE)	
	DataCubeRed.ImageSetDimensionCalibration(0,OriginX,ScaleX,unitX,1)
	DataCubeRed.ImageSetDimensionCalibration(1,OriginY,ScaleY,unitY,1)
	DataCubeRed.ImageSetDimensionCalibration(2,OriginE,ScaleE,unitE,1)
	
	DataCubeRed.showimage()
