year=1981:2015;

files=dir('/Users/yangyang/Extreme_Aerosol/VIS/dat/1980_2014/*.txt');

lon=zeros(length(files),1);
lat=zeros(length(files),1);

vis_mean=zeros(length(files),length(year),90);
vis_ndays=zeros(length(files),length(year),90);


for FileID=1:length(files)
    
    temp=importdata(['/Users/yangyang/Extreme_Aerosol/VIS/dat/1980_2014/',files(FileID).name],' ');
    lat(FileID)=temp(2);
    lon(FileID)=temp(3);
    temp=importdata(['/Users/yangyang/Extreme_Aerosol/VIS/dat/1980_2014/',files(FileID).name],' ',2);
    ncount=length(temp.data);
    month=temp.data(:,3);
    day=temp.data(:,4);
    vis=temp.data(:,5);
    prcp=temp.data(:,6);
    rh=temp.data(:,7);
    t=temp.data(:,8);
    
    YearID=1;
    month(ncount+1)=12;
    days=0;
    
    for DayID=1:ncount
        
        days=days+1;
        if month(DayID)==12
            vis_mean(FileID,YearID,day(DayID))=vis(DayID);
        elseif month(DayID)==1
            vis_mean(FileID,YearID,day(DayID)+31)=vis(DayID);
        elseif month(DayID)==2 && day(DayID)<29
            vis_mean(FileID,YearID,day(DayID)+62)=vis(DayID);
        end
        
        if vis(DayID)<10
            if month(DayID)==12
                vis_ndays(FileID,YearID,day(DayID))=1;
            elseif month(DayID)==1
                vis_ndays(FileID,YearID,day(DayID)+31)=1;
            elseif month(DayID)==2 && day(DayID)<29
                vis_ndays(FileID,YearID,day(DayID)+62)=1;
            end
        end
        
        if month(DayID)==2 && month(DayID+1)==12
            days=0;
            YearID=YearID+1;
        end
    end
    
end





save('VIS_1981_2015_daily.mat','lat','lon','vis_mean','vis_ndays')

nccreate('VIS_1981_2015_daily.nc','Year','Dimensions',{'year',length(year)},'Format','classic')
ncwrite('VIS_1981_2015_daily.nc','Year', year)
ncwriteatt('VIS_1981_2015_daily.nc','Year','long_name','Year 1973-2014')
nccreate('VIS_1981_2015_daily.nc','lat','Dimensions',{'nstation',length(files)},'Format','classic')
ncwrite('VIS_1981_2015_daily.nc','lat', lat)
ncwriteatt('VIS_1981_2015_daily.nc','lat','units','degrees_north')
ncwriteatt('VIS_1981_2015_daily.nc','lat','long_name','Latitude')
nccreate('VIS_1981_2015_daily.nc','lon','Dimensions',{'nstation',length(files)},'Format','classic')
ncwrite('VIS_1981_2015_daily.nc','lon', lon)
ncwriteatt('VIS_1981_2015_daily.nc','lon','units','degrees_east')
ncwriteatt('VIS_1981_2015_daily.nc','lon','long_name','Longitude')
nccreate('VIS_1981_2015_daily.nc','vis_mean','Dimensions',{'nstation',length(files),'year',length(year),'day',90},'Format','classic')
ncwrite('VIS_1981_2015_daily.nc','vis_mean', vis_mean)
nccreate('VIS_1981_2015_daily.nc','vis_ndays','Dimensions',{'nstation',length(files),'year',length(year),'day',90},'Format','classic')
ncwrite('VIS_1981_2015_daily.nc','vis_ndays', vis_ndays)
ncdisp('VIS_1981_2015_daily.nc')
