function format_isee3_mag_7883(flag)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function format_imp_mag_0
% author: j.m. weygand
% purpose: format the isee 3 magnetometer files
% into matlab time format and Bx, By, Bz, (GSM)
% X, Y, Z (GSM RE)
% output files are ascii and matlab binary
% FLAG is YYYYMM format (year/month)
% NOTE: ONLY GOOD FOR 1978 TO 1983
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Givens
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
format long e;				% use the long format
k_b           = 1.380622e-23;     	% boltzmann constant
m_p           = 1.672e-27;          	% mass of a proton
eflag         = 1.0e+34;		% error flag 
months        = strvcat('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'); % month string
daysofmonths  = [31 28 31 30 31 30 31 31 30 31 30 31];		% number of days per months, normal year
daysofmonths2 = [31 29 31 30 31 30 31 31 30 31 30 31];		% number of days per months, leap year
doyn          = [1,32,60,91,121,152,182,213,244,274,305,335];	% day of year, first of month, normal year
doyl          = [1,32,61,92,122,153,183,214,245,275,306,336];	% day of year, first of month, leap year
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Load in data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yy=flag;							% Get year and month
outputtxt = [' Working on year: ', num2str(yy)]; 		% check inputs
	disp(outputtxt);
if (double(int32(flag/100)) >= 1984 ), 				% check again the inputs (ISEE3 mag has two versions)
	disp('Your using the wrong program! This is only good for year < 1983!');
	keyboard;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Determine file name and open input file.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yyyy=num2str(yy);      						% num to string to get input files
ssthree = [yyyy,'_isee3_mag03_1min.asc'];   			% make input file
outputtxt = [' Input file: ', ssthree]; 			% check input 
	disp(outputtxt);
[fidmag,message] = fopen(ssthree,'r');   			% open the file and check errors
if fidmag == -1							% error check
	disp(message);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Enter the input plasma file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
allmagdata = fscanf(fidmag,['%d %d %d %d %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f\n'],[21,inf]);
len = length(allmagdata(1,:));               			% Determine array length
% sort data
myrs  = allmagdata(1,:);					% Location determined by getting ascii
doy   = allmagdata(2,:);					% file header
mhrs  = allmagdata(3,:);
mmins = allmagdata(4,:);
bxsc  = allmagdata(5,:);
bysc  = allmagdata(6,:);
bzsc  = allmagdata(7,:);
xgse  = allmagdata(19,:);
ygse  = allmagdata(20,:);
zgse  = allmagdata(21,:);

mdays    = zeros(1,len);     					% saves time 
mons     = zeros(1,len);     					% saves time
lyear = myrs(1);
disp('Getting Days and Months from DOY!'); % bob wants YYYY MM DD, but we have yyyy doy
        
Mmagtime = datenum(myrs,1,doy,mhrs,mmins,0); % get matlab time
% Their error flag determined from their header files
index=find((xgse>=9999.9) | (ygse>=9999.9) | (zgse>=9999.9) | (bxsc>=999.9) | (bysc>=999.9) | (bzsc>=999.9));	%% Change flag value
%% eliminate the flags for these. Normally there are very few missing.
%% Removing the flag ones helps prevent corruption of the data on the
%% edges of the flag zones. A 1e34 flag "pulls up" the data on the ends
%% of the flag zones and makes that data worthless. By removing a few
%% flags now it helps to save 3 to 4 data points on each side of the
%% flag. The edges are "pulled up" by the degap program. This program
%% removes bad times, but not bad data.
if (length(index) == len)
	xgse(index) = eflag;					% put in my error flag for theirs
	ygse(index) = eflag;					% if the WHOLE files is error flags
	zgse(index) = eflag;
	bxsc(index) = eflag;
	bysc(index) = eflag;
	bzsc(index) = eflag;
