

%note some details about how this data is stored. 
%it's stored 212 days starting Oct 1... in a file with the year = 2023 (for startign Oct 1 2022)

dataDir = '/data/projects/CHILL/';
if(0);
        %check on completeness of data - looks good
        f_lat = 300;
        f_lon  = 500;
        for ny = 1981:2023; %wateryears
                m=matfile([dataDir,'historicalchill_alldays_',num2str(ny),'.mat'],'Writable',false);
                %c(:,ny-1981+1) = squeeze(m.chillhours_all(f_lat,f_lon,:));
                %c(:,ny-1981+1) = squeeze(m.chillportion_all(f_lat,f_lon,:));
                c(:,ny-1981+1) = squeeze(m.utahchill_all(f_lat,f_lon,:));
        end
end;


dataDir = '/data/projects/CHILL/';

addpath('/home/katherine/CRONJOBS/');


%==========================================
% DETERMINE YEAR TO PROCESS
%==========================================
%addpath('/data/code/MATLAB:');
DATE = datetime('now','Format','yyyy');


YEAR = year(DATE);
MONTH = month(DATE);
if(MONTH==1)
	YEAR = YEAR -1; %this is the year we are processing freeze summaries
	MONTH = 12;
else;
	MONTH = MONTH-1
end;

%==========================================
% Break CONUS grid into regional subsets. The more powerful the machine, the
% larger the regional subsets can be.
LAT_START = [1 301];
LAT_END = [300 585];
LON_START = [1 301 601 901 1101];
LON_END = [300 600 900 1100 1386];
% Create constant for number of years, lat, lon, and models.
N_LAT = 585;
N_LON = 1386;
N_DAY = 366;

YEARS = 1979:2026;

YR_START=1979;
YR_END=YEAR; 
N_YRS = YR_END-YR_START+1;
YR_INDEX = 1:N_YRS;
years =YR_START: YR_END;
n_yr = length(YEARS);

%==========================================
%  GET GRID
%==========================================
%new grid
m=matfile(['alt_gridmetlonlat.mat']);
lat = double(m.lat);
lon =double(m.lon);
%==========================================
%  SET UP NEW .MAT FILE
%==========================================
	yr_index = [1:N_YRS];
	n_lat = length(lat);
	n_lon = length(lon);
	n_yr = length(yr_index);

	mread = matfile('oldchill.mat','Writable',false);

	mwrite = matfile('/data/projects/CHILL/historicalchill_alldays_allyears.mat','Writable',true);
	if(0);
		mwrite.lat=lat;
		mwrite.lon=lon;
		mwrite.years =years; 
		mwrite.chillhours=NaN(n_lon,n_lat,n_yr,7,'single');
		mwrite.chillportion=NaN(n_lon,n_lat,n_yr,7,'single');
		mwrite.utahchill=NaN(n_lon,n_lat,n_yr,7,'single');
	end;
        %mwrite.chillhours(:,:,1:n_yr-1,:) = mread.chillhours;
        %mwrite.chillportion(:,:,1:n_yr-1,:) = mread.chillportion;
        %mwrite.utahchill(:,:,1:n_yr-1,:) = mread.utahchill;

%==========================================
%  COMPUTE DD FOR CURRENT YEAR

%% NEED TO CHANGE THE   lastmonth = 1 to 2 under  if(yearInFilename == 2025); below
%==========================================
yearmin = min(years);

%temp for creating big oldfile
for yearInFilename= 2025;
%for yearInFilename= 1980:2024;
	yearInFilename
	mread = matfile(['/data/projects/CHILL/historicalchill_alldays_',num2str(yearInFilename),'.mat'],'Writable',false);
	% 585        1386         212  this is data from Oct 1 I believe

	if(yearInFilename == 2025);
		months = 1;  %months=1:4 means Oct - Jan
		months = 1:MONTH - 10+1; %this tries to do this automatically for the MONTH run
	else;
		months = 1:7;
	end;

	for mo=months; %oct to april
		if(mo<=3);
			year = yearInFilename - 1;
		else;
			year = yearInFilename ;
		end;
		yrindex2write = year  -yearmin+1; 
		yr = year-yearmin+1;

		if(isleapyear(year));
			daysInMonths  =[31 30 31 31 29 31 30]; % 31 30 31 31 30];
		else;
			daysInMonths  =[31 30 31 31 28 31 30]; % 31 30 31 31 30];
		end;

		if(mo==1);
			dayStart(mo) = 1;
			dayEnd(mo) = 31;
		else;
			dayStart(mo) = sum(daysInMonths(1:mo-1))+1;
			t = sum(daysInMonths(1:mo));
			if(mo==7 && t == 213);
				t = 212;
			end
			dayEnd(mo) =t;
		end;
		dayRange=[dayStart(mo):dayEnd(mo)];

		%get nan mask
		t= mread.chillhours_all(:,:,1)';
		f_nan=find(isnan(t));


		temp = nansum(double(mread.chillhours_all(:,:,dayRange)),3);
		temp = temp';
		temp(f_nan) = NaN;
		mwrite.chillhours(:,:,yr,mo) = single(temp);

		%for chill units.. need to set negatives to 0 for the season accumulation (corrected 1/18/2024)
		temp = mread.chillportion_all(:,:,dayRange);
		%f=find(temp<0);temp(f) = 0.0;
		temp = nansum(double(temp),3);
		temp = temp';
		temp(f_nan) = NaN;
		mwrite.chillportion(:,:,yr,mo) = single(temp);


		temp = nansum(double(mread.utahchill_all(:,:,dayRange)),3);
		temp = temp';
		temp(f_nan) = NaN;
		mwrite.utahchill(:,:,yr,mo) = single(temp);
	end;
	%for mo=lastmonth+1:7;
	%	 mwrite.chillhours(:,:,yr,mo) = NaN(1386,585,'single');
	%	  mwrite.chillportion(:,:,yr,mo) = NaN(1386,585,'single');
	%	   mwrite.utahchill(:,:,yr,mo) =  NaN(1386,585,'single');
	%end;
