% plasisc_spase.m is based on plasisc.m but generates the results requested by
% Spase at La Trobe University and Endowoke at UCLA then saves them to the
% corresponding ascii files
% 
% Author: Phillip A. Webb
% Last updated: September 25 2006
%

clear all
close all

data=[...
 135 2005 01 -101;
 135 2005 04 -149;
 135 2005 06 -174;
 135 2005 07 160;
 135 2005 09 130;
 134 2005 08 152;
 136 2005 07 165;
 170 2003 01 -151;
 170 2003 23 -134];

%Loop through each date of interest to generate the required densities and
%then save the results to ASCII file
for m=1:size(data,1);
 
 lonlsh=data(m,4);
 latmnop=181;
 radnop=100;
 timmat=data(m,3);
 year=data(m,2);
 dno=data(m,1);
 [day,month]=daynum2(dno,year);
 nop=100;

 disp(['Up to ',int2str(dno),'/',int2str(year),' (',int2str(m),' of ',...
  int2str(size(data,1)),')'])
 
 %Determine the maximum allowed altitude.
 re=6371;                                %Earth radi (km)
 lshcp=plasires2(dno,year);
 altmx=1e3*floor((lshcp-1)*re/1e3);

 altmin=800;
 altmax=20200;
 tecalt=0;

 lonlsh=deg2rad(lonlsh);

 [eden,oxden,hyden,heden,latmatm,dismat,hes]=plasisc1(lonlsh,latmnop,...
  altmin,altmax,radnop,timmat,day,month,year,nop);

 svm=ones(size(dismat));
 [lonmat,latmat]=mag2geo3(lonlsh*svm,latmatm);
 
 loni=round(lonlsh);
 if loni<0
  loni=loni+360;
 end 
 lonms=num2str(loni,'%03.0f');
 filse=['GPID_',int2str(year),'_',num2str(dno,'%03.0f'),'_UT',num2str(round(timmat),'%02.0f'),'_lonm',lonms,'_e.txt'];

 fid=fopen(filse,'w');
 tits=['GPID Electron Density (m^-3)  Lonm=',lonms,'  UT=',num2str(round(timmat)),'  Day number=',int2str(dno),'  Year=',int2str(year)];
 fprintf(fid,[tits,'\n\n']);
 fprintf(fid,'No. of long.-lat. points and no. of alt. points\n');
 fprintf(fid,'%3.0f %3.0f\n\n',size(eden));
 fprintf(fid,'Altitudes (km)\n');
 fprintf(fid,'%5.0f %5.0f %5.0f %5.0f %5.0f %5.0f %5.0f %5.0f %5.0f %5.0f\n',dismat(1,:)-re);
 fprintf(fid,'\n');
 fprintf(fid,'Longitudes (deg)\n');
 fprintf(fid,'%4.1f %4.1f %4.1f %4.1f %4.1f %4.1f %4.1f %4.1f %4.1f %4.1f\n',rad2deg(lonmat(:,1)));
 fprintf(fid,'\n\n');
 fprintf(fid,'Lattudes (deg)\n');
 fprintf(fid,'%4.1f %4.1f %4.1f %4.1f %4.1f %4.1f %4.1f %4.1f %4.1f %4.1f\n',rad2deg(latmat(:,1)));
 fprintf(fid,'\n\n');
 fprintf(fid,'Electron densities (m^-3) at each altitude for given longitude-latitude location\n');
 for i=1:size(eden,1)
  fprintf(fid,'Longitude = %4.1f Latitude = %4.1f\n',[rad2deg(lonmat(i)) rad2deg(latmat(i))]);
  fprintf(fid,'%3.2e %3.2e %3.2e %3.2e %3.2e %3.2e %3.2e %3.2e\n',real(eden(i,:)));
  fprintf(fid,'\n\n');
 end
 fclose(fid);
 
end
