function spt_fit = read_spt_fast(filename)
% This function was written by Debra Wunch
% Read gfit output spt fit file
% example: 
% filename = '/home/dwunch/ggg/spt/zr10921_1175479872.762';%zsr9138_1165028291.227';
% fit = read_spt_fast(filename)
% output:
% spt_fit = 
%         Freq: [45200x1 double]
%           Tm: [45200x1 double]
%           Tc: [45200x1 double]
%      mol_1o2: [45200x1 double]
%      mol_2o2: [45200x1 double]
%      mol_3o2: [45200x1 double]
%      mol_0o2: [45200x1 double]
%          h2o: [45200x1 double]
%        other: [45200x1 double]
%        solar: [45200x1 double]
%     Freq_min: 1.2949e+04
%     Freq_max: 1.3289e+04
%         npts: 45200
%       zenith: 70.3150
%       obsalt: 0.4420
%       tanalt: 0.4680
%          rms: 1.2871
%        intdz: 4.5150e+24
%     tot_cols: [1.7000e+23 4.3560e+24 1.7000e+23 4.6470e+24 1.8000e+23 1.8130e+23 2.5000e+23 9.5820e+22 1.6000e+22]

% clear
% % filename = '/home/dwunch/ggg/spt/zeu20080405s0e00c.000';
% filename = '/export/raid1/dwunch/parkfalls_ifs1/o2_quadrupole/spt/zpa20050114saaaab.042';
% filename = '/export/raid1/dwunch/jpl_ifs3/080117/o2_7885_fits/final_iteration/zjc20080117sfddaa.266';
% tic
% filename = '/net/ccycle/data3/dwunch/parkfalls_ifs1/o2_quadrupole/20040709/spt/zpa20040709saaaab.189';
% filename = '/net/ccycle/data2/tccon/justus_notholt/results/results_20100907/spt/hcooh_1100/z04100800.1';

fid = fopen(filename,'r');
a = str2num(fgetl(fid));
nhead = a(1);
ncol = a(2);
% fm = repmat('%f',1,17);
b = textscan(fgetl(fid),'%f');
b = b{1};

headers = textscan(fgetl(fid),'%s');
headers = headers{1};
if length(headers)~=ncol
    disp(['The number of headers, ' num2str(length(headers)) ' does not match the first line of the file, ' num2str(ncol)]);
end

for i=1:length(headers)
    if headers{i}(1)=='1'||headers{i}(1)=='2'||headers{i}(1)=='3'||headers{i}(1)=='4'||headers{i}(1)=='5'...
            ||headers{i}(1)=='6'||headers{i}(1)=='7'||headers{i}(1)=='8'||headers{i}(1)=='9'||headers{i}(1)=='0'
        headers{i} = ['mol_' headers{i}];
    end
end

form = repmat('%f',1,length(headers));
A = fscanf(fid,form,[length(headers),inf])';
% fscanf is faster than textscan
fclose(fid);

A = mat2cell(A,size(A,1),ones(1,length(headers)));
spt_fit = cell2struct(A,headers,2);
spt_fit.Freq_min = b(1);
spt_fit.Freq_max = b(2);
spt_fit.npts = b(3);
spt_fit.zenith = b(4);
spt_fit.obsalt = b(5);
spt_fit.tanalt = b(6);
spt_fit.rms = b(7);
spt_fit.intdz = b(8);
spt_fit.tot_cols = [b(9:end)];
[~,name,ext] = fileparts(filename);
spt_fit.filename = [name ext];
% toc
