function format_ace_mag_1(flag,version)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  function format_ace_mag_1(flag, version)
%  FLAG = year/month in format yyyymm
%  VERSION = version of the file.
%  purpose: convert CDF file format 
%  to one minute resolution ascii and matfile files
%  Author: James Weygand
% Creation: Feb 27, 2003
% Revision: August, 2003
% ex: ac_h0_mfi_20000221_v04.cdf
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% givens
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
format long e;							% for the matlab time.
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 month normal year.
daysofmonths2 	= [31 29 31 30 31 30 31 31 30 31 30 31];	% number of days per month leap year.
re 		= 6378.0;  					% Earth radus in kilometers
ct 		= 1 ; 						% counter set 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Load in data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yeardoing  = double(int32(flag/100));				% determine the year we are working on.
monthdoing = flag - yeardoing*100;				% determine the month we are working on.
if ( (yeardoing==1976) | (yeardoing==1980) | (yeardoing==1984) | (yeardoing==1988) | (yeardoing==1992) | (yeardoing==1996) | (yeardoing==2000)  ),
	monthend   = daysofmonths2(monthdoing);
else
	monthend   = daysofmonths(monthdoing);
enda								% Determine if this is a leap year.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Creat arrays (extra long)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
full = 60*60*24*31/3.0;   % 60 sec by 60 min by 24 hr by 31 days div by resolution to get max size
Mtime = zeros(1,full);	  % by creating arrays a head of time and fill the array we reduce time to 
bxgsm = zeros(1,full);    % run program. In the end we will cut off the extra length of the array.
bygsm = zeros(1,full);	  % Note that the length must be a maximum estimate.
bzgsm = zeros(1,full);
xgsm = zeros(1,full);
ygsm = zeros(1,full);
zgsm = zeros(1,full);

for ii=1:1:monthend	% loop through the number of days per month
	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    	% Determine file name and open input file.
    	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        yyyy      = num2str(flag);		% Convert year/month to string
	ver       = num2str(version);		% convert version to string
	dd        = num2str(ii,'%2.2d');  	% same with day
        ssone     = ['ac_h0_mfi_',yyyy,dd,'_v0',ver,'.cdf'];	% create file name
        outputtxt = [' Input file: ', ssone];	% Check we have the correct file
        	disp(outputtxt);			
        [fid,message] = fopen(ssone,'r');	% open the file
        if fid == -1				% error check.
                disp('Missing Data file!');
                disp(message);
        else
		[alldata,info] = cdfread(ssone);	% read in the cdf file. Note must have Matlabd 6.1 or higher to run this.	
		len = length(alldata);			% length of cdf file.
		for jj = 1:1:len,			% get the data from the file.
			Mtime(ct) = todatenum(alldata{jj,1});	% sort into arrays I can understand
			bxgsm(ct) = alldata{jj,6}(1);		% The location of data was determined by comparing
			bygsm(ct) = alldata{jj,6}(2);		% the cdf file with an ascii file.
			bzgsm(ct) = alldata{jj,6}(3);		% Note that you cannot run todatenum unless you
			xgsm(ct) = alldata{jj,12}(1);		% have matlab 6.5 or higher.
			ygsm(ct) = alldata{jj,12}(2);
			zgsm(ct) = alldata{jj,12}(3);
			ct = ct+1;				% counter for length of whole month
		end
		clear allmagdata;				% save save
	end
end
Mtime = Mtime(1:ct-1);						% chop of remainder of larger array.
bxgsm = bxgsm(1:ct-1);
bygsm = bygsm(1:ct-1);
bzgsm = bzgsm(1:ct-1);
xgsm = xgsm(1:ct-1)/re;
ygsm = ygsm(1:ct-1)/re;
zgsm = zgsm(1:ct-1)/re;

flag=1.0e+34;			% Flag Bob wants (discussed GEM 03)
				% -1.0e+31 is the error flag used in the cdf file.
index=find((xgsm<=-1.0e+29) | (ygsm<=-1.0e+29) | (zgsm<=-1.0e+29) | (bxgsm<=-1.0e+29) | (bygsm<=-1.0e+29) | (bzgsm<=-1.0e+29) );
%% 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.
xgsm(index)  = [];
ygsm(index)  = [];
zgsm(index)  = [];
bxgsm(index) = [];
bygsm(index) = [];
bzgsm(index) = [];
Mtime(index) = [];
len          = length(Mtime);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check what month we have
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[yrs, monthdoing,dummy, dummy,dummy,dummy] = datevec(Mtime(1));	% Get time in numbers I understand
outputtxt = [' Working on month: ', num2str(monthdoing)];	% Double check we are doing the month we think
disp(outputtxt);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% determine output file name
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ssoutfour = ['acemag',num2str(yrs(1)),num2str(monthdoing,'%2.2d'),'.dat'];	% Create outfule file name
ssoutfive = ['acemag',num2str(yrs(1)),num2str(monthdoing,'%2.2d'),'.mat'];	% Create outfule file name
outputtxt = [' Output plasma file: ', ssoutfour];				% Double check it is done right
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(yrs(1)),' ','00:00:00.00'];
startend(1)        = datenum(startyyymmddhhmmss);	% Determine start time of month and make string
lyear = yrs(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(yrs(1)),' ','23:59:00.00'];
else
	endyyymmddhhmmss = [num2str(daysofmonths(monthdoing)),'-',months(monthdoing,:),'-',num2str(yrs(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
nMtime     = Mtime';					% turn row into column
nbxgsm     = bxgsm';
nbygsm     = bygsm';
nbzgsm     = bzgsm';
nxgsm      = xgsm';
nygsm      = ygsm';
nzgsm      = zgsm';
inmagarray = [nMtime,nbxgsm,nbygsm,nbzgsm,nxgsm,nygsm,nzgsm];
clear bygsm bzgsm xgsm ygsm zgsm;			% free RAM
							% Run Bob's degap progrm.
outmagarray= degapint(inmagarray,flag,datenum('00:01:00'),startend,datenum('00:10:00'));
[maxmagval,lllmag] = max(outmagarray(:,1));		% get new dimensions and max value
nMtime     = outmagarray(:,1);				% sort into array I understand.
nbxgsm     = outmagarray(:,2);				% 'n' stands for new
nbygsm     = outmagarray(:,3);
nbzgsm     = outmagarray(:,4);
nxgsm      = outmagarray(:,5);
nygsm      = outmagarray(:,6);
nzgsm      = outmagarray(:,7);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Plot out to check
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
figure;                                     	% make fig window
plot(Mtime,bxgsm,'b',nMtime,nbxgsm,'k*');   	% plot original and interpolated
datetick('x','dd/mm/yy');			% make x axis I understand
if (min(bxgsm) == max(bxgsm)),
        ylim([0,1]);            		% set limits to avoid plotting flags
else
	ylim([-50,50]);          		% set limits to avoid plotting flags
end
clear Mtime vxgsm bxgsm;                        % free memory
%keyboard
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% read out to an ascii file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
disp('Fixing rounding error in Time.');
ctout   = 1;                              % set flag
newyear = zeros(1,lllmag);		  % make arrays ahead of time to improve run time.
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 = ['Mag 2: length: ',num2str(lllmag),' ctout: ',num2str(ctout)];
       ctout = ctout + 1;              % incriment the counter
end
disp('Closing ascii output file.');
status = fclose (fidmagout);

% read out to matlab binary file.
disp('Making matlab binary file.');
save(ssoutfive,'nMtime','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 nbxgsm nbygsm nbzgsm nxgsm nygsm nzgsm;
disp('Program complete');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% end of program
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%end


