
{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=D:\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\Utilities\Delays\*.ini'; 		 	  //default directory for INI file
//  	 P = 'D:\DATA\04072001\*.ini';	 
	 Prompt0 = 'Select the MASK image';		
  	 Prompt1 = 'Select the molecular SAMPLE image' ;
  	 Prompt2 = 'Select the atomic REFERENCE image' ;
  	 Prompt3 = 'Select the BACKGROUND image for SAMPLE' ;
  	 Prompt4 = 'Select the BACKGROUND image for REFERENCE' ;

  
  
var

  Im_Sam, Im_S;                             {Input molecular Sample ED Image}
  Im_Ref, Im_R;								{Input atomic Reference ED Image}
  Im_Back;									{Input Background ED Image}
  Im_Bias;									{Input CCD's Bias Image}
  II_Mask;									{Mask image}
  Im_Zer;									{"0" for the image intensifier area}
  Im_One;									{"1" for the image intensifier area}
  Im_RAT;									{(Sam-Back)/(Ref-Back) image}
  Im_sigma;									{standard deviation image}
  Size_x, Size_y;                           {Size of image in X and Y}
  N_pix;  									{Total number of pixels}
  Mean_count;								{Mean value over non-zero pixels}
  STD;										{standard deviation over non-zero pixels}
  Im_reject, Im_keep;						{images for rejection "bad" pixels}
  ind;										{index}
  SamName;									{name of the sample image}
  NewMask;
  Im_BackSam, Im_BackRef;

//--------------->
		Path, PathU, PathIMG, InIMG, PathImgOUT;
  		Sel;		
		Crit, Loops;
		M512, M512L, M512R, M512LC, M512RC;	//mask images names	  
		RefIm;		 					   	//Reference image name
		BackSam,BackRef;					//Background for sample, and refernence
		NS,NF, im, curIm;
		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);
	 		 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 <-----------------------------------			



{************************************************************************}
{ ***	                      NormC(RATimg, NMimg, NewName, RM, LM)	  ***}									   
{************************************************************************}
//This  procedure will normalize calculated ratio image  
//NormC normalization of LEFT and RIGHT halves separately using selected masks
procedure NormC(RATimg, NMimg, NewName, RM, LM);
var 
	pix, MeanImg;
	NormImg;
	NImg;
	LImg,RImg;
	RMeanImg,LMeanImg;
	cNMimg;	

begin				  
						RImg:= RATimg*RM;						 
	 					pix:= Single(SumOf(RM*cNMimg));					{count all nonzero pixels}
                        RMeanImg:=Single(SumOf(RImg*cNMimg)/pix);		{mean count for selected Image}

						LImg:= RATimg*LM;						 
	 					pix:= Single(SumOf(LM*cNMimg));					{count all nonzero pixels}
                        LMeanImg:=Single(SumOf(LImg*cNMimg)/pix); 	   	{mean count for selected Image}
						
						NormImg:=CreateImage( typ_Single, Size_x, Size_y ) ;
						NormImg:=(LImg/LMeanImg)+(RImg/RMeanImg);
						Show(NormImg, 'N'+NewName);
				//		Save(NormImg, Path2 +'N'+NewName+'.tif');						
Free(NMimg);
Free(RATimg);						
Free(RMeanImg);
Free(LMeanImg);
Free(NormImg);
Free(cNMimg);			
										
end;

{------------------------------------> end of procedure ---NormC---}

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

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

begin
	 					pix:= Single(SumOf(NMimg));						{count all nonzero pixels}
                        NormImg:=RATimg/Single(SumOf(RATimg)/pix); 	   	{mean count for selected Image}
						Show(NormImg, 'N'+NewName);
						Save(NormImg, PathImgOUT +'N'+NewName+'.tif');						
	Free(NMimg);
	Free(RATimg);						
	Delete(NormImg);
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
				 NF:=Val(ReadPrivateINIString( Sel, 'TotalDelays', 'Last'));	   //last frame to process
				 

				 				 
				 Crit:=Val(ReadPrivateINIString( Sel, 'ImgReject', 'Crit'));	   //read a rejection criteria
				 Loops:=Val(ReadPrivateINIString( Sel, 'ImgReject', 'Loops'));	   //read a number of loops

				 PathIMG:=ReadPrivateINIString( Sel, 'Paths', 'OutIMG');  		   //read a path for output Ratio images and masks
			  if (StrLen(FindFirstFile( Path+InIMG+'*.tif', fa_Archive)) = 0) then
				 CreateDir(Path+InIMG);			 		  				  	   	   //create subdirectory for output
				 PathImgOUT:=Path+PathIMG;


				 M512:=ReadPrivateINIString( Sel, 'Images', 'Mask');  	  		   //read a mask file name
	WriteInfo(M512);			 
//				 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

				 RefIm:=ReadPrivateINIString( Sel, 'Images', 'RefIm');    	 	 //read a reference image name
				 BackSam:=ReadPrivateINIString( Sel, 'Images', 'BackSam');   	 //read a backround sample image name
				 BackRef:=ReadPrivateINIString( Sel, 'Images', 'BackRef');   	 //read a backround reference image name				 

				 
				 if (StrLen(FindFirstFile( PathImgOUT+'*.tif', fa_Archive)) = 0) then  
				 CreateDir(PathImgOUT);		 		  				 	  	  	 //create directory for output Ratio images and masks
				 
//-----------------------> end of Initialization <------------------------------------------

    { check for images }
//                   if GetNumImages = 0 then halt( 'This program requires a desktop image' ) ;

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

  {-------> Get Input Reference Image}			
   		    		  Open(Path + RefIm, Im_Ref);
                   if IsNull( Im_Ref ) then halt( 'No Reference image was selected' ) ;

  {-------> Get Backgound Image for Sample}			

                   	  Open(Path + BackSam, Im_BackSam);
                   if IsNull( Im_BackSam ) then halt( 'No SAMPLE Background image was selected' ) ;

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

  {-------> Get Input Sample Image}			
//                   SelectImage( Prompt1 ,Im_Sam ) ;
//                   if IsNull( Im_Sam ) then halt( 'No Sample image was selected' ) ;
//				   SamName:=GetName(Im_Sam);

				   
                   Size_x:=GetXSize(II_Mask);
                   Size_y:=GetYSize(II_Mask);					  
				   

			   for im:=NS to NF do
   	   		   	   begin       
				   	   delay:='delay'+Str(im);   
	   		   		   FL:=ReadPrivateINIString( Sel, 'FileNames', delay);		//read a current image name		 	   		
					   Open(Path + FL +'.tif',Im_Sam);  			   			//open current sample image

                   if IsNull( Im_Sam ) then halt( 'No Sample image was selected' ) ;
					   SamName:=FL;

				   		Im_S := CreateImage( typ_Single, Size_x, Size_y ) ;
	    				Im_R := CreateImage( typ_Single, Size_x, Size_y ) ;
						Im_sigma:= CreateImage( typ_Single, Size_x, Size_y ) ;		

						Im_S:=(Im_Sam-Im_BackSam);		   						
						Im_R:=(Im_Ref-Im_BackRef);
				   		

				   				Im_Zer:= (Im_R=0);		 {found the '0' for reference image}
				   				Im_One:= not(Im_Zer);     {make '1' where counts}
				   				NewMask:=II_Mask*Im_One;  {correction of mask image}
								Im_R:=Im_R+Im_Zer;                   {remove '0' from reference image}

								Im_RAT:=(Im_S/Im_R)*NewMask;         {divide and remove artifacts}


	    			for ind:=1 to Loops do
						begin

							 N_pix:=SumOf(NewMask);
							 Mean_count:=SumOf(Im_RAT)/N_pix;			

							 Im_sigma:= Im_RAT-Single(Mean_count*NewMask);
							 Im_sigma:=Im_sigma*Im_sigma;		
							 STD:=sqrt(SumOf(Im_sigma)/(N_pix-1));


							 Im_reject:= (Im_RAT < Mean_count-Crit*STD) or (Im_RAT > Mean_count+Crit*STD);
							 Im_keep:=not Im_reject;
							 Im_RAT:= Im_RAT*Im_keep;
							 NewMask:=NewMask*Im_keep;
					 	 	 Show(NewMask, 'NMR'+SamName);
						 	 Save(NewMask, PathImgOUT+'NMR'+SamName+'.tif');
						 
					end;

			   		   NormF(Im_RAT, NewMask, 'R'+SamName);	  					//normalization of FULL image		
		end;			
		
		

			        PlaySound( 'C:\Program Files\Digital Optics\V++\Library\Mac.wav' ) ;								
{------> Free Memory}
    Delete(NewMask);
	Delete(Im_Sam);
	Free(Im_Ref);
	Free(Im_Back);
	Delete(Im_RAT);
	Delete(Im_reject);	 
	Delete(Im_sigma);
	Delete(Im_S);
	Delete(Im_R);
	Free(II_Mask);
	Delete(Im_Zer);
	Delete(Im_One);
end
