{
This program generate difference files in respect to reference 
Reference could be a single delay, or averaged over specified number of delays

Before start of this program need to run General_Radial.v

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

<Path\Radial_1D\TREDREF> - combined files of differences at set of delays <difFULL(difLEFT,difRIGHT)><Tail>.tif 
<Path\Radial_1D\TREDREF> - corresponding combined files of 3x standard of average <sdifFULL(sdifLEFT,sdifRIGHT)><Tail>.tif
						
Output files: 1D arrays
<Path\Radial_1D\TRED> - combined files of intensities at set of delays <FULL(LEFT,RIGHT)><Tail>.csv 
					    with added Reference (first coloumn)
<Path\Radial_1D\TRED> - corresponding combined files of 3x standard of average <sigmaFULL(sigmaLEFT,sigmaRIGHT)><Tail>.csv 
					    with added Reference (first coloumn)
<Path\Radial_1D\TRED> - combined files of intensities at set of delays <difFULL(difLEFT,difRIGHT)><Tail>.csv
<Path\Radial_1D\TRED> - corresponding combined files of 3x standard of average <sdifFULL(sdifLEFT,sdifRIGHT)><Tail>.csv

Tail= <First frame to average>to<Last frame to average>

created 12/02/2001 by V.Lobastov Ver. 01.
}
const
	 P ='D:\data\UED4_Data_processed\Utilities_UED4\Delays\*.ini'; 		  //default directory for INI file

var
   	 Sel, Path, Path2;
	 Start;
	 NS,NF, Combo;
	 Sub, Out, OutREF; 	  					 //subdirectories for OUTPUT and OTPUT REFERENCE files 
	 PathOUT,PathOUTREF;					 //full paths for output files 
   	 FSEL, LSEL;							 // first and last coloumns for reference
	 DIF, sDIF;  							 // difference array
	 TL;									 //Tail
	 FL;									 //FileName
{
******************************************************************
********************** 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 HEADER **************************
******************************************************************
This procedure will generate header for output ASCII file
}

procedure HEADER(com, Head, RF);
   var
   	  im;
	  delay;
   begin
			Write(com,'pix'+RF);
   		for im:=NS to NF do
   	   		begin
				   delay:='delay'+Str(im);   
					Write(com, ',', Head + ReadPrivateINIString( Sel, 'FileNames', delay));
	   		end;
					WriteLn(com);
	end;	
//------------------> end of procedure HEADER <------------------------------------
{
******************************************************************
********************** procedure OUTRAT **************************
******************************************************************
This procedure will create output ASCII files in csv format from
combined image contianing the array of 1D radial intensity data
}

procedure OUTRAT(FNAME);

var
   Combo;
   FULLX;
   jx, jjx, SX, NFX;

	begin
		 	Open(PathOUTREF+FNAME+'.tif',FULLX);   //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Redifine Path
			SX:=GetXSize(FULLX);
			NFX:=GetYSize(FULLX);

				Combo:=CreateEditor('Out'+FNAME);        		 		
				HEADER(Combo,'',', REF');
		for jjx:=0 to NFX-1 do
     	 	begin		 
         				 	  Write(Combo, Start+jjx) ;
     				for jx:=0 to Integer(SX-1) do	
	 				 	 begin
         				 	  Write(Combo,',', FULLX[jx,jjx]:20:15) ;
 						 end;
         					  WriteLn(Combo);						 
			end;			 	 
				 Save(Combo, PathOUTREF + FNAME+'.csv');
				 Delete(Combo);
				 Delete(FULLX);
	end;
//----------------------> end of procedure OUTRAT <-----------------
{
******************************************************************
********************** procedure OUTDIF **************************
******************************************************************
This procedure will create output ASCII files in csv format from
combined image contianing an array of 1D radial intensity data
}

procedure OUTDIF(FULLY,FNAMEY);

var
   Combo;
   jy, jjy, SY, NFY;

	begin
			SY:=GetXSize(FULLY);
			NFY:=GetYSize(FULLY);

				Combo:=CreateEditor('Out'+FNAMEY);        		
				HEADER(Combo,'d','');
		for jjy:=0 to NFY-1 do
     	 		begin		 
         				 	  Write(Combo, Start+jjY) ;
     				for jy:=0 to Integer(SY-1) do	
	 				 	 begin
         				 	  Write(Combo,',', FULLY[jy,jjy]:20:15) ;
 						 end;
         					  WriteLn(Combo);						 
				end;			 	 
				 Save(Combo, PathOUTREF + FNAMEY+'.csv');
				 Delete(Combo);
				 Delete(FULLY);
	end;
	
//----------------------> end of procedure OUTDIF <-----------------



{
******************************************************************
********************** procedure DIFF *****************************
******************************************************************
This procedure will generate a reference for difference images
}

procedure DIFF(FNAM, Head, Tail);		 	 //FNAM - file name; Head - header for difference file; Tail - tail (rNtoM)
	var
	   iu, iz, iw;
	   SZ,NFZ;
	   REF,curARR;
	   DX, DY; 		 	   	   			//array size
	   NewRaw;

//		   iz:=0;

	   begin

		   Open(PathOUT+FNAM+'.tif',curARR);				//open arrays  //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Redifine Path
		   		DX:=GetXsize(curARR);
		   		DY:=GetYsize(curARR);
			WriteStatus('DX= '+Str(DX) + '   DY= '+Str(DY));									   
		 //  Halt(FNAM+'.tif');
		   REF:=CreateImage(single,DX,DY);
		   REF:=0;
