  {
This program produce radial distribution of the ED image
from Ratio images 
Before start of this program need to run General_RATany4.v

Output files: 2D arrays (coloumn corresponding to delay, and row to pixel number)
<Path\Radial_1D\TRED> - combined files of intensities at set of delays <FULL(LEFT,RIGHT)>.tif
<Path\Radial_1D\TRED> - corresponding combined files of 3x standard of average 
					    <sigmaFULL(sigmaLEFT,sigmaRIGHT)>.tif

Output files: 1D arrays
<Path\Radial_1D\RAW\> - files <F(L,R)><delay>.csv
<Path\Radial_1D\TRED> - combined files of intensities at set of delays <FULL(LEFT,RIGHT)>.csv
<Path\Radial_1D\TRED> - corresponding combined files of 3x standard of average 
					    <sigmaFULL(sigmaLEFT,sigmaRIGHT)>.csv

created 12/02/2001 by V.Lobastov Ver. 01.
}

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
	 	 
//------------> Global variables
var
	Data;
    F, L, R, T, B;					 			//field image variables for full, left, and right halves CCD}
    M, M_L, M_R, M_T, M_B;						// MASKS   
    Size_x, Size_y; 		  	 	  		 	//image size	 
    SamName;									//name of the file header   
    Fuss;										//image of the apparatus imperfections
	X0,Y0, RR;											
	im, imm; 	 	  	  	   	   		
	cur, curIm, curSDIm, curMask;				//index, current Image, current standard deviation image
	FULL, LEFT, RIGHT;							//combined RAW 1D data
	sigmaFULL, sigmaLEFT, sigmaRIGHT;			//standard deviations for RAW 1D data
	difFULL, difLEFT, difRIGHT;		 			//combined difference 
	sdifFULL, sdifLEFT, sdifRIGHT;	 			//standard deviations for difference

//   Mask_II;                                     //Image Intensifier Mask Image}
//   Image_I;                                     //Input ED Image}

	 NS,NF, Combo;
	 Sel, delay, FL;
	 Sub, Out, Raw, InIMG;
	 Path, PathR, PathU, PathOUT;
	 Start, Loops, Crit;
	 AppMask;
	 Ed1;	 	   		 		 				 //Editor Variable
	 PLlow, PLup;									//Upper and Lower Pixel Limits
	 F_pix; 										//number of pixels at certain radius
     Rad_F;										//Output Sum of all pixels with equal radius}
	 
	 
{
******************************************************************
********************** 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 HEADER **************************
******************************************************************
This procedure will generate header for output ASCII file
}

procedure HEADER(com, Head, RF);
   var
   	  im;
	  delay;
   begin
			Write(com,'pix'+RF);			   		 	 		  				//Write an expression to the output window without a terminating carriage-return
   		for im:=NS to NF do														//step through the number of delays
   	   		begin
				   delay:='delay'+Str(im);   									//define the delay number
					Write(com, ',', Head + ReadPrivateINIString( Sel, 'FileNames', delay));	 //write the delay name into the line
	   		end;
					WriteLn(com);		   						 	  			//write a carriage return
	end;	
//------------------> end of procedure HEADER <------------------------------------


