{
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 from <XXX>.ini

Center:
------------->> lines from <XXX>.ini
::
[Center]
cX=249
cY=258.0
::
<<-------------- 

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
   Ed1;                            //Output ASCII file




	Data;						   //output ASCII array
	SamName;					   //name of the file
	X0,Y0;					   	   //center coordinates
	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	  
	
{

******************************************************************
********************** 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 <-----------------------------------			


{
************************************************************************
 ***                                                                  ***
 ***	                      Procedure RAD							  ***
 ***																  ***
 ************************************************************************ 
This procedure generate polar coordinate image with center passed as input parameters 
 }  

procedure RAD(X_off,Y_off);

var
  Image_R;                                      {Polar-field image (equal radius field)}
  i, j;											{indices}
  Full;
begin
   Full:='x'+Str(Word(Round(10*X_off)))+'y'+Str(Word(Round(10*Y_off)));	  		//Rounds the center coordinates, converts the expression to word and then to a string
   if FileExists(PathR+Full+'.tif') then										//Check if a polar image already exists
   begin
      WriteStatus('File Already Exists  '+ Full);								//Report that the file exists 
   end   
   else   
   begin
      WriteStatus('X_off= '+Str(X_off)+ '  Y_off= '+Str(Y_off));				//display the center coordinates 
      Image_R:= CreateImage(Double, Size_x,Size_y);								//create a radial image of type double
      for i:= 0 to (Size_x-1) do	
         for j:= 0 to (Size_y-1) do
            Image_R[i,j] := Sqrt(Sqr(i-X_off)+Sqr(j-Y_off));					//assing a radial distance to each pixel in the image
      Save(Image_R,PathR+Full+'.tif');											//save the radial image in the output directory 
      Free(Image_R);															//free the memory held by the variable 
   end;
end;  
  
{---------> end of procedure RAD}

{
 ************************************************************************
 ***                                                                  ***
 ***	                      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(R_field, MM);
	var
	   F_Image, Masked_FF, F_pix;	
		
		 begin

               F_Image := ( R_field > i)  and (R_field <= i+1) and (MM) and (Fuss);    //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(MM)
 
{
 ******************************************************************************
 ***                                                                  		***
 ***      Procedure RadialLR(R_Field, Mask_L, Mask_R, Mask_T, Mask_B)		***
 ***																  		***
 ****************************************************************************** 
This procedure converts 2D image in 1D intensity curve;
The polar coordinates passed as parameter;

 }  

procedure RadialLR(R_Field, Mask_L, Mask_R, Mask_T, Mask_B);

   
  begin

  
				   Start:=0;					 	   							//first pixel number
						 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
				else
				
          for i:=Start to Integer((Size_x)/2-1-Start) do  	 					//count for until half the diameter (start:=0)
           begin											
				//Show(Mask_L);
				//Halt('');
				Data[0,i]:=Start+i;												//The first column holds the radius
				Data[1,i]:=MeanOfRad(R_Field,Mask_II);							//The second column holds the mean count for that radius which was masked by Mask_II
				Data[2,i]:=MeanOfRad(R_Field,Mask_L);							//The third column holds the mean count for that radius which was masked by Mask_L
				Data[3,i]:=MeanOfRad(R_Field,Mask_R);		 					//The fourth column holds the mean count for that radius which was masked by Mask_R
     			Data[4,i]:=MeanOfRad(R_Field,Mask_T);							//The firth column holds the mean count for that radius which was masked by Mask_T
				Data[5,i]:=MeanOfRad(R_Field,Mask_B);		 					//The sixth column holds the mean count for that radius which was masked by Mask_B
				WriteStatus('pix= ', Data[0,i], ' Rad_F= ', Data[1,i],  ' Rad_L= ', Data[2,i], ' Rad_R= ', Data[3,i], ' Rad_T= ', Data[4,i], ' Rad_F= ', Data[5,i]);	  //Display a message in the status bar.
           end;									  		 				  		//end of loop

					 
{---------> 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-Start-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(R_field);
		 Delete(Mask_II);
		 Delete(Mask_L);
		 Delete(Mask_R);
		 Delete(Ed1);
		 Delete(Data) ;
end;

{---------> end of procedure Radial}

{
 ************************************************************************
 ************************************************************************
 ***                                                                  ***
 ***	                      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
			
	 			 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
				 
		//		 Show(ML);
		//		 Halt('');
				 
				 
				 
				 
	{			 
				 
				 M512L:=ReadPrivateINIString( Sel, 'Images', 'MaskL');  	  	 //read a mask file LEFT name
				 M512R:=ReadPrivateINIString( Sel, 'Images', 'MaskR');  	  	 //read a mask file RIGHT name
				 M512LC:=ReadPrivateINIString( Sel, 'Images', 'CentMaskL');    	 //read a mask file LEFT center part 				 
				 M512RC:=ReadPrivateINIString( Sel, 'Images', 'CentMaskR');    	 //read a mask file RIGHT center part
}
  {-------> Get Mask images}			
   		    		  Open(PathU + M512, Mask_II);					
                   if IsNull( Mask_II ) then halt( 'No Reference image was selected' ) ;

{   		    		  Open(PathU + M512L, ML);					
                   if IsNull( ML ) then halt( 'No Reference image was selected' ) ;
   		    		  Open(PathU + M512R, MR);					
                   if IsNull( MR ) then halt( 'No Reference image was selected' ) ;
				   
   		    		  Open(PathU + M512LC, MLC);					
                   if IsNull( MLC ) then halt( 'No Reference image was selected' ) ;
   		    		  Open(PathU + M512RC, MRC);					
                   if IsNull( MRC ) then halt( 'No Reference image was selected' ) ;				 				 
}
//-------->get apparatus mask				 	 
 		    	   	  Open(PathU + AppMask,Fuss);							 
                   if IsNull( Fuss ) then halt( 'No Reference image was selected' ) ;

//--------->check an existing polar image or create one if there is none				   
					 RAD(X0,Y0);		 	   					
					 RR:='x'+Str(Word(Round(10*X0)))+'y'+Str(Word(Round(10*Y0)));						  

 		    		 Open(PathR+ RR+'.tif',F);						  
						  
 {-------> Open or select from desktop Polar coordinate image}
 		   		    RadialLR(F,ML,MR,MT,MB);
								
			        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(MLC);				
	Free(MRC);
	Free(Image_I);

end
