% This script will attach to an existing AdvCAT object in STK, grab it's
% calculated close approach times, create a time interval list file that
% gets stored in the scenario directory, and then display all the intervals
% on the Timeline View.

% Data written: 12/20/2019
% Author: Kyle Kochel - AGI

% Clear any existing Workspace and Command Window
clear all, clc

% Attach to open existing scenario and advCAT object
uiapp = actxGetRunningServer('STK11.application');
root = uiapp.Personality2;
scenario = root.CurrentScenario;

%%%% CHANGE NAME FOR ADVCAT OBJECT HERE
advCat = root.GetObjectFromPath('AdvCAT/AdvCAT1');
%%%%

% Set Object Model units to Epoch Seconds. This unit is easier to work with
% when making the interval file.
root.UnitPreferences.SetCurrentUnit('DateFormat','EpSec');

% Grab data
eventDP = advCat.DataProviders.Item('Events by Time In').Exec(scenario.StartTime,scenario.StopTime);
timeIn = cell2mat(eventDP.DataSets.GetDataSetByName('Time In').GetValues);
timeOut = cell2mat(eventDP.DataSets.GetDataSetByName('Time Out').GetValues);

%% Write data to a .int file in the scenario directory

% Initialize and open file
scenEpoch = root.ExecuteCommand('GetEpoch *').Item(0);
scenDir = root.ExecuteCommand('GetDirectory / Scenario').Item(0);
fileName = 'AdvCAT_Intervals.int';
filePath = strcat(scenDir,fileName);
fileID = fopen(filePath,'w');

% Write header
fprintf(fileID, ['stk.v.11.0\n\n'...
                'BEGIN IntervalList\n\n'...
                ['ScenarioEpoch ', scenEpoch, '\n\n']...
                'BEGIN Intervals\n']);
            
% Write data
fprintf(fileID, '%f %f\n', [timeIn, timeOut]');

% Write footer
fprintf(fileID, ['END Intervals\n\n'...
                'END IntervalList']);

% Close file
fclose(fileID);

%% Create time component from File in Analysis Workbench and add to Timeline View

% Create time component
scenName = root.ExecuteCommand('ShowNames * Class Scenario').Item(0);
intervalName = fileName(1:end-4); % removes the .int from fileName
scenarioVGT = scenario.Vgt;
timeListFactory = scenarioVGT.EventIntervalLists.Factory;

% If interval list already exists, delete it
if scenarioVGT.EventIntervalLists.Contains(intervalName) == 1
    scenarioVGT.EventIntervalLists.Remove(intervalName)
end

% Create new interval list
Custom = timeListFactory.Create(fileName(1:end-4),'','eCrdnEventIntervalListTypeFromFile');
Custom.Filename = filePath;

% Add to Timeline View
root.ExecuteCommand(['Timeline * TimeComponent Add ContentView "Scenario Availability" "', scenName(3:end), ' ', intervalName, ' Interval List"']);
root.ExecuteCommand('Timeline * Refresh WindowID 1');