% [R, V, date] = readros(filename) reads the Rosetta trajectory file provided by ESOC
% and returns the (xyz) state vectors 'R', the velocity vectors 'V' and the 'date'.
%
% Initial version: Magnus Billvik, Swedish Institute of Space Physics,
%Uppsala, June 2005

function [R, V, date] = readros(filename, startdate, enddate)

disp(strcat('Reading ROSETTA TRAJECORY data from file "',filename , '"...'));


fp = fopen(filename,'r');    % open the trajectory file
i=1;
stop=0;
while (stop==0)
    test=fscanf(fp,'%1c',1);
    if isempty(test)
        stop=1;
    elseif test == '2'      % if the line starts with '2' and is thus a data line...
        % read the intigers (year, month, day, hour, minute)
        [A]=fscanf(fp,'%3u %*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

        % read the float variables (seconds, coordinates & velocity vectors)
        fscanf(fp,'%*1c',1);       % dump the first character
        temp=fscanf(fp,'%162c',1); % all the rest
        temp=strrep(temp,'D','e'); % translate exponential character so Matlab understands
        [date(6,i), R(1,i), R(2,i), R(3,i), V(1,i), V(2,i), V(3,i)] = strread(temp,'%f %f %f %f %f %f %f',7);
        fgetl(fp);

        % 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
        

        % step forward in the file, unless before the start date or if two lines are the same
        if (datenum(date(:,i)') >= datenum(startdate')) & ((i<=1) | max(date(:,i)~=date(:,i-1)))
            i=i+1;        
        end
    else
        fgetl(fp);
    end
end
fclose(fp);


