% [Q, date] = readatt(filename) reads the Rosetta attitude data from the ESOC file 'filename
% and returns the quarternions 'Q' and the 'date'.
%
% Initial version: Magnus Billvik, Swedish Institute of Space Physics,
%Uppsala, June 2005

function [Q, date] = readatt(filename, startdate, enddate)

disp('Reading ROSETTA ATTITUDE data...');
disp(strcat(' startdate :',datestr(datenum(startdate'))));
disp(strcat(' enddate   :',datestr(datenum(enddate'))));


% Rosettas attitude, given in Geocentric Equatorial Aries coordinates
fp = fopen(filename,'r');    % open the trajectory file
i=1;
stop=0;
while (stop==0)
    test=fscanf(fp,'%2c',1);
    if isempty(test)
        stop=1;
    elseif test == '20'
        % read the intigers (year, month, day, hour, minute)
        [A]=fscanf(fp,'%2u %*1c %2u %*1c %2u %*1c %2u %*1c %2u %*1c',5);
        date(1,i)=2000+A(1);   % year
        date(2,i)=A(2);        % month
        date(3,i)=A(3);        % day
        date(4,i)=A(4);        % hour
        date(5,i)=A(5);        % minute

        % if the date of the read data is past the interesting range, the loop should stop
        if datenum(date(:,i)') > datenum(enddate')
            stop=1;
        end
        
        % read the float variables (seconds, coordinates & velocity vectors)
        fscanf(fp,'%*1c',1);       % dump the first character
        temp=fscanf(fp,'%111c',1); % all the rest
        temp=strrep(temp,'D','e'); % translate exponential character so Matlab understands
        [date(6,i), Q(1,i), Q(2,i), Q(3,i), Q(4,i)] = strread(temp,'%f %f %f %f %f',5);
        fgetl(fp);
        if datenum(date(:,i)') >= datenum(startdate')
            i=i+1;
        end
    else
        fgetl(fp);
    end
end
fclose(fp);