end; %yr

%==========================================
%  CREATE NETCDF SUMMARY FILE
%==========================================
file_chill = matfile(['/data/projects/CHILL/historicalchill_alldays_allyears.mat'],'Writable',true);
chillhours =file_chill.chillhours;
lat = file_chill.lat;
lon = file_chill.lon;
years = file_chill.years;
%===============================
%       TIME
%===============================
REF_YEAR=1900;
YR_REF=1900;
%===============================
%   MAKE NETCDF
%=============================
MONTHS ={'Oct';'Nov';'Dec';'Jan';'Feb';'Mar';'Apr';};

units='';
for mo=1:7;
	clear time;
	if(mo <=3);
		monthAdjusted = mo+9;
	else;
		monthAdjusted = mo-3;

	end;
	for yr=1:length(years);
		year =years(yr);
		time(yr) = datenum(year,monthAdjusted,15)  -datenum(REF_YEAR,1,1);
	end;
	[Y,M,D]=datevec(time+datenum(YR_REF,1,1));


	varname = 'chillhours';
	filename_chill = ['metdata_',varname,'_monthlyTimeSeries_',char(MONTHS{mo}),'.nc'];
	chill =double(file_chill.(varname)(:,:,:,mo));
	chill = permute(chill,[3 1 2]); %change dimensions to time,lon,lat
	netcdfFilename = [filename_chill]; 
	  system(['rm ',netcdfFilename])
	make_monthlynetcdf(chill,time,lat,lon,varname,units,1,netcdfFilename,REF_YEAR);

	varname = 'chillportion';
	filename_chill = ['metdata_',varname,'_monthlyTimeSeries_',char(MONTHS{mo}),'.nc'];
	chill =double(file_chill.(varname)(:,:,:,mo));
	chill = permute(chill,[3 1 2]); %change dimensions to time,lon,lat
	netcdfFilename = [filename_chill]; 
	  system(['rm ',netcdfFilename])
	make_monthlynetcdf(chill,time,lat,lon,varname,units,2,netcdfFilename,REF_YEAR);

	varname = 'chillunits';
	filename_chill = ['metdata_',varname,'_monthlyTimeSeries_',char(MONTHS{mo}),'.nc'];
	chill =double(file_chill.('utahchill')(:,:,:,mo));
	chill = permute(chill,[3 1 2]); %change dimensions to time,lon,lat
	netcdfFilename = [filename_chill]; 
	  system(['rm ',netcdfFilename])
	make_monthlynetcdf(chill,time,lat,lon,varname,units,3,netcdfFilename,REF_YEAR);

end;
%==========================================
%  TRANSFER NETCDF SUMMARY FILES
%==========================================
%this part isn't working on santaana... due to not having this connection set up
if(0);
	NKN_PATH = 'khegewisch@climate-utils.nkn.uidaho.edu://reacch-data/MET/summaries'
	for mo=1:7;
		filename_chill = ['metdata_chillhours_monthlyTimeSeries_',char(MONTHS{mo}),'.nc'];
		outputfilename = filename_chill;
		scpstatus = system(['scp ',outputfilename,' ',NKN_PATH]);

		filename_chill = ['metdata_chillportion_monthlyTimeSeries_',char(MONTHS{mo}),'.nc'];
		outputfilename = filename_chill;
		scpstatus = system(['scp ',outputfilename,' ',NKN_PATH]);

		filename_chill = ['metdata_chillunits_monthlyTimeSeries_',char(MONTHS{mo}),'.nc'];
		outputfilename = filename_chill;
		scpstatus = system(['scp ',outputfilename,' ',NKN_PATH]);

	end;
end;
%==========================================
% RESET FOR NEXT YEAR
%==========================================
if(0);
	system('mv oldchill.mat bkupchill.mat');
	system('cp historicalchill_alldays_allyears.mat oldchill.mat')
end;
