{
This program selects all images with a ROI mean in a specified range and renumbers them continually.

Program DO NOT require initialization file


The input parameters requested from operator:

- 'Select IMAGE for size definition' --> enter the file header 
- Browse and select directory where images are stored
- 'Enter the FILE HEADER' --> enter the file header convention <FILE HEADER><_><Index>.tif
- 'Enter the FIRST frame' --> enter the index number for start
- 'Enter the LAST frame' --> enter the index number for end

- 'Enter the NUMBER of LOOPS' 	   --> number of circles of rejection 
- 'Enter the REJECTION CRITERIA'   --> rejection criteria in sigmas 
- 'Enter the REJECTION TRESHOLD'   --> threshold for saturated pixels or 
  		 	 		   			   	   pixels with anomalously high amplitude

All averaged and standard deviation images stored for each loop
Naming convention for output files:
<File header><"_"><av><loop index> 	--> averaged file
<File header><"_"><sd><loop index>	--> standard deviation file

Usually the last averaged file is used for further processing
									   
Created by Vladimir Lobastov 13.01.2002}



const
  	 	  CommonDlgsLib = 'VppCommonDlgs.dll' ;	 	{DLL for common dialog} 
		  InPath='D:\UED4_Data_raw\28082003\';			 	{default path for images}
		  Path2='D:\UED4_Data_raw\Utilities_UED4\';		{default path for initial mask image}
		  Qwst='Do you want to use Patch for saturated pixels?';
		  		  
		  function BrowseFolders( Path:pointer ) : integer ; external CommonDlgsLib ;
		  

var 
	Mask;		//Image variables


{************************************************************************}
{ ***	                      Function FieldedFileName 				  ***}									   
{************************************************************************}


function FieldedFileName(FName, ind);
  begin
    FieldedFileName:= FName+'_'+ReplaceStr(Str(ind:4),' ','0',rs_ReplaceAll);		//Attach the index count (with leading zeros) to the file name 
  end; 
	


Procedure SetRegion(var L,T,R,B;Left,Top,Right,Bottom);								//Equate four variables
begin
   L:=Left;
   T:=Top;
   R:=Right;
   B:=Bottom;
end;
  
  
{************************************************************************}
{ ***	                      Function GetFolder	   				  ***}									   
{************************************************************************}

  
function GetFolder( InitPath ) ;
{ Opens the folder browse dialog and returns a folder path }
{ InitPath may be used to set the initial folder (set to '' otherwise) }
{ Returns a null string if Cancel is pressed }

const
  BufSize = 255 ;
  
var
  FolderName ;

begin
  FolderName := InitPath + StringOfChar( ' ',BufSize - Length( InitPath ) ) ;		//Initialize the variable Folder Name
  if BrowseFolders( FolderName ) <> 0 then 			   		   			  	 		//If a folder is selected
    GetFolder := Trim( FolderName )	  												//Return the folder path
else
    GetFolder := '' ;			  													//Return the Null String
end;  { GetFolder }

{------------------------------------>end of Function --GetFolder--}  	



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

var
   	Img, Image, ROIImage, ROI, MaskedImage;	//Image variables
	xyCoor;									//ROI array
	RLeft,RTop,RRight,RBottom;				//ROI coordinate variables
	mean;									//mean count
	ind, new_ind;							//indices
	i, j;									//string varialbes of indices
	F,N;		  							//first and last number of images to process
	FHead;	  								//file header
	Path, Output;							//path for images
	TRlow, TRup;							//lower and upper intensity threshold
	xSize,ySize;							//full image size
	PLlow, PLup;							//selected radius limit
	X_off,Y_off;							//center coordinates
	r, t;							   				{indices}
  	a,b;											{elliptical major and minor semi-axis}
  	Xt, Yt;	   	   								{Coordinates of the ellipse}
	Ed1, Ed2;									//Editor Handles
  
