
{This program will create Normalized Ratio images and corresponding Mask images 
from four input averaged images:

Processed images specified in initialization file located in directory specified with constant "P" 

------------->> lines from <XXX>.ini
::
[Images]
RefIm=Xe.tif			   -> reference image 
BackSam=BnL.tif			   -> background for sample 
BackRef=BnL.tif			   -> backgrounf for reference
::
::
<<--------------

!!!!!!!!! NOTE !!!!!!!!!!!!!!
Sample image name is specified in a different place with 
constant delay<XX>, and File name WITHOUT extension

------------->> lines from <XXX>.ini
::
[FileNames]
delay1=CO2
delay2=GS
::
::
<<--------------



Sample, Reference,Background for sample and Background for Reference
and then will normalize according to selection
NRAT=(Sample-BackSample)/(Reference-BackReference)

Output files: Normalized ratio and corresponding mask images would be sent in directory 
specified as <Path\Images_RAT> 

---------->>
::
[Paths]
::

::
Path=E:\DATA\11012002\Mean\
::
::
OutIMG=Images_RAT\
::

<<-------------------------
Final path will look like <Path>+<OutImg>=  D:\DATA\11012002\Mean\Images_RAT\

Output file names followin convention
<"NR"><delayXX>.tif	   <-- normalized ratio image
<"NMR"><delayXX>.tif   <-- mask image for normalized ratio image

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


const
	  P ='D:\data\UED4_Data_processed\Utilities_UED4\Delays\*.ini'; 		 	  //default directory for INI file
  
var

  Im_Sam, SD_Im_Sam, Im_S, SD_Im_S;         {Input molecular Sample ED Image and the corresponding standard deviation images}
  Im_Ref, SD_Im_Ref, Im_R, SD_Im_R;			{Input atomic Reference ED Image and the corresponding standard deviation images}
  II_Mask;									{Mask image}
  Im_Zer_S, Im_Zer_R;									{"0" for the image intensifier area}
  Im_One_S, Im_One_R;									{"1" for the image intensifier area}
  Im_RAT, SD_Im_RAT, SD_Im_Rat_Rel;			{(Sam-Back)/(Ref-Back) image and its corresponding standard deviation image}
  Size_x, Size_y;                           {Size of image in X and Y}
  N_pix;  									{Total number of pixels}
  ind;										{index}
  Weight;
  SamName;									{name of the sample image}
  NewMask;									{mask image}
  Im_BackSam1, SD_Im_BackSam1;				{Sample Background Image 1 and the corresponding standard deviation image}
  Im_BackSam2, SD_Im_BackSam2;				{Sample Background Image 2 and the corresponding standard deviation image}
  Im_BackSam3, SD_Im_BackSam3;				{Sample Background Image 2 and the corresponding standard deviation image}
  Im_DetectorOffset, SD_Im_DetectorOffset;	{Detector Offset Image and the corresponding standard deviation image}
  Im_BackRef, SD_Im_BackRef;				{Reference Background Image and the corresponding standard deviation image}

//--------------->
		Path, PathU, PathIMG, InIMG, PathImgOUT;
  		Sel;		
		M512; 				  		 		//mask images names	  
		RefIm;		 					   	//Reference image name
		BackSam1, BackSam2, BackSam3,DetectorOffset, BackRef;	//Background for sample, and reference
		NS,NF, im; 
		delay, FL;


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


  
{************************************************************************}
{ ***	                      NormF(RATimg, NMimg, NewName)		  ***}									   
{************************************************************************}
//This  procedure will normalize calculated ratio image  

procedure NormF(RATimg, SD_RATImg, NMimg, NewName);
var 
	pix, MeanImg;
	NormImg, SD_NormImg;

begin
	 					pix:= Single(SumOf(NMimg));						  		//count all nonzero pixels in the Mask image
                        
						NormImg:=RATimg/1; 	   									//dont normalize the image
						SD_NormImg:=SD_RATimg/1; 	   							//dont normalize the standard deviation image 
										
						//NormImg:=RATimg/Single(SumOf(RATimg)/pix); 	   			//normalize the image
						//SD_NormImg:=SD_RATimg/Single(SumOf(RATimg)/pix); 	   			//normalize the standard deviation image 
						
						//Show(NormImg, 'NR_'+NewName);								//Show the normalized image on the desktop
						//Show(NormImg, 'NR_');								//Show the normalized image on the desktop
						//Show(SD_NormImg, 'NR_SE_'+NewName);		
						Save(NormImg, PathImgOUT +'NR_'+NewName+'.tif');			//Save the normalized image to the output directory
						Save(SD_NormImg, PathImgOUT +'NR_SE_'+NewName+'.tif');	//Save the normalized standard deviation image to the output directory
						Save(NMimg, PathImgOUT +'NewMask_'+NewName+'.tif');	//Save the normalized standard deviation image to the output directory
	Free(NMimg);					  			 								//Release the memory used by a variable
	Free(RATimg);																//Release the memory used by a variable
	Free(SD_RATimg);															//Release the memory used by a variable
end;


{------------------------------------> end of procedure ---NormF---}

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

//-----------------------> Initialization parameters<---------------------------------------
	 		Sel:=SELECT;												  			// selector for initialization file

	 			 Path:= ReadPrivateINIString( Sel, 'Paths', 'Path');	  			//read a base path	 	
	 			 PathU:= ReadPrivateINIString( Sel, 'Paths', 'PathU');	  			//read a path	for utilities Masks		
				 InIMG:=ReadPrivateINIString( Sel, 'Paths', 'OutIMG');	  			//subdirectory for Output Ratio Images
				 
				 NS:=Val(ReadPrivateINIString( Sel, 'TotalDelays', 'First'));	   //first frame to process, Convert a string expression into a numerical value
				 NF:=Val(ReadPrivateINIString( Sel, 'TotalDelays', 'Last'));	   //last frame to process, Convert a string expression into a numerical value
				 				 
				 PathIMG:=ReadPrivateINIString( Sel, 'Paths', 'OutIMG');  		   //read a path for output Ratio images and masks
			 	 		 if (StrLen(FindFirstFile( Path+InIMG+'*.tif', fa_Archive)) = 0) then //If there is no directory holding a tif-file, then..
				 CreateDir(Path+InIMG);			 		  				  	   	   //create subdirectory for output
				 PathImgOUT:=Path+PathIMG;

				 M512:=ReadPrivateINIString( Sel, 'Images', 'Mask');  	  		   //read a mask file name
				 WriteInfo(M512);			 	  								   //Display a dialog box containing an information message

				 RefIm:=ReadPrivateINIString( Sel, 'Images', 'RefIm');    	 	   //read a reference image name
				 BackSam1:=ReadPrivateINIString( Sel, 'Images', 'BackSam1');   	   //read a backround sample image name 1
				 BackSam2:=ReadPrivateINIString( Sel, 'Images', 'BackSam2');   	   //read a backround sample image name 2
				 BackSam3:=ReadPrivateINIString( Sel, 'Images', 'BackSam3');   	   //read a backround sample image name 3
				 DetectorOffset:=ReadPrivateINIString( Sel, 'Images', 'DetectorOffset');   //read a detector offset image name
				 BackRef:=ReadPrivateINIString( Sel, 'Images', 'BackRef');   	   //read a backround reference image name				 

							 
							 
//-----------------------> end of Initialization <------------------------------------------

 
  {-------> Get Mask  Image}			
   		    		
					  Open(PathU + M512, II_Mask);					
                   if IsNull( II_Mask ) then halt( 'No mask image was selected' ) ;

  		   
				   
  {-------> Get Backgound Image 1 for Sample}	
                   	  Open(Path + BackSam1+'_av2.tif', Im_BackSam1);
                   if IsNull( Im_BackSam1 ) then halt( 'No SAMPLE Background image 1 was selected' ) ;
  {-------> Get SD image of the Backgound Image 1 for Sample}	
                   	  Open(Path + BackSam1+'_se2.tif', SD_Im_BackSam1);
                   if IsNull( SD_Im_BackSam1 ) then halt( 'No SAMPLE Background standard deviation image 1 was selected' ) ;

  {-------> Get Backgound Image 2 for Sample}	
                   	  Open(Path + BackSam2+'_av2.tif', Im_BackSam2);
                   if IsNull( Im_BackSam2 ) then halt( 'No SAMPLE Background image 2 was selected' ) ;
  {-------> Get SD image of the Backgound Image 2 for Sample}	
                   	  Open(Path + BackSam2+'_se2.tif', SD_Im_BackSam2);
                   if IsNull( SD_Im_BackSam2 ) then halt( 'No SAMPLE Background standard deviation image 2 was selected' ) ;

  {-------> Get Backgound Image 3 for Sample}	
                   	  Open(Path + BackSam3+'_av2.tif', Im_BackSam3);
                   if IsNull( Im_BackSam3 ) then halt( 'No SAMPLE Background image 3 was selected' ) ;
  {-------> Get SD image of the Backgound Image 3 for Sample}	
                   	  Open(Path + BackSam3+'_se2.tif', SD_Im_BackSam3);
                   if IsNull( SD_Im_BackSam3 ) then halt( 'No SAMPLE Background standard deviation image 3 was selected' ) ;

				   
  {-------> Get DetectorOffset}	
                   	  Open(Path + DetectorOffset+'_av2.tif', Im_DetectorOffset);
                   if IsNull( Im_DetectorOffset ) then halt( 'No DetectorOffset image ' ) ;
  {-------> Get SD image of the DetectorOffset Image}	
                   	  Open(Path + DetectorOffset+'_se2.tif', SD_Im_DetectorOffset);
                   if IsNull( SD_Im_DetectorOffset ) then halt( 'No DetectorOffset standard deviation image 2 was selected' ) ;

				   
  {-------> Get Input Reference Image}			
   		    		  Open(Path + RefIm+'_av2.tif', Im_Ref);
                   if IsNull( Im_Ref ) then halt( 'No Reference image was selected' ) ;
  {-------> Get the SD Image of the Input Reference Image}			
   		    		  Open(Path + RefIm+'_se2.tif', SD_Im_Ref);
                   if IsNull( SD_Im_Ref ) then halt( 'No Reference standard deviation image was selected' ) ;

  {-------> Get Backgound Image for reference}
                   	  Open(Path + BackRef+'_av2.tif', Im_BackRef);  			
                   if IsNull( Im_BackRef ) then halt( 'No REFERENCE Background image was selected' ) ;
  {-------> Get Backgound Image for reference}
                   	  Open(Path + BackRef+'_se2.tif', SD_Im_BackRef);  			
                   if IsNull( SD_Im_BackRef ) then halt( 'No REFERENCE Background standard deviation image was selected' ) ;

				  Weight:=1;						//Weight Factor  
				  GetNumber('Enter the coefficient of BackSam1',Weight);		//Display a dialog box and prompt the user to enter a number
			 
				   
  {-------> Get Input Sample Image}			
				   
                   Size_x:=GetXSize(II_Mask); 				   		 	 		//Return the x-dimension of the size definition image
                   Size_y:=GetYSize(II_Mask);					  				//Return the y-dimension of the size definition image
				   

			   for im:=NS to NF do												//for all imgages to process, do
   	   		   	   begin       
				   	   delay:='delay'+Str(im);   								//index the delay with consecutive numbers
	   		   		   FL:=ReadPrivateINIString( Sel, 'FileNames', delay);		//read the imth image name		 	   		
					  // Halt(FL);
					   Open(Path + FL +'_av2'+'.tif',Im_Sam);  			   		//open the imth sample image
					                      if IsNull( Im_Sam ) then halt( 'No Sample image was selected' ) ;  
					   Open(Path + FL +'_se2'+'.tif',SD_Im_Sam);  			   	//open the imth sample standard deviation image
					                      if IsNull( SD_Im_Sam ) then halt( 'No Sample standard deviation image was selected' ) ; 
					   
					   SamName:=FL;

				   		Im_S := CreateImage( typ_Single, Size_x, Size_y ) ;		//create a type singel image of the same size as the mask image
	    				Im_R := CreateImage( typ_Single, Size_x, Size_y ) ;		//create a type singel image of the same size as the mask image
						SD_Im_S:= CreateImage( typ_Single, Size_x, Size_y ) ;  //create a type singel image of the same size as the mask image
						SD_Im_R:= CreateImage( typ_Single, Size_x, Size_y ) ;  //create a type singel image of the same size as the mask image
						
						Im_S:=(Im_Sam-Weight*Im_BackSam1-(1-Weight)*Im_BackSam2+Im_DetectorOffset);	//Initialize the variable Im_S
						SD_Im_S:=Sqrt(SD_Im_Sam*SD_Im_Sam+Weight*Weight*SD_Im_BackSam1*SD_Im_BackSam1+(1-Weight)*(1-Weight)*SD_Im_BackSam2*SD_Im_BackSam2+SD_Im_BackSam3*SD_Im_BackSam3+SD_Im_DetectorOffset*SD_Im_DetectorOffset);	//Initialize the variable SD_Im_S
						Im_R:=(Im_Ref-Im_BackRef);								//Initialize the variable Im_R
				   		SD_Im_R:=Sqrt(SD_Im_Ref*SD_Im_Ref+SD_Im_BackRef*SD_Im_BackRef);	//Initialize the variable SD_Im_R

				   				Im_Zer_S:= (Im_S=0);							//Identify the zero pixels in the sample image and make a binary image
								Im_Zer_R:= (Im_R=0);							//Identify the zero pixels in the reference image and make a binary image
				   				Im_One_S:= not(Im_Zer_S);     					//Invert the binary image
				   				Im_One_R:= not(Im_Zer_R);     					//Invert the binary image
								NewMask:=II_Mask*Im_One_S*Im_One_R;				//create a corrected mask image for the sample 
								Im_R:=Im_R+Im_Zer_R;                   	 	  	//add 1 to each zero pixel in the reference image, so the division is possible
								
								Im_RAT:=(Im_S/Im_R)*NewMask;					//divide and remove all aftificially altered pixels
								
								Im_S:=Im_S+Im_Zer_S;                   	 	  	//add 1 to each zero pixel in the sample image, so the division is possible
								
								SD_Im_Rat_Rel:=NewMask*Sqrt(((SD_Im_S*SD_Im_S)/(Im_S*Im_S))+((SD_Im_R*SD_Im_R)/(Im_R*Im_R)));  // calculate the relative standard deviation of the quotient
								SD_Im_Rat:=Im_RAT*SD_Im_Rat_Rel;				// calculate the absolute standard deviation of the quotient
								//Show(SD_Im_Rat_Rel, 'SD_Im_Rat_Rel_'+SamName);
				
			   		   NormF(Im_RAT, SD_Im_RAT, NewMask, SamName);	  			//this procedure normalizes/scales the ratio image and the standard deviation image	
		end;			
		
		

			        PlaySound( 'C:\Program Files\Digital Optics\V++\autorun.wav' ) ;								
{------> Free Memory}
    Delete(NewMask);
	Delete(Im_Sam);
	Free(Im_Ref);
	Delete(Im_RAT);
	Delete(SD_Im_S);
	Delete(SD_Im_R);
	Delete(Im_S);
	Delete(Im_R);
	Free(II_Mask);
	Delete(Im_Zer_S);
	Delete(Im_Zer_R);
	Delete(Im_One_S);
	Delete(Im_One_R);
end
