function format_isee3_mag_4(flag)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function format_imp_mag_0
%
% purpose: format the imp 8 magnetometer files
% into matlab time format and Bx, By, Bz, (GSM)
% X, Y, Z (GSM RE)
%
%
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Givens
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Jul 14, 1975 62860   64.19 -0.44839 -1.3184 -3.1557 -3.3912 -2.8834 -0.94964 -1.8924 0.087856
format long e;
k_b = 1.380622e-23;     % boltzmann constanr
m_p =1.672e-27;          % mass of a proton
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];
daysofmonths2 = [31 29 31 30 31 30 31 31 30 31 30 31];
doyn = [1,32,60,91,121,152,182,213,244,274,305,335];
doyl = [1,32,61,92,122,153,183,214,245,275,306,336];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Load in data
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	yy=flag;
	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
                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
        indb = find(allmagdata(5,:) == 999.9);       % This is very important must replace
        indyz = find(allmagdata(21,:) == 9999.99);   % the flags with bob flags
        % sort data
        myrs  = allmagdata(1,:);
	    doy   = allmagdata(2,:);
	    mhrs  = allmagdata(3,:);
	    mmins = allmagdata(4,:);
        bxsc  = allmagdata(5,:);
        bysc  = allmagdata(6,:);
	    bzsc  = allmagdata(7,:);
        xgse  = allmagdata(19,:);
        ygse  = allmagdata(20,:);
	    zgse  = allmagdata(21,:);
        %%keyboard
        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
        for ii=1:1:len,
              % leap year check
		      if ( (lyear==1976) | (lyear==1980) | (lyear==1984) | (lyear==1988) | (lyear==1992) | (lyear==1996) | (lyear==2000)  ),
                        for jj=1:1:11.
                                if ( (doy(ii)>=doyl(jj)) & (doy(ii)<=doyl(jj+1)) ),
                                        mmons(ii) = jj;
                                end
                        end
                        mdays(ii) =      (doy(ii) - doyl(mmons(ii)) + 1);
                else % normal year check
                        for jj=1:1:11.
                                if ( (doy(ii)>=doyn(jj)) & (doy(ii)<=doyn(jj+1)) ),
                                        mmons(ii) = jj;
                                end
                        end
                        mdays(ii) =  (doy(ii) - doyn(mmons(ii))  + 1);
                end
	    end

        Mmagtime = datenum(myrs,mmons,mdays,mhrs,mmins,0); % get matlab time
	    clear allmagdata;  % clear some RAM
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % check what month we have
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	    monthdoing = mmons(1);  % check, check and recheck
        outputtxt = [' Working on month: ', num2str(monthdoing)];
        disp(outputtxt);

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % determine output file name
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
	    ssoutfour = ['isee3mag',num2str(myrs(1)),num2str(monthdoing,'%2.2d'),'.dat'];
        ssoutfive = ['isee3mag',num2str(myrs(1)),num2str(monthdoing,'%2.2d'),'.mat'];
        outputtxt = [' Output plasma file: ', ssoutfour];
        disp(outputtxt);
        % open output file
        [fidmagout,message] = fopen(ssoutfour,'w');
        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);
        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);
%keyboard
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % 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));
            vector = [bxsc(jj),bysc(jj),bzsc(jj)];
            vecout = mat9vec3(RF,vector);
            bxgsm(jj) = vecout(1);
            bygsm(jj) = vecout(2);
            bzgsm(jj) = vecout(3);
            vectortwo = [xgse(jj),ygse(jj),zgse(jj)];
            vectwoout = mat9vec3(RF,vectortwo);
            xgsm(jj) = vectwoout(1);
            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,1.0e25,datenum('00:01:00'),startend,datenum('00:10:00'));
        [maxmagval,lllmag] = max(outmagarray(:,1));
	    nMmagtime = outmagarray(:,1);     % putinot something more readable for this stupid programmer
	    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(Mmagtime,bxgsm,'b',nMmagtime,nbxgsm,'k*');   % plot original and interpolated
    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
    %plot(nMtime,nbxgsm,'k*');
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % 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');
        for kk=1:1:length(indb),
            nbxgsm(indb(kk)) = 1.0e25;
            nbygsm(indb(kk)) = 1.0e25;
            nbzgsm(indb(kk)) = 1.0e25;
        end
        for kk=1:1:length(indyz),
            nxgsm(indyz(kk)) = 1.0e25;
            nygsm(indyz(kk)) = 1.0e25;
            nzgsm(indyz(kk)) = 1.0e25;
        end

    
	% 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
	%keyboard
    disp('Closing output file.');
    status = fclose (fidmagout);	
    
    % read out to 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 
