Adjusting tested range based on current exploration date

Hi, I've tried so many things and searched the forum but no joy so far.
I have an exploration which runs From and To a date range. I want to test the last 40 bars before each date in the exploration, but am not able to do this as my code always tests 40 bars before the From date, then 41 bars before the date after the From date, etc. (but I want to test only 40 bars for each date).
Anyhow this is the code to illustrate my problem.

_SECTION_BEGIN("Dateexplore");
SetBarsRequired( sbrAll, sbrAll );
// Just to make it really simple for me I added parameters for the From-To range start and end dates
// So these are set to the same dates as the From-To dates in the analysis window
SDATE = ParamDate( "Start Date", "02/02/2024" , format = 2);
EDATE = ParamDate( "End Date", "16/02/2024" , format = 2);

BI = BarIndex();
FIRSTBAROFEXPLORE=Lookup( BI, SDATE, -1 );
// Make a counter which I hoped would track which bar we are on since the From date
BARSSINCESTARTDATE=BarsSince(Status( "firstbarinrange" ));

// Run through all bars from start of data to end of current exploration date
BARSPROCESSED=0;
PROFIT=0;
for( i = 30; i < BarCount; i++ )
{
	BARSPROCESSED[i]=BARSPROCESSED[i-1];
	PROFIT[i]=PROFIT[i-1];
	
	if(i<FIRSTBAROFEXPLORE[i]-39+0)
//	if(i<FIRSTBAROFEXPLORE[i]-39+BARSSINCESTARTDATE[i])
	{
// Here I just want to ignore all bars before 40 bars prior to the current testing date		
		BARSPROCESSED[i]=0;
	}
	else
	{
// So BARSPROCESSED counts the number of bars traded - I want to trade only the 40 bars prior to the current date 
		BARSPROCESSED[i]=BARSPROCESSED[i]+1;
// Here I put the trading code, for example...
		PROFIT[i]=(Close[i]-Close[i-1])/Close[i-1]*100;
	}
	Filter[i]=1;
}
AddColumn(Close,"Close",format=1.1);
AddColumn(Barcount,"Barcount");
AddColumn(BARSSINCESTARTDATE,"Curent no. of bars since start of range");
AddColumn(BARSPROCESSED,"BARSPROCESSED");
AddColumn(PROFIT,"Total profit");
_SECTION_END();

Here is the screenshot with the code as above (BARSPROCESSED is 40, then 41, then 42, which is what I would expect.

BUT, then I tried to compensate for the current date to have BARSPROCESSED always be 40, I did this by switching the commented-out lines from above as so:

//	if(i<FIRSTBAROFEXPLORE[i]-39+0)
	if(i<FIRSTBAROFEXPLORE[i]-39+BARSSINCESTARTDATE[i])

But I don't get at all the result I expected and am really stuck.
Instead of 40,40,40 which I want to have, I get this:


Would be so greatful if anyone can point me in the right way.