//------> calculate average over FSEL and LSEL coloumns
			for iz:=FSEL-1 to LSEL-1 do
				begin
					 REF[0,..]:=REF[0,..]+curARR[iz,..];
				  	 iz:=iz+1;
				end;

		 	 	 REF[0,..]:=REF[0,..]/iz;

				 DIF:= CreateArray(single,DX,DY);
			for iu:=0 to DX-1 do
				begin
					 DIF[iu,..]:=curARR[iu,..]-REF[0,..];
				end;

				NewRaw:=CreateArray(single,DX+1,DY);
				NewRaw[1..DX,..]:=curARR[0..DX-1,..];
				NewRaw[0,..]:=REF[0,..];				
		//		Show(DIF);
		//		Halt('');
					Save(DIF,PathOUTREF + Head+Tail+'.tif');				  
  				 	Save(NewRaw, PathOUTREF + FNAM+Tail+'.tif');
					Delete(NewRaw); 
					Free(curARR);
					Free(REF);				 
		end;
//----------------> end of procedure DIFF <-------------------- 

{
******************************************************************
********************** function sDIFF ****************************
******************************************************************
This procedure will generate a standard deviation of reference for difference images
}

procedure sDIFF(FNAM, Head, Tail);
	var
	   iu, iz, iw;
	   SZ,NFZ;
	   sREF, curARR;
	   DX, DY; 		 	   	   			//array size
	   NewRaw;

//		   iz:=0;

	   begin

		   Open(PathOUT+FNAM+'.tif',curARR);
		   		DX:=GetXsize(curARR);
		   		DY:=GetYsize(curARR);
			WriteStatus('DX= '+Str(DX) + '   DY= '+Str(DY));									   
		   sREF:=CreateImage(single,DX,DY);
		   sREF:=0;

//------> calculate a standard deviation of average
			for iz:=FSEL-1 to LSEL-1 do
				begin
					 sREF[0,..]:=sREF[0,..]+sqr(curARR[iz,..]);
				  	 iz:=iz+1;
				end;

		 	 	 sREF[0,..]:=sqrt(sREF[0,..])/iz;

//-----> calculate a standard deviation of difference
				 sDIF:= CreateArray(single,DX,DY);
			for iu:=0 to DX-1 do
				begin
					 sDIF[iu,..]:=sqrt(sqr(curARR[iu,..])+sqr(sREF[0,..]));
				end;

				NewRaw:=CreateArray(single,DX+1,DY);
				NewRaw[1..DX,..]:=curARR[0..DX-1,..];
				NewRaw[0,..]:=sREF[0,..];				
				
					Save(sDIF,PathOUTREF+Head+Tail+'.tif');				  
  				 	Save(NewRaw, PathOUTREF+FNAM+Tail+'.tif');
					Delete(NewRaw); 
					Free(curARR);
					Delete(sREF);				 
		end;
//----------------> end of procedure sDIFF <-------------------- 

{
******************************************************************
********************** procedure REFOUT **************************
******************************************************************
This procedure will generate output ASCII file
}

procedure REFOUT(MD);
var
   HD;
   begin
		   		 HD:='dif'+MD;											   		   //Head
				   	   
//-----------> calculate a new difference 		   
		   		DIFF(MD,HD,TL);
		 		OUTDIF(DIF,HD+TL);
				OUTRAT(MD+TL);
			Free(DIF);					   

		   		MD:='sigma'+MD;											//Mode
		   		HD:='s'+HD;												//Head				   
		
//-----------> calculate a standard deviation for new difference
		   		sDIFF(MD,HD,TL);
		 		OUTDIF(sDIF,HD+TL);
				OUTRAT(MD+TL);
			Free(sDIF);				 		 
	end;	
//------------------> end of procedure REFOUT <------------------------------------
		
{
 ************************************************************************
 ************************************************************************
 ***                                                                  ***
 ***	                      Main program							  ***
 ***																  ***
 ************************************************************************ 
 ************************************************************************
}

	
begin

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

	 			 Path:= ReadPrivateINIString( Sel, 'Paths', 'Path');	 //read a base path
				 	
				 Sub:=ReadPrivateINIString( Sel, 'Paths', 'Sub');
				 if (StrLen(FindFirstFile( Path+Sub+'*.csv', fa_Archive)) = 0) then				 		 
				 CreateDir(Path+Sub);			 		  				 //create subdirectory for output
				 	 			 
				 Out:=ReadPrivateINIString( Sel, 'Paths', 'Out');		 

				 PathOUT:=Path+Sub+Out;
				 if (StrLen(FindFirstFile( PathOUT+'*.csv', fa_Archive)) = 0) then							 
				 CreateDir(PathOUT);		 		  				 //create directory for first output
				 				 
				 OutREF:=ReadPrivateINIString( Sel, 'Paths', 'OutREF');
				 PathOUTREF:=Path+Sub+OutREF;
				 if (StrLen(FindFirstFile( PathOUTREF+'*.csv', fa_Archive)) = 0) then			
				 CreateDir(PathOUTREF);   				 		   	 //create directory for second output
				 				 
				 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

				 FL:=ReadPrivateINIString( Sel, 'FileNames', 'delay'+Str(NF));
			//	 Halt(FL);
				 
//-----------------------> end of Initialization <------------------------------------------

//-----------------------> get the reference definition <-----------------------------------
		   FSEL:=1;
		   LSEL:=1;
		   GetNumber('Select the FIRST frame for REFERENCE',FSEL);
		   GetNumber('Select the LAST frame for REFERENCE',LSEL);		   

		   		 
		   		 TL:=Str(FSEL)+'to'+Str(LSEL);								   //Tail
	   		//	 Halt('FULL'+FL);
				 REFOUT('FULL'+FL);
	   			 //REFOUT('LEFT');
	   			 //REFOUT('RIGHT');				 				 

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