begin
		F:=1;								//the first frame to process
		N:=100;								//the last frame to process
		FHead:='GS';					    //file header
		TRup:=2000;							//upper threshold for rejection
		TRlow:=40;							//lower threshold for rejection
		new_ind:= 1;						//new index label 
		PLlow:=110;
		PLup:=170;  
       	X_off:=679;
		Y_off:=620;	
    				 
				 		GetNumber('Enter the LOWER Pixel Limit',PLlow);		
				 		GetNumber('Enter the UPPER Pixel Limit',PLup);			
		
				   		  Path:=GetFolder( InPath )+'\';	  	  			  								  //Use the default directory or select a new one
                		  if ( Path = '\' ) then halt( 'Directory not selected' ) ;
				   	 	  WriteInfo(Path);					   
                          GetString('Enter the FILE HEADER',FHead);									  //Display a dialog box and prompt the user to enter a string
						  GetNumber('Enter the FIRST frame',F);						  				  //Display a dialog box and prompt the user to enter a number
						  GetNumber('Enter the LAST frame',N);				   
						  GetNumber('Enter the LOWER Rejection Treshold',TRlow);		
						  GetNumber('Enter the UPPER Rejection Treshold',TRup);			
						 
						 
  

begin

			   i:=FieldedFileName('',1);  										//Convert expression (ind) to a string (with leading zeros)
   			   CreateDir(Path + FHead + '_' + Str(TRlow) + '_' + Str(TRup) + '\'); 	//create subdirectory for output
			   Open(Path+FHead+i+'.tif',Image);										//Read the first sample image from disk  	   
	  		   GetXYSize( Image,xSize,ySize );
			   Mask:= CreateImage( typ_Binary, xSize, ySize ) ;						//create blank mask image   	  				   
 	 		   Mask:=0;															//reset the variables:=0;	
  	 		   r:=PLlow;

  while (r<PLup) do
  	 begin 
			a:=r;
  		   	b:=r;
			t:=0;
			
			while (t<2*3.14159265) do		  									//generate elliptical mask image
    		begin	  	 					
				Xt:= Round(X_off+a*cos(t)-b*sin(t));			// x coordinate of the ellipse
				Yt:= Round(Y_off+a*cos(t)+b*sin(t));			// y coordinate of the ellipse
				Mask[Xt,Yt]:=1;
				t:=t+0.001;
			end;
			r:=r+0.5
	end;
	
	//			Show(Mask);	
		Ed1 := CreateEditor( 'InitialFrames' ) ;
		Ed2 := CreateEditor( 'FinalFrames' ) ;
		WriteLn( Ed1, 'Filename' +', '+ 'Frame#' +', '+ 'FilteredMean') ;			   
		WriteLn( Ed2, 'Filename' +', '+ 'New Frame #' +', '+ 'FilteredMean') ;
		
{---->}	for ind:=F to N do	   
		   begin
			   i:=FieldedFileName('',ind);  										//Convert expression (ind) to a string (with leading zeros)
   			   CreateDir(Path + FHead + '_' + Str(TRlow) + '_' + Str(TRup) + '\'); 	//create subdirectory for output
			   Open(Path+FHead+i+'.tif',Image);										//Read the ith sample image from disk
			   MaskedImage:=Image*Mask;
	//		   Show(MaskedImage);
	//		   SetDisplayZoom(MaskedImage, 25);
    //         FitInWindow(MaskedImage) ;
			   mean:=SumOf(MaskedImage)/SumOf(Mask);								//Calculate the mean intensity count of the ROI image
			   WriteLn( Ed1, FHead+i+'.tif'+', '+ Str(ind)+', '+ Str(mean)) ;						   

			   if (TRlow < mean) AND (mean < TRup)  then							//If the mean count falls within a given range
			   	  begin 
							j:=FieldedFileName('',new_ind);  						//Convert expression (new_ind) to a string (with leading zeros)
							Save(Image, Path + FHead + '_' + Str(TRlow) + '_' + Str(TRup) + '\'+FHead+j+'.tif');				//Save the jth sample image
			  				WriteLn( Ed2, FHead+i+'.tif'+', '+ Str(new_ind)+', '+ Str(mean)) ;	
							new_ind := new_ind + 1 ;   	   	 			  	  		// Increment the new index by one
							Free(j); 												//Free the string j		
				  end;
			   Delete(Image);				  										//Delete the image from the desktop
			   Free(i); 															//Free the string i		   					

			end  ;
			
			Save(Ed2, Path + FHead + '_' + Str(TRlow) + '_' + Str(TRup) + '\FinalFrames.tif');
			Free(Mask);															//Free the variable ROI	
	//		Delete(MaskedImage); 		
		PlaySound( 'C:\Program Files\Digital Optics\V++\Library\Mac.wav' ) ;	 		 //Play a sound
		WriteInfo('Processing completed!!!');							   				 //Display a message in the status bar

end;
end
