function format_isee2_mag_4(flag)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function format_imp_mag_0
%
% purpose: format the ISEE 2 magnetometer files
% into Bx, By, Bz, (GSM)  X, Y, Z (GSM RE)
% at one minute resolution.
% output is ascii file and matlab binary file
% FLAG is format YYYY/MM (year/month)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Given 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
format long e;
k_b           = 1.380622e-23;			% boltzmans const
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');
%daysofmonths  = strvcat('31', '28', '31', '30', '31', '30', '31', '31', '30', '31', '30', '31');
%daysofmonths2 = strvcat('31', '29', '31', '30', '31', '30', '31', '31', '30', '31', '30', '31');
daysofmonths  = [31 28 31 30 31 30 31 31 30 31 30 31];	% day of year, normal year
daysofmonths2 = [31 29 31 30 31 30 31 31 30 31 30 31];	% day of year, leap year.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Load in data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yy=flag;						% Get year and month
outputtxt = [' Working on year: ', num2str(yy)];	% Double check
	disp(outputtxt);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Determine file name and open input file.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yyyy=num2str(yy);					% Convert year/month to string
ssthree = ['isee2_mag_',yyyy,'.dat'];			% Get file name
outputtxt = [' Input file: ', ssthree];			% Check you did it correctly
disp(outputtxt);
[fidmag,message] = fopen(ssthree,'r');
if fidmag == -1						% Error test
	disp(message);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Enter the input mag file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
allmagdata = fscanf(fidmag,['%d %d %d %d %d %d %d %f %f %f %f %f %f %f %f %f %f %f %f %f \n'],[20,inf]);
myrs     = allmagdata(1,:);	% if files has data sort the data
mmons    = allmagdata(2,:);	% Location determined by getting ascii
mdays    = allmagdata(3,:);	% file header
mhrs     = allmagdata(4,:);
mmins    = allmagdata(5,:);
msec     = allmagdata(6,:);
mmsec    = allmagdata(7,:);
bxgsm    = allmagdata(12,:);
bygsm    = allmagdata(13,:);
bzgsm    = allmagdata(14,:);
xgsm     = allmagdata(18,:);
ygsm     = allmagdata(19,:);
zgsm     = allmagdata(20,:);
Mmagtime = datenum(myrs,mmons,mdays,mhrs,mmins,msec);
        
theirflag      = 1.0e+25;
index=find((xgsm>=theirflag) | (ygsm>=theirflag) | (zgsm>=theirflag) | (bxgsm>=theirflag) | (bygsm>=theirflag) | (bzgsm>=theirflag));	%% Change flag value
xgsm(index)     = [];
ygsm(index)     = [];
zgsm(index)     = [];
bxgsm(index)    = [];
bygsm(index)    = [];
bzgsm(index)    = [];
Mmagtime(index) = [];
len = length(Mmagtime);			% Length of the array
clear allmagdata;			% Free RAM
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check what month we have
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
monthdoing = mmons(1);			% Check again: What month are we really doing
outputtxt = [' Working on month: ', num2str(monthdoing)];
	disp(outputtxt);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% determine output file name
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ssoutfour = ['isee2mag',num2str(myrs(1)),num2str(monthdoing,'%2.2d'),'.dat'];	% Contruct file names
ssoutfive = ['isee2mag',num2str(myrs(1)),num2str(monthdoing,'%2.2d'),'.mat'];	% Contruct file names
outputtxt = [' Output plasma file: ', ssoutfour];	
disp(outputtxt);
% open output file
[fidmagout,message] = fopen(ssoutfour,'w');					% open output file
if fidmagout == -1								% error check
	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
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% degap requires a specific input construct input array
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nMmagtime = Mmagtime';					% covert to column
nbxgsm = bxgsm';
nbygsm = bygsm';
nbzgsm = bzgsm';
nxgsm = xgsm';
nygsm = ygsm';
nzgsm = zgsm';
inmagarray = [nMmagtime,nbxgsm,nbygsm,nbzgsm,nxgsm,nygsm,nzgsm];	%construct specific array
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));		% Degap done get new size.
nMmagtime = outmagarray(1:lllmag,1);			% sort out data.
nbxgsm    = outmagarray(1:lllmag,2);			% I understand it better this way.
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);
% Here we are removing spikes in the data. Originally this was
% associated with the "pull" up edges arounded the originally flagged
% regions, but now it just removes spikes.
is = find((nbxgsm > 2000.0)|(nbxgsm<-2000.0));
nvxgsm(is) = eflag;
is = find((nbygsm > 2000.0)|(nbygsm<-2000.0));
nvygsm(is) = eflag;
is = find((nbzgsm > 2000.0)|(nbzgsm<-2000.0));
nvzgsm(is) = eflag;
        
is = find((nxgsm > 300.0)|(nxgsm < -300.0));
nvxgsm(is) = eflag;
is = find((nygsm > 300.0)|(nygsm < -300.0));
nvygsm(is) = eflag;
is = find((nzgsm > 350.0)|(nzgsm < -350.0));
nvzgsm(is) = eflag;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot out to check
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure;						 	% make fig window
plot(Mmagtime,bxgsm,'b',nMmagtime,nbxgsm,'k*');    	% plot original and interpolated
datetick('x','dd/mm/yyyy');                        	% show date in dd/mm/yy form
if (min(bxgsm) == max(bxgsm)),
ylim([0,1]);                				% set limits to avoid plotting flags
else
ylim([min(bxgsm),200]);             			% 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)];	% text out to check
	disp(atxt);
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 
