{
Progam is used for Center Search purpose  

This program generate 1D radial intensity curve from ED image
Before start of this program you need to generate Ratio image
with "General_RATany4F.v"

Progam will ask to select image for processing, and it should be open on on desktop

Progam will ask to select initialization file located in directory specified with constant "P"

All modification of the center, and file directory structure should be modified in initialization file

Passed parameters
Directory structure:
------------->> lines from <XXX>.ini
::
[Paths]

PathU=D:\DATA\Utilities\   				 --> read a path for Masks
PathR=D:\DATA\Utilities\XYarrayNEW\		 --> read a path for polar image
Path=D:\DATA\11012002\Mean\		   		 --> read a base path
::
::
Center=CenterGS\						 --> read a path for output file
::
<<--------------  



------------->> lines from <XXX>.ini
::
[Images]
:: 
Mask=M512.tif		  	   				 --> binary Mask image
::
AppMask=M512.tif						 --> binary apparatus Mask (could be different) 
::
::
<<--------------  

Output file saved in directory <Path><Center> with extention CSV
Naming convention:
<"x"><cX*10><"y"><cY*10><image name>.csv

cX*10 --> lable for center coordinate in X multiplied by factor of 10
cY*10 --> lable for center coordinate in Y multiplied by factor of 10  

File contains four columns:
1st column <pix>   	--> pixel number from the center
2nd column <FULL>  	--> 1D averaged intensity curve over FULL image
3nd column <LEFT>   --> 1D averaged intensity curve over LEFT half of the image
4th column <RIGHT>	--> 1D averaged intensity curve over RIGHT half of the image

created 13/01/2002 by V.Lobastov Ver. 08.}


const
  	 Prompt = 'Select an image for calculation' ;
		 	  //P ='D:\UED3_Data_processed\Utilities\Delays\*.ini'; 		 	  //default directory for INI file
		  	  	P ='d:\data\UED4_Data_processed\Utilities_UED4\Delays\*.ini'; 		 	 	  //default directory for INI file

var
   Sel;	 			   			   //selector constant for initialization file
   Path;						   //Path constant for a base path
   PathU;						   //Path constant for a path for Masks
   PathR; 						   //Path constant for a path for polar image	
   PathC;  	                       //Paths constant for a path output file

 
 
   
   Size_x, Size_y;				   //image size constants
   F;					 		   //field image variables for full, left, and right halves CCD
   Image_I;                        //Input ED Image
   i, j;						   //indices
   Start;						   //start index for calculation

   Mask_II;                        //Image Intensifier Mask Image
   Fuss;						   //image of the apparatus imperfections
   FName;                          //Output filename
 




	Data;						   //output ASCII array
	SamName;					   //name of the file
	X0,Y0;					   	   //center coordinates
	alpha, beta, CamDist;		   //elliptical distortion parameters
	RR;  						   //name for polar array

	M512, M512L, M512R, M512LC, M512RC;	//mask images names
	Mask_L;		 					//mask image variables
   	AppMask;						   //apparatus mask file for defect, hot spots etc.
	MLC,MRC;						   			   //obsolete 
	ML, MR, MT, MB; 						//mask images for right, left, top, and bottom	
	Image_e;										{Elliptical Mask Image}  
	
{

******************************************************************
********************** function Select ***************************
******************************************************************
This function return a full file name for a file 
}	 	 

function SELECT;											
		var
   		   nName; Name, ix;
   		   Choice, nDIR;
		begin
	 		 Name:=FindFirstFile(P, fa_Archive);				  	 	 		//Find the first ini file in the delays directory 
	 		 nName:=ExtractFileName(Name);										//Convert the file name and the extension to a string
	 		 nDIR:= ExtractFilePath(Name);										//Return the drive and directory portions of a file name including the trailing backslash
			 ix:=0;																//initialize the variable ix to value of zero
	  		 
			 while StrLen(Name) > 0 do											//If there is a file in the directory, do

	  		 	   begin
	  	   		   		Name:=ExtractFileName(FindNextFile) ;					//Finde the next ini file in the delays directory
		   				nName:=nName+';'+Name;									//Augment the nName string with the next file name
					 if ix>100 then halt('Too many Files in Directory');   		//Stop, if there are more than 100 files
					 	ix:=ix+1;			  	   		 						//Increase the counter ix by 1
	 				end; 

	 			 if SelectString( 'Select File',nName , Choice ) >= 0 then		//If a selection among nName strings is made from the dialog box, then
	 			 	begin
			 			 SELECT:=nDIR+Choice;		  		   	 	  			//Initialize SELECT to the selected ini file
	 				end	
	 			else
	 				begin 
	 	 	  			  WriteInfo('No Selection made! Restart program! ');	//Inform the user that no selection was made
		 	  			  halt;					  						 		//abort the program
	 				end; 
		end;
//----------------------> end of function SELECT <-----------------------------------			



{
 ************************************************************************
 ***                                                                  ***
 ***	                      function MeanOfRad(MM)				  ***
 ***																  ***
 ************************************************************************ 
This function will return and mean count of the ring at certain radius
and specified mask as in put parameter
 }  
