function format_ace_mag_0(flag,version)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%  function format_ace_mag_0(flag)
%  purpose: convert CDF file format 
%  Author: James Weygand
% Creation: Feb 27, 2003
% ex: ac_h0_mfi_20000221_v04.cdf
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% givens
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
format long e;
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];
daysofmonths2 = [31 29 31 30 31 30 31 31 30 31 30 31];
re = 6378.0;  % kilometers
ct =1 ;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Load in data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
yeardoing  = double(int32(flag/100));
monthdoing = flag - yeardoing*100;
if ( (yeardoing==1976) | (yeardoing==1980) | (yeardoing==1984) | (yeardoing==1988) | (yeardoing==1992) | (yeardoing==1996) | (yeardoing==2000)  ),
	monthend   = daysofmonths2(monthdoing);
else
	monthend   = daysofmonths(monthdoing);
end

	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    	% 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);
	bxgsm = zeros(1,full);
	bygsm = zeros(1,full);
	bzgsm = zeros(1,full);
	xgsm = zeros(1,full);
	ygsm = zeros(1,full);
	zgsm = zeros(1,full);
for ii=1:1:monthend
	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    	% Determine file name and open input file.
    	%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        yyyy=num2str(flag);
	ver = num2str(version);
	dd = num2str(ii,'%2.2d');  %%num2str(ii);
        ssone = ['ac_h0_mfi_',yyyy,dd,'_v0',ver,'.cdf'];
        outputtxt = [' Input file: ', ssone];
        disp(outputtxt);
        [fid,message] = fopen(ssone,'r');
        if fid == -1
                disp('Missing Data file!');
                disp(message);
        else
		[alldata,info] = cdfread(ssone);	
		len = length(alldata);
		for jj = 1:1:len
			%keyboard
			Mtime(ct) = todatenum(alldata{jj,1});
			bxgsm(ct) = alldata{jj,6}(1);
			bygsm(ct) = alldata{jj,6}(2);
			bzgsm(ct) = alldata{jj,6}(3);
			xgsm(ct) = alldata{jj,12}(1);
			ygsm(ct) = alldata{jj,12}(2);
			zgsm(ct) = alldata{jj,12}(3);
			ct = ct+1;
		end
		clear allmagdata;
		%status = fclose(fid);
	end
	%keyboard
end
	Mtime = Mtime(1:ct-1);
	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+25;
index=find(bxgsm<=-1.0e+29);	% error flag for cdf is -1.0e+31
bxgsm(index)=repmat(flag,1,length(index));

index=find(bygsm<=-1.0e+29);
bygsm(index)=repmat(flag,1,length(index));

index=find(bzgsm<=-1.0e+29);
bzgsm(index)=repmat(flag,1,length(index));

index=find(xgsm<=-1.0e+29);
xgsm(index)=repmat(flag,1,length(index));

index=find(ygsm<=-1.0e+29);
ygsm(index)=repmat(flag,1,length(index));

index=find(zgsm<=-1.0e+29);
zgsm(index)=repmat(flag,1,length(index));

%keyboard
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% check what month we have
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
[yrs, monthdoing,dummy, dummy,dummy,dummy] = datevec(Mtime(1))
outputtxt = [' Working on month: ', num2str(monthdoing)];
disp(outputtxt);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% determine output file name
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ssoutfour = ['acemag',num2str(yrs(1)),num2str(monthdoing,'%2.2d'),'.dat'];
ssoutfive = ['acemag',num2str(yrs(1)),num2str(monthdoing,'%2.2d'),'.mat'];
outputtxt = [' Output plasma file: ', ssoutfour];
disp(outputtxt);
        % open output file
[fidmagout,message] = fopen(ssoutfour,'w');
if fidmagout == -1
	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);
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);
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % degap requires a specific input construct input array
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        nMtime = Mtime';
        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;
        %keyboard
        outmagarray=degapint(inmagarray,1.0e25,datenum('00:01:00'),startend,datenum('00:10:00'));
        [maxmagval,lllmag] = max(outmagarray(:,1));
        nMtime = outmagarray(:,1);
        nbxgsm = outmagarray(:,2);
        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','HH:MM');
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
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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 = ['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.
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;
%keyboard

