%% Header
filename='data_7_Abril_exp1_m3_parc.txt';
hdr='N,TimeStamp,ID,DataAcceX,DataAcceY,DataAcceZ,DataGyroX,DataGyroY';
dlmwrite(filename,hdr,'');

%% Database

counter_writer=[0;1;1];
for i=2:3
    log_tempo(:,:,i)=database.id.mod2.timestamp-database.id.(['mod' num2str(i)]).timestamp(1); %Zerar
end

tempo_estoiro_tmr1=0.049664; %conversão para seg
log_tempo=log_tempo*tempo_estoiro_tmr1; %seg
m=[];

for i=1:counter-1
    for f=3:3
        if database.id.(['mod' num2str(f)]).N(counter_writer(f,1))==i
            m(end+1,1)=database.id.(['mod' num2str(f)]).N(counter_writer(f,1));
            m(end,2)=log_tempo(1,counter_writer(f,1),f);
            m(end,3)=f;
            m(end,4)=database.id.(['mod' num2str(f)]).acel.data(counter_writer(f,1),1);
            m(end,5)=database.id.(['mod' num2str(f)]).acel.data(counter_writer(f,1),2);
            m(end,6)=database.id.(['mod' num2str(f)]).acel.data(counter_writer(f,1),3);
            m(end,7)=database.id.(['mod' num2str(f)]).gyro.data(counter_writer(f,1),1);
            %Correcção do erro do gyro
            if m(end,7)>=96.5 && m(end,7)<=99.5 || m(end,7)<=-96.5 && m(end,7)>=-99.5
                m(end,7)=database.id.(['mod' num2str(f)]).gyro.data(counter_writer(f,1)-1,1);
%                 m(end,7)=0;
            end
            m(end,8)=database.id.(['mod' num2str(f)]).gyro.data(counter_writer(f,1),2);
            %Correcção do erro do gyro
            if m(end,8)>=96.5 && m(end,8)<=99.5 || m(end,8)<=-96.5 && m(end,8)>=-99.5
                m(end,8)=0;
            end
            
            counter_writer(f,1)=counter_writer(f,1)+1;
        end
    end
end

media=zeros(1,size(m,2));
nn=99;
for i=1:nn+1:size(m,1)
    if max(media)==0
        media(end,1)=m(i,1);
        media(end,2:size(m,2))=mean(m(i:i+nn,2:size(m,2)));
    else
        media(end+1,1)=m(i,1);
        falta=size(m,1)-i;
        if falta<nn
            media(end,2:size(m,2))=mean(m(i:i+falta,2:size(m,2)));
        else
            media(end,2:size(m,2))=mean(m(i:i+nn,2:size(m,2)));
        end
    end
end

dlmwrite(filename,media,'-append','precision', '%.6f','newline', 'pc');