function MeanOfRad(Image_e, MM);
	var
	   F_Image, Masked_FF, F_pix;	
		
		 begin

               F_Image := Image_e and (MM);			     			  	  		//binary ring of current radius masked by MM   
               F_pix:= Longint(SumOf(F_Image)); 	   	  						//calculate the number of pixels in the ring
               Masked_FF:=Single(Image_I*F_Image);								//mask the electron diffraction image with the current righ image	
						 
               if (F_pix = 0) then		         							    //if there is no ring
                    begin
                        MeanOfRad:=0;											//the mean is zero
                    end
               else
                        MeanOfRad:=Single(SumOf(Masked_FF)/F_pix); 	   			//calculate the mean count for current radius						
Free(F_Image);
Free(Masked_FF);
			end;

			 
//-------> end of function MeanOfRad



{
************************************************************************
 ***                                                                  ***
 ***	                      Procedure RAD_Ellipse					  ***
 ***																  ***
 ************************************************************************ 
This procedure generates elliptical mask images using the given input parameters 
 }  

procedure RAD_Ellipse(X_off,Y_off, alpha, beta, CamDist);



var
  r, t;							   				{indices}
  a,b;											{elliptical major and minor semi-axis}
  theta;										{scattering angle}
  CenterShift, Xr, Yr;							{Center of ellipse of given radius}
  Xt, Yt;	   	   								{Coordinates of the ellipse}
  Ed1;                            				//Output ASCII file
  
begin
  
  
 
  Data := CreateArray( single, 6, Size_x) ;				//create an array of type single with 6 columns and x rows
	 if IsNull( Data ) then		  	 		 				//If array Data is unititialized, then
		begin
			 WriteError( 'Insufficient memory to create array!' ) ;	//tell the user why
			 Halt;		 			   		  	 				  	//abort the program
		end;
	   
  //CreateDir(Path+'EllipticalMasks\');		 		  			 		//create directory for output
 
  for r:= 0 to 600 do
  //for r:= 0 to Integer((Size_x-1)/2-1) do
  	  begin 
  	  	 	theta:=arctan(r/CamDist);
			
			CenterShift:=0.5*(-CamDist*sin(theta)/cos(alpha-theta)+CamDist*sin(theta)/cos(alpha+theta));
  			Xr:=X_off+CenterShift*cos(beta);									//Define the center X position for each radius
			Yr:=Y_off-CenterShift*sin(beta);									//Define the center Y position for each radius
			//a:=r;																// to do circular averages			
			a:=0.5*(CamDist*sin(theta)/cos(alpha-theta)+CamDist*sin(theta)/cos(alpha+theta));  //to do elliptical averages
  		   	b:=r;
			//Halt(Xr);
			Image_e:=0;															//reset the variables
			t:=0;
			
			while (t<2*3.14159265) do		  									//generate elliptical mask image
    		begin	  	 					
				Xt:= Round(Xr+a*cos(t)*cos(beta)-b*sin(t)*sin(beta));			// x coordinate of the ellipse
				Yt:= Round(Yr+a*cos(t)*sin(beta)+b*sin(t)*cos(beta));			// y coordinate of the ellipse
				Image_e[Xt,Yt]:=1;
				t:=t+0.001;
			end;
			
			//Show(Image_e);
			//Halt('');
			
			Data[0,r]:=r;														//The first column holds the radius
			Data[1,r]:=MeanOfRad(Image_e,Mask_II);								//The second column holds the mean count for that radius which was masked by Mask_II
			Data[2,r]:=MeanOfRad(Image_e,ML);									//The third column holds the mean count for that radius which was masked by ML
			Data[3,r]:=MeanOfRad(Image_e,MR);		 							//The fourth column holds the mean count for that radius which was masked by MR
     		Data[4,r]:=MeanOfRad(Image_e,MT);									//The firth column holds the mean count for that radius which was masked by MT
			Data[5,r]:=MeanOfRad(Image_e,MB);		 							//The sixth column holds the mean count for that radius which was masked by MB
			WriteStatus('pix= ', Data[0,r], ' Mean_F= ', Data[1,r],  ' Mean_L= ', Data[2,r], ' Mean_R= ', Data[3,r], ' Mean_T= ', Data[4,r], ' Mean_B= ', Data[5,r]);	  //Display a message in the status bar.
								 			
		//	Save(Image_e,Path+'EllipticalMasks\'+'r'+Str(r)+'.tif');			//save the radial image in the output directory
		
	 end;
		
	 
{---------> Create Output ASCII file}
    	 Ed1:=CreateEditor(SamName+'_FLR');										//Create a window on the desktop for text output							
         WriteLn(Ed1,'pix', ',', 'FULL', ',', 'LEFT', ',', 'RIGHT', ',', 'TOP', ',', 'BOTTOM') ;			//Write the first line of the output (column titles)
		  
     for j:=0 to Integer(Size_x/2-1) do 		  	   						//for all radii do:
	 begin
         Write(Ed1, ShortInt(Data[0,j]), ',', Data[1,j]:20:15, ',', Data[2,j]:20:15, ',', Data[3,j]:20:15, ',', Data[4,j]:20:15, ',', Data[5,j]:20:15);	  //Write the contents of the array data into the editor window
         WriteLn(Ed1);					 	  				   					//end with a blank line
 	 end;	 
		 Save(Ed1, Path +PathC + RR+SamName+'_FLR'+'.csv');						//save the output as a *.csv file

