%% QDC calculation
% for actual day 
%%
function [qday, ActDay]= q_day(arr);
% ------------------------------------------------------------ 
% The function calculates actual Qiuet Day Curve (QDC) for 
% INPUT array (arr) of data. 
% arr - is 1-minutes values for 30 days = 43200 elements
% OUTPUT
% qday - array of 1400 elements (1-day) QDC values 
% ActDay - actual day in 30 days array 
% ------------------------------------------------------------

step=2;
arr_s=smooth(arr,120);
arr_g=gradient(arr);
len= size(arr,1);
q(1:len)=NaN;
a=len/1440;
day=[];
s=0;
p=0; 
divq=0;
act(1:50000)=NaN;
ac=1;
flag = true;

while min(p)<120
 divq=divq + step;
 clear q  p; 
 q(1:len)=NaN;

 
for i=31:len-31
   if max(abs(arr(i-30:i+30)-arr_s(i-30:i+30)))<divq & max(abs(arr_g(i-30:i+30)))<divq
     q(i)=arr(i);  
    act(ac)=i;
     ac=ac+1;
   end; 
end    
q=q';  

for i=1:a
    n=i*1440;
     s=size(day,2)+1; 
    day(1:1440,s)= q(n-1439:n);

end;    

for i=1:1320
    p(i) = length(find(not(isnan( day(i:i+120,:)  ))));
end;    

actual = step/divq;

 if actual<=0.05 
  flag = false;  
  break;
 end; %IF    

end; %WHILE


if flag
    qqq=[day ;day; day];
    qqq_s  = smooth(nanmean(qqq'),240,'moving');%240
    qqq_s = smooth(qqq_s,240,'rlowess');
    qday = qqq_s(1440:2880-1);
    %!!!!! Actual Day !!!!!!!
    ActDay=round(nanmedian(act)/1440)

else
  qday(1:1440) = NaN;
  ActDay = NaN;
  actual = 0;
end;    
