%% K值和SWIR数据准备
function [swir_sel_res, k_CO2_sel_res] = DataAcquire(datapath, flist, Facility, FWHM_SWIR, choice)
%% 读取待选取波段
datafile = ['data/CertainBand',num2str(choice),'.xlsx'];
Tabledata = readtable(datafile, 'VariableNamingRule', 'preserve', 'TreatAsEmpty', '');
swir_var = ['swir_sel',num2str(choice)];
k_CO2_var = ['k_CO2_sel',num2str(choice)];
swir_sel_name = fullfile(datapath, [swir_var,'.mat']);
exist_swir_file = exist(swir_sel_name, 'file'); % 判断是否存在SWIR_SEL文件
k_CO2_sel_name = fullfile(datapath, [k_CO2_var,'.mat']);
exist_k_CO2_file = exist(k_CO2_sel_name, 'file'); % 判断是否存在k_CO2_SEL文件

if(exist_swir_file)
    mydisp('正在加载SWIR_SEL...')
    load(swir_sel_name, swir_var) % 加载变量
else
    swir = ReadDataSWIR_ori(datapath, flist); % 读取SWIR
    eval(['swir_sel',num2str(choice),'= [];']);
end
mydisp('数据读取完成');
% 计算k值的参数
if(exist_k_CO2_file)
    load(k_CO2_sel_name, k_CO2_var) % 加载变量
else
    k_CO2_sel2 = []; % 初始化
    eval(['k_CO2_sel',num2str(choice),' = [];']);
    xmlStruct = ReadXmlData(flist.xml);   % 读取xml文件
    PARM.SolarAzimuth = str2double(xmlStruct.SolarAzimuth); % 太阳方位角
    PARM.SolarZenith = str2double(xmlStruct.SolarZenith); % 太阳天顶角
    PARM.MON = month(str2date(xmlStruct.StartTime));
%     PARM.albedo = 0;
    PARM.albedo = -53;
end
%% 根据卫星确定波段
index = find(strcmp(Tabledata{:,1}, Facility.Satellite));
if(strcmp(Facility.Satellite, 'ZY1F'))
    if(FWHM_SWIR(1,2) == 16.26)
        index = 5;
    elseif(FWHM_SWIR(1,2) == 16.848)
        index = 6;
    else
        mydisp('ERROR FWHM of ZY1F!');
    end
end
%% K值计算
for j = 1:4
    Gas.Band_wav1 = Tabledata{index,3*j-1}; % nm 起始波段
    if(Gas.Band_wav1 == -1)
        continue;
    end
    Gas.Band_wav2 = Tabledata{index,3*j}; % nm 终止波段
    Gas.bandindex = GetWavIndexes(FWHM_SWIR, Gas);
    cellstr = cell2mat(Tabledata{index, 3*j+1}); % 待去除的波段
    %% 计算k值
    if(~exist_k_CO2_file) % 如果不存在K_CO2_SEL
        k_temp = calc_k(FWHM_SWIR, Gas, PARM, 'CO2');
        if(~strcmp(cellstr,"")) % 需要去除中间波段
            deleteband = reshape(str2double(split(cellstr,',')), 1, []);
            k_temp(deleteband) = [];
        end
        %         k_CO2_sel2 = cat(1, k_CO2_sel2, k_temp);
        eval(['k_CO2_sel', num2str(choice), ' = cat(1, k_CO2_sel', num2str(choice), ', k_temp);']);
    end
    %% 截取SWIR
    if(~exist_swir_file) % 如果不存在SWIR_SEL
        swir_temp = swir(:, :, Gas.bandindex);
        if(~strcmp(cellstr,"")) % 需要去除中间波段
            swir_temp(:,:,deleteband) = [];
        end
        eval(['swir_sel', num2str(choice), ' = cat(3, swir_sel',num2str(choice),',swir_temp);']);
    end
end
%% 保存变量
if(~exist_swir_file)
    mydisp('正在保存swir_sel变量')
    save(swir_sel_name, swir_var);
end
if(~exist_k_CO2_file)
    mydisp('正在保存k_CO2_sel变量')
    save(k_CO2_sel_name, k_CO2_var);
end
mydisp("k值计算完成");
%% 变量赋值
eval(['swir_sel_res = swir_sel', num2str(choice),';']);
eval(['k_CO2_sel_res = k_CO2_sel', num2str(choice),';']);
end