{------> Free memory}

		 Delete(Ed1);
		 Free(Data) ;
		 Free(Image_e);
	 
end; 

  
{---------> end of procedure RAD_Ellipse}




{
 ************************************************************************
 ************************************************************************
 ***                                                                  ***
 ***	                      Main program							  ***
 ***																  ***
 ************************************************************************ 
 ************************************************************************
}

begin

    {-------> Get Input Data Image}
                                        { check for images }
                   if GetNumImages = 0 then halt( 'This program requires a desktop image' ) ;		//check for images on the desktop
                   SelectImage( Prompt,Image_I ) ;						   		   		  			//select an image from the desktop to initialize variable Image_I	  
                   if IsNull( Image_I ) then halt( 'No image was selected' ) ;						//abort the program, if no image was selected
                   Size_x:=GetXSize(Image_I);	   	   		 	 		   	 						//read the x-dimension of the selected image
                   Size_y:=GetYSize(Image_I);														//read the y-dimension of the selected image
				   SamName:=GetName(Image_I);														//Return the name of a desktop image
			
 

{------> Default center}
	 		Sel:=SELECT;												 // selector for initialization file
{------> Set Center coordinates}
						      				 	  						  
				 X0:=Val(ReadPrivateINIString( Sel, 'Center', 'cX'));	 //read a center coordinates for X
				 Y0:=Val(ReadPrivateINIString( Sel, 'Center', 'cY'));	 //read a center coordinates for Y
				 alpha:=Val(ReadPrivateINIString( Sel, 'Center', 'alpha'));	 //read the detector tilt angle in radians
				 beta:=Val(ReadPrivateINIString( Sel, 'Center', 'beta'));	 //read the ellipse rotation angle in radians
				 CamDist:=Val(ReadPrivateINIString( Sel, 'Center', 'CameraDistance'));	 //read the CameraDistance in cm
				 CamDist:=CamDist*10000/60;				 		   		 //convert to unit of pixels
			
	 			 Path:= ReadPrivateINIString( Sel, 'Paths', 'Path');	 //read a base path
	 			 PathU:= ReadPrivateINIString( Sel, 'Paths', 'PathU');	 //read a path for Masks
				 PathR:=ReadPrivateINIString( Sel, 'Paths', 'PathR');	 //read a path for polar image				 	

				 PathC:=ReadPrivateINIString( Sel, 'Paths', 'Center');	 //read a path for output file

				 if (StrLen(FindFirstFile( Path+PathC+'*.csv', fa_Archive)) = 0) then				 
				 CreateDir(Path+PathC);		 		  				 	   	  		//create directory for output

//-----------> definition for Mask Images
 
				 M512:=ReadPrivateINIString( Sel, 'Images', 'Mask');  	  		 //read a mask file name			 
				 AppMask:=ReadPrivateINIString( Sel, 'Images', 'AppMask'); 		//apparatus mask

//-----------> Make left, right, top, and bottom mask images
				 Open(PathU + M512, Mask_II);					
                   if IsNull( Mask_II ) then halt( 'No Reference image was selected' );
				 //Show(Mask_II, 'Mask_II');
				 ML:= CreateImage(typ_Binary, Size_x,Size_y);					//create an image of type binary
				 MR:= CreateImage(typ_Binary, Size_x,Size_y);					//create an image of type binary
				 MT:= CreateImage(typ_Binary, Size_x,Size_y);					//create an image of type binary
				 MB:= CreateImage(typ_Binary, Size_x,Size_y);					//create an image of type binary
				 //Halt(Size_y);
				 ML[0..X0, 0..Size_y-1]:=Mask_II[0..X0, 0..Size_y-1];		 			 //copy specific region of Mask_II
				 MR[X0..Size_x-1, 0..Size_y-1]:=Mask_II[X0..Size_x-1, 0..Size_y-1];		 //copy specific region of Mask_II
				 MT[0..Size_x-1, 0..Y0]:=Mask_II[0..Size_x-1, 0..Y0];		 			 //copy specific region of Mask_II
				 MB[0..Size_x-1, Y0..Size_y-1]:=Mask_II[0..Size_x-1, Y0..Size_y-1];		 //copy specific region of Mask_II
				 

//--------->create elliptical mask images			   
					 
				    Image_e:= CreateImage(typ_Binary, Size_x,Size_y);
					RR:='x'+Str(Word(Round(10*X0)))+'y'+Str(Word(Round(10*Y0)));						  
					RAD_Ellipse(X0,Y0, alpha, beta, CamDist);
					PlaySound( 'C:\Program Files\Digital Optics\V++\Library\Mac.wav' ) ;								
					WriteInfo('Calculation completed!');

	Free(Mask_II);
	Free(Fuss);
	Free(F);
	Free(ML);				
	Free(MR);
	Free(MT);				
	Free(MB);
	Free(Image_I);

end
