{
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 <Mean>  	--> Mean intensity
3nd column <MSEx3>  --> Standard deviation of mean multyplied by factor of 3
4th column <Npix>	--> Total number of pixels at given radius 

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\04072001\*.ini';	 

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

   AppMask;						   //apparatus mask file for defect, hot spots etc. 
   M512; 						   //default mask 
   
   Size_x, Size_y;				   //image size constants
   F;					 		   //field image variables for full, left, and right halves CCD
   Image_I;                        //Input ED Image
   D_Image, F_Image;               //Equal radii Mask images
   i, j;						   //indices
   Start;						   //start index for calculation
   Masked_F;					   //
   Masked_FF;                      //Masked ED Image

   Mask_II;                        //Image Intensifier Mask Image
   Fuss;						   //image of the apparatus imperfections
   Num_pix;                        //number of pixels at certain radius
   F_pix;                          //left and right halves
   Rad_F;                          //Output Sum of all pixels with equal radius
   FName;                          //Output filename
   Ed1;                            //Output ASCII file
   F_sum;                          //variance image for left and rigth halves
   FS;							   //sums
   F_std;                          //standard deviation for left and rigth halves


   	Rad_FF;						   //Corrected output sum for Radial distribution
	Lambda;						   //wavelength for electrons in Angstrems
	Data;						   //output ASCII array
	SamName;					   //name of the file
	X0,Y0;					   	   //center coordinates
	RR;  						   //name for polar array

{

******************************************************************
********************** 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);
	 		 nName:=ExtractFileName(Name);		
	 		 nDIR:= ExtractFilePath(Name);			//extract the path
			 ix:=0;
	  		 
			 while StrLen(Name) > 0 do

	  		 	   begin
	  	   		   		Name:=ExtractFileName(FindNextFile) ;
		   				nName:=nName+';'+Name;
					 if ix>100 then halt('Too many files in Directory');   
					 	ix:=ix+1;
	 				end; 

	 			 if SelectString( 'Select File',nName , Choice ) >= 0 then
	 			 	begin
			 			 SELECT:=nDIR+Choice;
	 				end	
	 			else
	 				begin 
	 	 	  			  WriteInfo('No Selection made! Restart program! ');	
		 	  			  halt;
	 				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_x, Image_y;                             {X- and Y-coordinate Ramp images}
  Image_R;                                      {Polar-field image (equal radius field)}
  i, j;											{indices}
  x,y;
  Ramp_X, Ramp_Y;                               {Ramp vectors}
  Full;											{image headers}


		  begin
				   Full:='x'+Str(Word(Round(10*X_off)))+'y'+Str(Word(Round(10*Y_off)));
		  	   	if FileExists(PathR+Full+'.tif') then
				begin
				   WriteStatus('File Already Exists  '+ Full);
				end   
				else   
		  		   begin
						  WriteStatus('X_off= '+Str(X_off)+ '  Y_off= '+Str(Y_off));
                          Ramp_X:= Single(MakeLinear(0,Size_x,Size_x));
                          Ramp_Y:= Single(MakeLinear(0,Size_y,Size_y));
                                 Ramp_X:=Single(Ramp_X-X_off);
                                 Ramp_Y:=Single(Ramp_Y-Y_off);
                                 x:=Single(sqr(Ramp_X));
                                 y:=Single(sqr(Ramp_Y));
                          Image_x := CreateImage( Single, Size_x, Size_y ) ;
                          Image_y := CreateImage( Single, Size_x, Size_y );

                          Image_R:= CreateImage(Double, Size_x,Size_y);

 
           for j := 0 to (Size_x-1) do
                  begin
                          PutRow( Image_x, x, j ) ;
                      for i := 0 to (Size_y-1) do
                          PutColumn( Image_y, y, i );
                 end; 
                         Image_R:= Single(sqrt(Image_x+Image_y));
	   			   		 Save(Image_R,PathR+Full+'.tif');
							 
{------> Free memory}
                Free (Image_x);
                Free(Image_y);
                Free(Ramp_X);
                Free(Ramp_Y);
                Free(Image_R);
				Free(X_off);
				Free(Y_off);
			end;
		  end;  
  
{---------> end of procedure RAD}

{
 ************************************************************************
 ***                                                                  ***
 ***	                      Procedure Radial						  ***
 ***																  ***
 ************************************************************************ 
This procedure converts 2D image in 1D intensity curve;
The polar coordinates passed as parameter;

 }  

procedure Radial(R_Field, Flag);


  begin
  
  	   Show(R_field,Flag);

					   Start:=0;				{first pixel number}

						 Data := CreateArray( single, 4, Size_x) ;
						 if IsNull( Data ) then
				Begin
						 WriteError( 'Insufficient memory to create array!' ) ;
						 Halt;
				end
				else

          for i:=Start to Integer((Size_x)/2-1-Start) do
           begin

               F_Image := ( R_field > i)  and (R_field <= i+1) and (Mask_II) and (Fuss);  {binary ring of current radius}

                         F_pix:= Longint(SumOf(F_Image)); 	   	   			   {number of pixels}
                         Masked_FF:=Single(Image_I*F_Image);				   {intensity ring of current radius}
	

                 if (F_pix = 0) then
                    begin
                         Rad_F:=0;
                         F_std:=0;					
                    end
                 else
					begin

                        Rad_F:=Single(SumOf(Masked_FF)/F_pix); 	   			{mean count for current radius}
                        F_sum:=Double(Masked_FF-F_Image*Rad_F);
                        F_sum:=F_sum*F_sum;
						FS:=SumOf(F_sum);					
                        F_std:= Single(sqrt(FS/F_pix));						{STD for a current radius}		

		 			end;	 

{----> calculation of "mean" and STD completed}

																														
                        WriteStatus('pix= ', i, ' Rad_F= ', Rad_F, ' F_std= ', F_std);
						

				Data[0,i]:=Start+i;
				Data[1,i]:=Rad_F;
//------> check for division by zero and calculate standard of average multiplied by factor of 3				
			if ((F_pix-1)= 0) then
			  begin 
				Data[2,i]:=F_std/sqrt(F_pix);
			  end
			  else				
				Data[2,i]:=3*F_std/sqrt(F_pix-1);
				Data[3,i]:=F_pix;		 		
Free(F_sum);
           end;

 						 


{------> Free memory}

	Delete(D_Image);
	Delete(Masked_FF);
	Delete(Masked_F);
	Delete(R_field);
	Delete(F_Image);

{---------> Create Output ASCII file}
    	 Ed1:=CreateEditor(Flag+SamName);
         WriteLn(Ed1,'pix', ',', 'Mean', ',', 'MSEx3', ',', 'Npix') ;
		  
     for j:=0 to Integer(Size_x/2-Start-1) do
	 begin
         Write(Ed1, ShortInt(Data[0,j]), ',', Data[1,j]:20:15, ',', Data[2,j]:20:15, ',', Integer(Data[3,j])) ;
         WriteLn(Ed1);
 	end;	 
		 Save(Ed1, Path +PathC + Flag+ SamName+'.csv');
		 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' ) ;

                            { select one of them }
                   SelectImage( Prompt,Image_I ) ;
                   if IsNull( Image_I ) then halt( 'No image was selected' ) ;
                   Size_x:=GetXSize(Image_I);
                   Size_y:=GetYSize(Image_I);
				   SamName:=GetName(Image_I);
				   
 {--------> Read II_mask.tif image from HDD'
 updated with rejected points mask 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

				 M512:=ReadPrivateINIString( Sel, 'Images', 'Mask');  	  		 //read a mask file name
  {-------> Get Mask  Image}			
   		    		  Open(PathU + M512, Mask_II);					
                   if IsNull( Mask_II ) then halt( 'No Reference image was selected' ) ;
				 
				 
//-------->get apparatus mask				 
				 AppMask:=ReadPrivateINIString( Sel, 'Images', 'AppMask'); 		//apparatus mask	 
 		    	 Open(PathU + AppMask,Fuss);							 

					 RAD(X0,Y0);		 	   					//check an existing polar image or create one if there is none
					 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}
 		   		    Radial(F, RR);
								
			        PlaySound( 'C:\Program Files\Digital Optics\V++\Library\Mac.wav' ) ;								
					WriteInfo('Calculation completed!');

	Free(Mask_II);
	Free(Fuss);			
	Free(Image_I);

end
