function [OutputData] = SaveAVDSData(Action,InputData,Entity)
%SaveAVDSData - used to manage data for output to an AVDS playback file
%
%  Function Prototype:
%		[OutputData] = SaveAVDSData(Action,InputData,Entity)
%
%  Inputs:
%    Action - defines the mode of operation. Valid values are:
%      'Clear' - removes any stored data, entities, and latitude/longitude data.
%      'AddEntity' - adds a new entity to the stored data. (Optional, defaults 
%        to one entity)
%      'AddLatLong' - adds latitude and longitude starting position to the file.
%        (Optional, defaults to not using latitude and longitude. In this case 
%        AVDS uses selected airport as the starting position)
%      'Store' - saves one or more rows of data for the given entity. New rows 
%        of data must have the same number of columns as existing data for any 
%        given entity.
%      'WriteEntity' - write the stored data to a file with the given file name, 
%        see below.
%    InputData - the use of this argument changes based on the value of 'Action':
%        'Clear' - InputData is not used.
%        'AddEntity' - InputData is not used.
%        'AddLatLong' - InputData contains a two element row/column vector. The 
%          first element contains the starting latitude (degrees decimal ranging
%          -90.0 to 90.0) and the second element contains the starting longitude
%          (degrees decimal ranging from -180.0 to 180.0).
%        'Store' - InputData contains a row vector or matrix of data for AVDS 
%          to playback. 
%        'WriteEntity' - InputData contains the name of the file for the data.
%    Entity - the ID number of the entity to perform the 'Action' on. (Defaults to Entity=1)
%
%  Outputs:
%    OutputData - the value of this changes based on the value of 'Action
%        'Clear' - [].
%        'AddEntity' - The ID number of the entity just added.
%        'AddLatLong' - [].
%        'Store' - []. 
%        'WriteEntity' - The name of the file saved.
%
%  Usage:
%    SaveAVDSData is used in conjunction with WritePlaybackInit to produce the files
%      necessary for AVDS to load and configure dynamics data for playback. 
%      SaveAVDSData is used to save the data files and WritePlaybackInit is used to 
%      save the playback configuration file. AVDS is capable of playing back data for
%      multiple vehicles (entities), so SaveAVDSData contains the functionality 
%      necessary to save multiple playback data files.
%      
%      For one entity the user calls SaveAVDSData in the following sequence:
%        SaveAVDSData('Clear');  %this clears any old data and resets number of entities  
%        SaveAVDSData('AddLatLong',[37.793625,-122.32856]);  %this is optional
%              .
%              .
%              .
%        SaveAVDSData('Store',DataRow);  %this is repeated as many times as required.  
%              .
%              .
%              .
%        SaveAVDSData('WriteEntity','MyFile.save.dat');  %writes the latitude/longitude 
%                                                        %and stored data to the file  
%
%      For more that one entity the user calls SaveAVDSData in the following sequence:
%        SaveAVDSData('Clear');  %this clears any old data and resets number of entities
%        for (i = 1:NumberEntities),
%          SaveAVDSData('AddEntity');
%        end;
%        for (i = 1:NumberEntities),
%          SaveAVDSData('AddLatLong',[37.793625,-122.32856]);  %this is optional
%        end;
%              .
%              .
%              .
%        for (iEntities = 1:NumberEntities),    %this is repeated as many times as required.
%          SaveAVDSData('Store',DataRow{iEntities},iEntities);  
%        end;
%              .
%              .
%              .
%        for (iEntities = 1:NumberEntities),    
%          SaveAVDSData('WriteEntity',EntityFileNames(iEntities),iEntities);  
%                                        %writes the latitude/longitude 
%                                        %and stored data to the file  
%        end;
%
%    AVDS Default Data Format:
%      AVDS playback data files are ASCII (text) files where the data is in columns.
%      The columns can be in any order and the only requirement on the content/number
%       of columns is that there must be at least one column that contain time information, 
%      elapsed or delta, in seconds. The default column order for AVDS is:
%
%      TimeSeconds, NorthPositionFeet, EastPositionFeet, DownPositionFeet,
%      XRotationPsiDeg, YRotationThetaDeg, ZRotationPsiDeg,
%      craftmask, crafttype, EngineLevel,
%      AlphaDeg, BetaDeg, G, VFtSec, MachNumber,
%      DeltaSurface01Rad, DeltaSurface02Rad, DeltaSurface03Rad, DeltaSurface04Rad, 
%      DeltaSurface05Rad, DeltaSurface06Rad, DeltaSurface07Rad, DeltaSurface08Rad, 
%      DeltaSurface09Rad, DeltaSurface10Rad, DeltaSurface11Rad, DeltaSurface12Rad, 
%      DeltaSurface13Rad, DeltaSurface15Rad, DeltaSurface15Rad,
%      WeaponsSelect, WeaponsLaunch, Explode
%
%      If the column order is to be changed, the WritePlaybackInit function should be 
%      modified to reflect the changes. Alternatively, AVDS's Playback Configuration
%      dialog window can be used to create a new playback initialization file.
%

%   Steve Rasmussen, December 2000
%   Copyright (c) 2000 by RasSimTech Ltd
%   $Revision: 1.0 $  $Date: 2000/12/16 00:00:00 $