{
*************************************************************************************************
********************** procedure Radial(Image_I,Mask_II,R_Field, Flag) **************************
*************************************************************************************************
{This program produce 1D radial distribution from ED image with rejection of bad points}

procedure Radial(Image_I, Image_I_SD, Mask_II,R_Field, Flag);				 //Radial(curIm, curMask, F, 'F', cur});

var



   F_Image;                  					//Equal radii Mask images}
   Masked_F;
   Masked_FF, Masked_FF_SD;            			//Masked ED Image and standard deviation image}
   Num_pix;                                     //number of pixels at certain radius
   F_sum;                                       //variance image for left and rigth halves}
   FS;										 	//sums}
   F_std, F_stderr, F_stderr1;					//standard deviation for left and rigth halves}
 
   
  begin
  
			
					 
		 
		    F_Image := ( R_field > Start+PLlow)  and (R_field <= Start+PLup+1) and (Mask_II) and (Fuss);  //binary ring mask of current radius
		 				   
		                 F_pix:= Longint(SumOf(F_Image)); 	   	   			    //get the number of pixels in the ring mask image
                         Masked_FF:=Single(Image_I*F_Image);				    //mask the input diffraction image
						 Masked_FF_SD:=Single(Image_I_SD*F_Image);				//mask the input standard deviation image
												 
                if (F_pix = 0) then												//if there are no pixels in the ring
                    begin
                         Rad_F:=0;												//mean count for current radius = 0
                         F_std:=0;												//STD for a current radius = 0
                    end
                 else
					
					begin
                         Rad_F:=Single(SumOf(Masked_FF))/F_pix;						//mean count for current radius 
                         F_std:=Single(SumOf(Masked_FF_SD))/F_pix;					//STD for a current radius 
                    end;
                 
//----> calculation of weighted mean completed
	
//------> Free memory

		  	   		 															//Free memory
	Delete(Masked_FF);
	Delete(Masked_F);
	Delete(R_field);
	Delete(F_Image);

  
end;
//---------------> End of procedure Radial <------------------------------

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

begin

//-----------------------> Initialization parameters<---------------------------------------

	 		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				 	

//-------->get apparatus mask				 
				 AppMask:=ReadPrivateINIString( Sel, 'Images', 'AppMask'); 		//read the apparatus mask file name 
 		    	 Open(PathU + AppMask,Fuss);							 		//read the apparatus mask image from disk
				 
				 WriteInfo('Xcenter= '+Str(X0)+ '  Ycenter= '+Str(Y0));			//Display a dialog box containing an information message.
	
                 Size_x:=GetXSize(Fuss);		   								//read the x dimension of the image
                 Size_y:=GetYSize(Fuss);										//read the y dimension of the image

				 Start:=Val(ReadPrivateINIString( Sel, 'PixelStart', 'Start'));	//first pixel number 
				 
				 
				 NS:=Val(ReadPrivateINIString( Sel, 'TotalDelays', 'First'));	//first frame to process
				 NF:=Val(ReadPrivateINIString( Sel, 'TotalDelays', 'Last'));	//last frame to process
				 
				 
				 PLlow:=150;
				 PLup:=250;         	
				 GetNumber('Enter the LOWER Pixel Limit',PLlow);		
				 GetNumber('Enter the UPPER Pixel Limit',PLup);			
			
//-----------------------> end of Initialization <------------------------------------------

//-----> polar image selection						  
						  RR:='X'+Str(Word(Round(10*X0)))+'y'+Str(Word(Round(10*Y0)));		//polar image file name				  
 		    		 	  Open(PathR + RR+'.tif',F);										//open the polar image, if it exists					  
						  WriteStatus('Selected polar image is ' + RR);						//Write Status 



				cur:=0;
   	   		 	Ed1:=CreateEditor('Selected Radial Range Mean Intensity');					//Create an window for text output
	   			WriteLn(Ed1,'Filename', ',', 'Mean Intensity', ',', 'Npix') ;  				//Write the title row

//------> Browse trough files in directory defined in Path+InIMG
   for im:=NS to NF do
   	   begin   
			   delay:='delay'+Str(im);   
	   		   FL:=ReadPrivateINIString( Sel, 'FileNames', delay);
		 	   		
					Open(Path +  FL ,curIm); 			  				//open the image
		 			Open(Path +  FL ,curSDIm); 	  						//open the image
					SamName:=FL;	  		  	 									//assign the filename to SamName

//-------------> create combined <1D radial in colomns>x<sequential number of processed data>
 
							Radial(curIm, curSDIm, Fuss, F, 'F');			  	//This function produces the mean of the selected radial range
				   			WriteLn(Ed1, FL +'.tif', ',', Rad_F:20:15, ',', F_pix) ;  //Write the results to the output editor
				   			
				   			
					cur:=cur+1;					 								//increase the counter by one (move to another delay)												
			end;
WriteLn(Ed1);

//-------------> create ASCII output from combined images 			

		 				

			        PlaySound( 'C:\Program Files\Digital Optics\V++\autorun.wav' ) ;				
					WriteInfo('Calculation completed!');

//------> free memory					
			Free(Fuss);						
			Free(FULL);
			Free(sigmaFULL);
end
