%data should come in 2 column format, where 2nd column is counts and 1st is dates
function [dates,counts,missdataind] = fillingapwithperiodicities(dates_old,counts_old,data_name)

out = [];
missdataind = [];
currindex = 1;
dates = [];
counts = [];
%fill in the missing dates and set corresponding counts to zero
for i=1:length(dates_old)-1
    if dategapdetection(dates_old(i),dates_old(i+1))==1
        miss_dates = nogapcalendar(dates_old(i),dates_old(i+1));
        temp = zeros (length(miss_dates),1);
        dates = [dates; dates_old(i); miss_dates];
        counts = [counts; counts_old(i); temp];
        missdataind = [missdataind;currindex currindex+length(miss_dates)+1];
        currindex = currindex + length(miss_dates)+1;
    else
        dates = [dates;dates_old(i)];
        counts = [counts;counts_old(i)];
        currindex = currindex + 1;
    end;
    
end;

period = 7;
for i=1:length(missdataind)
    begint = 2*missdataind(i,1)-missdataind(i,2);
    if begint <= 0
        begint = 1;
    end;
    endint = 2*missdataind(i,2)-missdataind(i,1);
    if endint > length(dates)
        endint = length(dates);
    end;
    %trend
    x1 = (begint+missdataind(i,1))/2;
    x2 = (endint+missdataind(i,2))/2;
    y1 = mean(counts(begint:missdataind(i,1)));
    y2 = mean(counts(missdataind(i,2):endint));
    a = (y2-y1)/(x2-x1);
    gap_length = missdataind(i,2)-missdataind(i,1);
    index_miss = (1:gap_length+1)';
   % trend = (counts(missdataind(i,2)) - counts(missdataind(i,1)))/(gap_length+1);
    counts(missdataind(i,1):missdataind(i,2)) = ones(size(index_miss))*counts(missdataind(i,1))+index_miss*a;
    %add periodicity
    interval = begint:endint;
    [newdata,avglist]=seasrem(counts(interval),period);
    avglist = avglist - ones(size(avglist))*mean(avglist);
    for j=missdataind(i,1):missdataind(i,2)
        counts(j) = counts(j)+avglist(mod(j-begint,period)+1); 
    end;
end;  
[rows cols] = size(missdataind);
missindex = [];
for i=1:rows;
    missindex = [missindex missdataind(i,1):missdataind(i,2)];
end;
figure;
plot(counts);
title(data_name);
hold on;
plot(missindex,counts(missindex),'--','Color','white');
grid on;
set(gca,'XTick',1:30:length(counts));
set(gca,'XTickLabel',num2str(dates(1:30:length(dates))));
legend('data','filled-in values');
hold off;