persistent DataStorageCells;
persistent Latitude;
persistent Longitude;

OutputData = [];

if (nargin == 0),
   Message = sprintf('  ** SaveAVDSData:: Not enough arguments supplied during a call to SaveAVDSData **\n    *** For more information type ''help SaveAVDSData'' ***');
   error(Message)
end;

switch (Action),
   
case 'Clear',
   DataStorageCells = [];
   Latitude = [];
   Longitude = [];
   
case 'AddEntity',
   DataStorageCells = [DataStorageCells;cell(1)];  %add a new storage cell to the vector
   [iRows,iCols] = size(DataStorageCells);
   OutputData = iRows;  %new entity number is the last cell in the vector
   
case 'AddLatLong',
   if ((exist('InputData','var'))&(isa(InputData,'double'))),
      [iRows,iCols] = size(InputData);
      if ((iRows ~= iCols)&((iRows==2)|(iCols==2))),
   		Latitude = InputData(1);
      	Longitude = InputData(2);
      else;	%if ((iRows ~= iCols)&((iRows==2)|(iCols==2))),
			error('  ** SaveAVDSData:: The ''InputData'' argument must include Latitude and Longitude values in a two element row or column vector, during a ''AddLatLong'' operation. **');
      end;	%if ((iRows ~= iCols)&((iRows==2)|(iCols==2))),
   else;	%if ((exist('InputData','var')==0)|(isa(InputData,'double'))),
		error('  ** SaveAVDSData:: The ''InputData'' argument must include Latitude and Longitude values in a two element row or column vector, during a ''AddLatLong'' operation. **');
   end;	%if ((exist('InputData','var')==0)|(isa(InputData,'double'))),
   
case 'Store',
   if (~exist('Entity','var')),
   	Entity = 1;	%entity number defaults to 1
	end;
   [iNumberEntities] = size(DataStorageCells,1);
   if ((Entity == 0)|(Entity > iNumberEntities)),
   	if (Entity == 1),
			SaveAVDSData('AddEntity');
		else,	%if (Entity == 1),
			Message = sprintf('  ** SaveAVDSData:: ''Entity'' #%d has not been intialized with ''AddEntity''. **',Entity);
			error(Message);
		end;	%if (Entity == 1),
	end;	%if ((Entity ~= 0)&(Entity <= iNumberEtities)),
   [iRowsStorage,iColsStorage] = size(DataStorageCells{Entity});
   [iRowsData,iColsData] = size(InputData);
   if ((exist('InputData','var'))&(isa(InputData,'double'))),
   	if ((iColsData ~= iColsStorage)&(iColsStorage~=0)),
			error('  ** SaveAVDSData:: The number of columns of ''InputData'' must be equal to the number of columns in previously stored data. **');
   	end;	%if (iRowsData == 1),
   else,	%if ((exist('InputData','var'))&(isa(InputData,'double'))),
		error('  ** SaveAVDSData:: ''InputData'' must be set equal to an array/row vector of data during a ''Store'' operation. **');
   end;	%if ((exist('InputData','var'))&(isa(InputData,'double'))),
   DataStorageCells{Entity} = [DataStorageCells{Entity};InputData];
   
case 'WriteEntity',
   if (~exist('Entity','var')),
   	Entity = 1;	%entity number defaults to 1
	end;
   if ((~exist('InputData','var'))|(~isa(InputData,'char'))),
   	InputData = sprintf('AVDSSaved_%d.save.dat',Entity);	%default filename
   end;
   [iNumberEntities] = size(DataStorageCells,1);
   if ((Entity == 0)|(Entity > iNumberEntities)),
      if (iNumberEntities),
         Message = sprintf('  ** SaveAVDSData:: ''Entity'' #%d has not been intialized with ''AddEntity''. **',Entity);
      else,
         Message = sprintf('  ** SaveAVDSData:: There is no Stored data. **');
      end;
		error(Message);
   end;
   if((~isempty(Latitude))&(~isempty(Longitude))),
   	SaveMatrix = DataStorageCells{Entity};
   	save ('TempData.txt', 'SaveMatrix','-ascii','-double');
      fid = fopen('TempLat.txt','a');
      frewind(fid);
		fprintf(fid,'%% LAT %g\n',Latitude);
		fprintf(fid,'%% LONG %g\n\n',Longitude);
      fclose(fid);
      fid = fopen(InputData,'w');
      fclose(fid);
      CommandText = sprintf('!copy /A TempLat.txt+TempData.txt /A %s /Y  > nul',InputData);
      eval(CommandText);
      eval('!erase TempData.txt  > nul');
      eval('!erase TempLat.txt  > nul')
   else,	%if((~isempty(Latitude)&(~isempty(Longitude))),
   	SaveMatrix = DataStorageCells{Entity};
   	save (InputData, 'SaveMatrix','-ascii','-double');
   end;	%if((~isempty(Latitude)&(~isempty(Longitude))),
  	OutputData = InputData;
otherwise,
   Message = sprintf('  ** SaveAVDSData:: Given ''Action'' argument was not implemented, given ''Action'' argument = %s **',Action);
	error(Message);
end;	%switch (Action),