else    
	xgse(index) = [];					% if they only have a few error flags then
	ygse(index) = [];					% delete those lines
	zgse(index) = [];
	bxsc(index) = [];
	bysc(index) = [];
	bzsc(index) = [];
	Mmagtime(index) = [];
end
len = length(Mmagtime);
[dummy,mmons,dummy,dummy,dummy,dummy] = datevec(Mmagtime(1));
clear allmagdata;  						% clear some RAM
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check what month we have
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
monthdoing = mmons(1);  					% check, check and recheck
outputtxt = [' Working on month: ', num2str(monthdoing)];	% look at the output
	disp(outputtxt);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% determine output file name
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ssoutfour = ['isee3mag',num2str(myrs(1)),num2str(monthdoing,'%2.2d'),'.dat'];	% Contruct file names
ssoutfive = ['isee3mag',num2str(myrs(1)),num2str(monthdoing,'%2.2d'),'.mat'];	% Contruct file names
outputtxt = [' Output plasma file: ', ssoutfour];				% look at output
	disp(outputtxt);

[fidmagout,message] = fopen(ssoutfour,'w');					% open output file
if fidmagout == -1    								% check if they really open.
	disp(message);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Get start and end of the month.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('Linearly interpolating to value on the minute (Resampling). ');
startyyymmddhhmmss = [num2str(1,'%2.2d'),'-',months(monthdoing,:),'-',num2str(myrs(1)),' ','00:00:00.00'];
startend(1) = datenum(startyyymmddhhmmss);				% Determine start time of month and make string
lyear = myrs(1);							% Check if we have a leap year.
if ( (lyear==1976) | (lyear==1980) | (lyear==1984) | (lyear==1988) | (lyear==1992) | (lyear==1996) | (lyear==2000)  ),
	endyyymmddhhmmss = [num2str(daysofmonths2(monthdoing)),'-',months(monthdoing,:),'-',num2str(myrs(1)),' ','23:59:00.00'];
else
	endyyymmddhhmmss = [num2str(daysofmonths(monthdoing)),'-',months(monthdoing,:),'-',num2str(myrs(1)),' ','23:59:00.00'];
end
startend(2) = datenum(endyyymmddhhmmss);				% Determine end time of month and make string
                                                        		% degap requires a specifiv input
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% convert Mag and position from GSE to GSM
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('Convert Magnetic SC and position GSE to magnetic field and position GSM');
%RF = [1 2 3; 4 5 6; 7 8 9];
bxgsm = zeros(1,len); 					% these statements save computation time.
bygsm = zeros(1,len);
bzgsm = zeros(1,len);
xgsm = zeros(1,len);
ygsm = zeros(1,len);
zgsm = zeros(1,len);
for jj=1:1:len   					% convert SC about = GSE to GSM coords
	[RF,RI] = gse2gsm(Mmagtime(jj));		% builds the matrix
	vector = [bxsc(jj),bysc(jj),bzsc(jj)];		% make a vector
	vecout = mat9vec3(RF,vector);		
	bxgsm(jj) = vecout(1);				% sort our vector components
	bygsm(jj) = vecout(2);
	bzgsm(jj) = vecout(3);
	vectortwo = [xgse(jj),ygse(jj),zgse(jj)];	% make a vector
	vectwoout = mat9vec3(RF,vectortwo);
	xgsm(jj) = vectwoout(1);			% sort our vector components
	ygsm(jj) = vectwoout(2);
	zgsm(jj) = vectwoout(3);
end
disp('Convertion from GSE to GSM done');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% degap requires a specific input construct input array
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nMmagtime = Mmagtime';   		% Bobs interpolation program needs a specific format
nbxgsm    = bxgsm';
nbygsm    = bygsm';
nbzgsm    = bzgsm';
nxgsm     = xgsm';
nygsm     = ygsm';
nzgsm     = zgsm';
inmagarray = [nMmagtime,nbxgsm,nbygsm,nbzgsm,nxgsm,nygsm,nzgsm];
clear bygsm bzgsm xgsm ygsm zgsm;  			% free RAM

