function ReadAUTO1(path_name,file_name)

% ReadAUTO1.m reads the AUTO1 file generated by STOUR, the patched-conic propagator.
% The information contained in the AUTO1 file is extracted and converted into MATLAB variables.
% (M.Jokic 2003)

%DEFINE GLOBAL VARIABLES FOR PLOTTING ROUTINE
global AUTO1_data path_vector simulation_information_array path_events_string_labels

%-------
%Initialise flag variables and date matrix dimensions
%-------
initialise_flag=1;
initialise_line_count=0;
maneuver_flag=0;
maneuver_path_event=0;
number_lines_in=0;
trajectory_number=0;
event_number=0;
number_AUTO1_file_data_columns=8;
number_AUTO1_data_columns=11;
trajectory_start_line_check=[];
format_problem_flag=0;
trajectory_start_line_check=0;
empty_flag=0;
star_flag=0;


%-------
%track time taken to read the file, today's date 
%-------
tic
disp('/---------------------------------------------------\')
disp(' Reading AUTO1 File...')

AUTO1_read_date=date;

%-------
%Display Status
%-------
disp(' Stage 1: Extracting search information ....')

%-------
%Check for existing AUTO1_data array
%-------
if ~isempty(AUTO1_data)
    clear global AUTO1_data path_vector simulation_information_array path_events_string_labels %clear globals
    global AUTO1_data path_vector simulation_information_array path_events_string_labels %declare globals
end

%-------
%Open file
%-------
fid_in=fopen([path_name file_name],'rt');
if fid_in==-1
    error('Unable to locate AUTO1 file')
end
AUTO1_file_array_cell=textread([path_name file_name],'%[^\n]');

%convert to string array
AUTO1_file_array=char(AUTO1_file_array_cell);
[row_number,column_number]=size(AUTO1_file_array);


%----------------------------------------------------------------------------------------------------------------
%-------
%First Loop - reads and processes the opening lines of AUTO1_file_array 
%-------
loop_end=30;
for number_lines_in=1:loop_end
    text_line = AUTO1_file_array(number_lines_in,:);

    blank_line_check_flag=isequal(max(size(text_line)),max(size(findstr(text_line,' '))));
    %-------
    %Record information about the simulation. (Opening lines of the AUTO1 file.)
    %The trajectory path is recorded as a vector.
    %Other information about the simulation is recorded as strings.
    %-------
    simulation_start_line_check=findstr(text_line,'Starting'); 
    if simulation_start_line_check
        simulation_start_string=text_line(simulation_start_line_check:end);
    end
    path_line_check=findstr('PATH:',text_line);
    if path_line_check&initialise_line_count==0
        initialise_line_count=initialise_line_count+1;
        path_vector=str2num(text_line(path_line_check+5:end));
        if ismember(0,path_vector)
            maneuver_flag=1;
            maneuver_path_event=find(path_vector==0);
        end
        number_events=max(size(path_vector));
    elseif initialise_line_count==1
        initialise_line_count=initialise_line_count+1;
        search_dates_string=text_line;
    elseif initialise_line_count==2
        initialise_line_count=initialise_line_count+1;
        V_infinity_string=text_line;
    elseif initialise_line_count==3
        initialise_line_count=initialise_line_count+1;
        TOF_max_string=text_line;
    elseif initialise_line_count==4
        initialise_line_count=initialise_line_count+1;
        Min_Alt_string=text_line;
        initialise_flag=0;
    end
    
            
    
    % locate start of first trajectory
    if isequal(trajectory_start_line_check,0)
        trajectory_start_line_check=~isempty(findstr(text_line,'LAUNCH DATE ='));
    end
    if isequal(trajectory_start_line_check,1)
        first_trajectory_line=number_lines_in;
        number_lines_in=50;
        trajectory_start_line_check=2;
    end
    
    %check for unexpected formats
    if findstr('WARNING',text_line)|findstr('ERROR',text_line)
        format_problem_flag=1;
    end

end

% try to deal with format problems
if isequal(format_problem_flag,1)
    disp('*********************************************************')
    disp('There are lines with warnings or errors: they will be ignored.')
    disp('Please inspect the AUTO1 file.')
    disp('*********************************************************')
end

disp(' DONE!')

%----------------------------------------------------------------------------------------------------------------
%Record trajectory information 
%The launch dates are stored using MATLAB's DATENUM function (serial days with 1-Jan-0000 =1).
%The last 9 columns of the of the AUTO1 file are stored as numbers with the launch date and launch V_infinity
%in the matrix AUTO1_data.
%AUTO_1 is formatted thus:
%column1 column2 column3 column4 column5 column6 column7 column8 column9 column10 column11
%launch_date launch_Vinf path_event periapse_height theta_or_DV Vinf_or_TotDV period periapse apoapse TOF TotTOF
%-------

%-------
%indices of column ends for data collection
%-------
column_end_locations=[2 11 20 28 36 44 55 64 74]-1;

% launch date line locations
launch_date_lines=strmatch('LAUNCH DATE =',AUTO1_file_array);

% number of trajectories
number_of_trajectories=length(launch_date_lines);

% location of maneuver rows
maneuver_event=find(path_vector==0);

%create waitbar
waitbar_handle=waitbar(0,['Extracting trajectory information ....']);
set(waitbar_handle,'Name',['File Name: ' file_name]);

%notify status
disp(' Stage 2: Extracting trajectory information ....')

for event_number=1:number_events
    text_line = AUTO1_file_array(first_trajectory_line+event_number,:);
    
        if isequal(event_number,1)
            label_locations=find(isletter(text_line)==1);
            grabbed_text=deblank(text_line(label_locations));
            event_labels=grabbed_text;
        else
            label_locations=find(isletter(text_line)==1);
            grabbed_text=deblank(text_line(label_locations));
            event_labels=strvcat(event_labels,grabbed_text);
        end
        %------ Modified by Hippo Yam --------%
        % To avoid "??? Index exceeds matrix dimensions." error
        % final_columns_of_data_string=(AUTO1_file_array(launch_date_lines+event_number,...
        %    label_locations(end)+2:column_number));
        tmp_ind = launch_date_lines+event_number;
        tmp_ind = tmp_ind(find(tmp_ind<=row_number));
        final_columns_of_data_string=(AUTO1_file_array(tmp_ind,label_locations(end)+2:column_number));
        clear tmp_ind;
        %------ Modified by Hippo Yam --------%
        
        %check for missing data entries and replace with zeros (not for destination row)
        final_columns_of_data_numeric=double(final_columns_of_data_string);
        [numeric_row_number,numeric_col_number]=size(final_columns_of_data_numeric);
        [empty_data_row,empty_data_col]=...
            find(ismember(final_columns_of_data_numeric(:,numeric_col_number-column_end_locations),32));
        if ~isempty(empty_data_row)
            %set data point with space to 0
            final_columns_of_data_numeric(empty_data_row,numeric_col_number-column_end_locations)=48; 
            %diplay warning
            if ~isequal(event_number,number_events)&~isequal(empty_data_col,7)&~isequal(empty_flag,1)
                disp('*****************************************************')
                disp('Please note: A blank entry has been found.')
                disp('The blank entry will be set to 0 in the data matrix and may affect plots.')
                disp('All blank entries will be discarded.')
                disp('*****************************************************')
                empty_flag=1;
            end
        end
        % check for asterisk entries instead of data
        [star_data_row,star_data_col]=...
            find(ismember(final_columns_of_data_numeric,42));        
        if ~isempty(star_data_row)
            %replace asterisks with zeros
            final_columns_of_data_numeric(star_data_row,star_data_col)=48; 
            %diplay warning
            if ~isequal(star_flag,1)
                disp('*****************************************************')
                disp('Please note: An asterisk (*) entry has been found.')
                disp('The asterisk will be set to 0 in the data matrix and may affect plots.')
                disp('*****************************************************')
                star_flag=1;
            end
        end        
        %generate final columns of data
        final_columns_of_data=str2num(char(final_columns_of_data_numeric));
        %------ Modified by Hippo Yam --------%
        if (isempty(final_columns_of_data))  % some rows are messed up with non-numeric data
            for kk = 1:(numeric_row_number)
                tmp_data=str2num(char(final_columns_of_data_numeric(kk,:)));
                if (isempty(tmp_data))  % set data to zeros if find non-numeric data
                    final_columns_of_data(kk,:)=zeros(1,length(column_end_locations));
                else
                    final_columns_of_data(kk,:)=tmp_data;
                end
                clear tmp_data;
            end
            for kk = (numeric_row_number+1):number_of_trajectories
                final_columns_of_data(kk,:)=zeros(1,length(column_end_locations));
            end
        end
        %------ Modified by Hippo Yam --------%
        %delete C3 column (not used in plotting)
        final_columns_of_data(:,7)=[];
        

		% ---
		% check for unexpected formats - use code to read each line individually
		% ---
		if isempty(final_columns_of_data)
            disp('*****************************************************')
            disp(['Unexpected format for event number ' num2str(event_number)])
            disp('The line formats could not be resolved!  An empty data matrix has been produced.')
            disp('Please inspect the AUTO1 file.')
            disp('*****************************************************')
        end
		
        matrix_data_lines=[event_number:number_events:number_of_trajectories*number_events];
        % ---
		% assemble data matrix
        % ---
        AUTO1_data(matrix_data_lines,4:number_AUTO1_data_columns)=...
            (final_columns_of_data);
        
        % add event number to data matrix
        AUTO1_data(matrix_data_lines,3)=...
            path_vector(event_number);

        if isequal(event_number,1) %Launch date and Vinf inserted into first row of each trajectory
            %trajectory title text
            text_line = AUTO1_file_array(first_trajectory_line,:);
            
            equal_sign_location=findstr(text_line,'='); 
            at_word_location=findstr(text_line,' AT'); %space needed or other 'AT' instances reported 
            
            % launch dates
            AUTO1_data(matrix_data_lines,1)=...
                datenum(AUTO1_file_array(launch_date_lines,equal_sign_location(1):at_word_location(1)));
            
            % launch Vinf
            AUTO1_data(matrix_data_lines,2)=...
                str2num(AUTO1_file_array(launch_date_lines,equal_sign_location(2)+1:end));
        end
    
	%update waitbar
    waitbar(event_number/number_events,waitbar_handle)
end

%------ Modified by Hippo Yam --------%
% Discard the All-Zero Trajectories
if (empty_flag==1)
	zero_traj_num = [];
    del_rows = [];
	for kk = 1:number_of_trajectories
        for jj = 1:number_events
            if (isempty(find(kk==zero_traj_num)))
                check_zeros = AUTO1_data(kk*number_events-(number_events-jj),4:end);
                if (all(check_zeros==0))
                    zero_traj_num = [zero_traj_num,kk];
                    del_rows = [del_rows,kk*number_events-(number_events-[1:number_events])];
                end
            end
        end
	end
    AUTO1_data(del_rows,:)=[];
end
%------ Modified by Hippo Yam --------%

%----------------------------------------------------------------------------------------------------------------
        
%-------
%path name information in a string
%-------
path_events_string=['Trajectory Path: ' num2str(path_vector)];

%determine labels for trajectory path, if possible.
path_events_string_labels=event_labels;

%-------
%assemble description of trajectory into string array (opening lines of the AUTO1 file)
%-------
simulation_information_array=char(path_events_string,simulation_start_string,search_dates_string,...
    V_infinity_string,TOF_max_string,Min_Alt_string);

%-------
%close file and waitbar
%-------
fclose(fid_in);
close(waitbar_handle);

%-------
%clear working array
%-------
%clear AUTO1_file_array AUTO1_file_array_cell

%-------
%display status
%-------
disp(' DONE!')

%-------
%print trajectory information to the screen
%-------
disp('-----------------------------------------------------')
disp([simulation_information_array])
disp('-----------------------------------------------------')

%-------
%Indicate program conclusion
%-------
disp(' Finished! :)')
elapsed_time=toc;
disp([' Your request took ' num2str(elapsed_time) ' seconds.'])
disp([' There are ' num2str(row_number) ' lines in the original AUTO1 file array.'])
disp([' The new AUTO1_data array has ' num2str(max(size(AUTO1_data))) ' lines.'])
disp('\---------------------------------------------------/')

%------ Modified by Hippo Yam --------%
% Export data to MATLAB workspace
assignin('base','AUTO1_data',AUTO1_data);
%------ Modified by Hippo Yam --------%