pro merge_files,month=month,year=year,code=code,in_dir=in_dir,out_dir=out_dir,can=can,grn=grn,missing_min_path=missing_min_path
; This program merges daily 1 min. files into 1 big file
mm=['JANUARY','FEBRUARY','MARCH','APRIL','MAY','JUNE',$
'JULY','AUGUST','SEPTEMBER','OCTOBER','NOVEMBER','DECEMBER']
months=['jan','feb','mar','apr','may','jun',$
'jul','aug','sep','oct','nov','dec']
set=strarr(31)
missdays=intarr(31)
yrstr=string(year,format='(i2.2)')
if (year mod 4 eq 0) then begin
day1=[1,32,61,92,122,153,183,214,245,275,306,336]
day2=[31,60,91,121,152,182,213,244,274,305,335,366]
endif else begin
day1=[1,32,60,91,121,152,182,213,244,274,305,335]
day2=[31,59,90,120,151,181,212,243,273,304,334,365]
endelse
; Select stations
can_stations=['mc','co','rl','sm','si','da','pi','is','gi','ba','cc','es','rn','ta']
grn_stations=['am','sc','dn','dm','nr','na','fh','gb','sk','st','at','gd','um',$
'up','ku','sv','th','me','mw','mn','mg']
mac_stations=['re','cy','ig','rb','pb','gh','cb','pg','iq','cd','ch','bl', 'na']
stations = mac_stations
if keyword_set(can) then stations = can_stations
if keyword_set(grn) then stations = grn_stations
if keyword_set(code) then stations = [code]
; Set up loop
if keyword_set(month) then begin
start_month = month
end_month = month
endif else begin
start_month = 1
end_month = 12
endelse
for month = start_month, end_month do begin
for ii = 0, n_elements(stations)-1 do begin
code=STRUPCASE(stations(ii))
mo=month-1
ndays=(day2(mo)-day1(mo))+1
print,'Processing '+expandcode(code)+' '+mm(mo)+' '+yrstr
searchstr=code+strtrim(string(year),2)+'*'+'.1m'
print,in_dir+'\'+searchstr
fn=findfile(in_dir+'/'+searchstr,count=nel)
dot_pos = strpos(fn(0),'.')
d=fix(strmid(fn,dot_pos-3,3)) ;form array of days
if nel EQ 0 then begin
print,'NO MATCH FOR GIVEN YEAR AND STATION CODE'
goto, next_file
endif
ngood=0
nbad=0
s=0
for k=day1(mo),day2(mo) do begin
j=k-day1(mo)
i=where((d EQ k),count)
if count NE 0 then begin
set(j)=fn(i) ;names of month files
ngood=ngood+1
endif else begin
set(j)='missing.1m'
nbad=nbad+1
missdays(s)=k ;missing days
s=s+1
endelse
endfor
if ngood EQ 0 then begin
print,'NO FILES FOR GIVEN MONTH HAVE BEEN FOUND'
goto, next_file
endif
if nbad NE 0 then begin
print,format='(I3," missing days have been found")',nbad
print,'They are:'
print,missdays(0:s-1)
endif
; Open month file and write
newfn=out_dir+code+yrstr+months(mo)+'.1mg'
openw,newf,newfn,/get_lun
for kk=0,ndays-1 do begin
if set(kk) NE 'missing.1m' then openr,minf,set(kk),/get_lun $
else openr,minf,missing_min_path,/get_lun
rec=assoc(minf,bytarr(20160))
buf=rec(0)
writeu,newf,buf
free_lun,minf
endfor
free_lun,newf
next_file:
print,'ALL DONE...'
endfor ; station loop
endfor ; month loop
end