outmagarray=degapint(inmagarray,eflag,datenum('00:01:00'),startend,datenum('00:10:00'));
[maxmagval,lllmag] = max(outmagarray(:,1));
nMmagtime = outmagarray(1:lllmag,1);     % put in to something more readable for this stupid programmer
nbxgsm 	  = outmagarray(1:lllmag,2);
nbygsm    = outmagarray(1:lllmag,3);
nbzgsm    = outmagarray(1:lllmag,4);
nxgsm     = outmagarray(1:lllmag,5);
nygsm     = outmagarray(1:lllmag,6);
nzgsm     = outmagarray(1:lllmag,7);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot out to check
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure;							% make fig window
plot(Mmagtime,bxgsm,'b',nMmagtime,nbxgsm,'k*');   	% plot original and interpolated
datetick('x','dd/mm/yy');                       	% show date in dd/mm/yy form
if (min(bxgsm) == max(bxgsm)),
	ylim([0,1]);                   			% set limits to avoid plotting flags
else
	ylim([-500.0,500.0]);          			% set limits to avoid plotting flags
end
clear Mtime vxgsm bxgsm;				% free memory
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read out to an ascii file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ctout = 1;				% set flag
disp('Fixing rounding error in Time.');
newyear = zeros(1,lllmag);
newmon  = zeros(1,lllmag);
newday  = zeros(1,lllmag);
newhr   = zeros(1,lllmag);
newmin  = zeros(1,lllmag);
newsec  = zeros(1,lllmag);
while( (ctout) <= lllmag),
	% fix the rounding error problem.
	[newyear(ctout),newmonth(ctout),newday(ctout),newhr(ctout),newmin(ctout),newsec(ctout)]=datevec(outmagarray(ctout,1));
	if (   abs(newsec(ctout)-60.0) < 1.0), 		% here due to rounding error.
		newsec(ctout) = 0.000;			
	end						% end of while loop for (ctout) <= lll
	if (ctout > 1),
		if (newmin(ctout) == newmin(ctout-1)),
			newmin(ctout) = newmin(ctout) + 1;
			if (newmin(ctout) == 60),
				newmin(ctout) = 0;
			end
		end
	end
	ctout = ctout + 1;				% incriment the counter
	atxt = ['Plasma 1: length: ',num2str(lllmag),' ctout: ',num2str(ctout)];	
	disp(atxt);					% text out to check
end
disp('Making output array');
    
% contruct output array
outputmagarray = [newday',newmonth',newyear',newhr',newmin',newsec',nbxgsm,nbygsm,nbzgsm,nxgsm,nygsm,nzgsm]; 
							% export output array to file.
ctout = 1;                              		% set flag
while( (ctout) <= lllmag),
	count = fprintf(fidmagout,'%2.2d %2.2d %4.4d %2.2d %2.2d %06.3f %12.6e %12.6e %12.6e %12.6e %12.6e %12.6e\n',outputmagarray(ctout,:));
	atxt = ['Plasm and Maga 2: length: ',num2str(lllmag),' ctout: ',num2str(ctout)];
	ctout = ctout + 1;              		% incriment the counter
end
disp('Closing output file.');
status = fclose (fidmagout);	
    
% read out to matlab binary file.
disp('Making matlab binary file.');
save(ssoutfive,'nMmagtime','nbxgsm','nbygsm','nbzgsm','nxgsm','nygsm','nzgsm');
    
% recall we clear the input file varies above
% clear Mtime bxgsm bygsm bzgsm xgsm ygsm zgsm;
% now clear the interpolated data so we can start the next month.
% Recall we will never get the next month.
clear newyear newday newmonth newhr newmin newsec nvxgsm nvygsm nvzgsm;

status = fclose (fidmag);          			% close input files
disp('Program complete');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% end of for loop for years (Yeah, that was a pipe dream).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%end 
