function format_imp8_mag_4(flag)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Function format_imp_mag_0
% Author: J. Weygand
% Purpose: format the imp 8 magnetometer files
% into matlab time format and Bx, By, Bz, (GSM)
% X, Y, Z (GSM RE)
% NOTE:  this is for file type number 2
% FLAG = yyyymm (year month) format
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Given 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
format long e;						% use the long format
k_b 	= 1.380622e-23;					% Boltzman's constant
m_p 	= 1.672e-27;					% mass of a proton
eflag 	= 1e+34;					% error flag
months        = strvcat('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
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.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Load in data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yy=flag;						% get year/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 = ['IMP8_mag_',yyyy,'.dat'];			% Get the file name
outputtxt = [' Input file: ', ssthree];			% Double check file name.
disp(outputtxt);
[fidmag,message] = fopen(ssthree,'r');			% Open file.
if fidmag == -1						% Error message check
	disp(message);
	keyboard;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Enter the input mag file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
allmagdata = fscanf(fidmag,['%d %d %d %d %d %d %f %f %f %f %f %f %f %f %f %f %f %f\n'],[18,inf]);
				% get all the data at once. This saves time.
myrs  = allmagdata(1,:);	% Location determined by getting ascii headers
doy   = allmagdata(2,:);
mmons = allmagdata(3,:);
mdays = allmagdata(4,:);
mhrs  = allmagdata(5,:);
mmins = allmagdata(6,:);
msec  = allmagdata(7,:);
	
xgsm  = allmagdata(8,:);
ygsm  = allmagdata(11,:);
zgsm  = allmagdata(12,:);
bxgsm = allmagdata(14,:);
bygsm = allmagdata(17,:);
bzgsm = allmagdata(18,:);
Mmagtime = datenum(myrs,mmons,mdays,mhrs,mmins,msec);				% Matlab likes matlab time
clear allmagdata;								% free some 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 = ['imp8mag',num2str(myrs(1)),num2str(monthdoing,'%2.2d'),'.dat'];	% Contruct file names
ssoutfive = ['imp8mag',num2str(myrs(1)),num2str(monthdoing,'%2.2d'),'.mat'];	% Contruct file names
outputtxt = [' Output plasma file: ', ssoutfour];
	disp(outputtxt);

[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 specific input
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% degap requires a specific input construct input array
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
nMmagtime = Mmagtime';				% turn row into column for degap program
nbxgsm    = bxgsm';
nbygsm    = bygsm';
nbzgsm    = bzgsm';
nxgsm     = xgsm';
nygsm     = ygsm';
nzgsm     = zgsm';
inmagarray = [nMmagtime,nbxgsm,nbygsm,nbzgsm,nxgsm,nygsm,nzgsm];	% Degape prgram wants a specific format
clear bygsm bzgsm xgsm ygsm zgsm;			%free up some RAM.

outmagarray=degapint(inmagarray,eflag,datenum('00:01:00'),startend,datenum('00:10:00'));
[dummy,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/yyy');				% Make tick in form I understand
%if (min(bxgsm) == max(bxgsm)),
%    ylim([0,1]);            				% set limits to avoid plotting flags
%else
%    ylim([-300,300]);          			% 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
	atxt = ['Plasma 1: length: ',num2str(lllmag),' ctout: ',num2str(ctout)];	% text out to check
	disp(atxt);					% text out to check
	ctout = ctout + 1;				% incriment the counter
end
disp('Making output array');
							% contruct output array
outputmagarray = [newday',newmonth',newyear',newhr',newmin',newsec',nbxgsm(1:lllmag),nbygsm(1:lllmag),nbzgsm(1:lllmag),nxgsm(1:lllmag),nygsm(1:lllmag),nzgsm(1:lllmag)]; 
							% 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 = ['Mag 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
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% end of for loop for years (Yeah, that was a pipe dream).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%end 
