subroutine fill_grads_template(output_string,template,unusable,experiment_id,nymd,nhms,time,preserve,rc)
character(len=*), intent(out) :: output_string
character(len=*), intent(in) :: template
class(keywordEnforcer), optional, intent(in) :: unusable
character(len=*), intent(in), optional :: experiment_id
integer, intent(in), optional :: nymd
integer, intent(in), optional :: nhms
type(ESMF_Time), intent(in), optional :: time
logical, intent(in), optional :: preserve
integer, intent(out), optional :: rc
integer :: year,month,day,hour,minute,second,tmpl_length,output_length
integer :: i, m, istp, k, kstp, i1, i2
character(len=1) :: c0,c1,c2
character(len=4) :: sbuf
logical :: valid_token,preserve_
integer :: status
_UNUSED_DUMMY(unusable)
if (present(preserve)) then
preserve_=preserve
else
preserve_=.false.
end if
year=uninit_time
month=uninit_time
day=uninit_time
hour=uninit_time
minute=uninit_time
second=uninit_time
if (present(time)) then
_ASSERT(.not.present(nymd),'can not specify an ESMF_Time and an integer time')
_ASSERT(.not.present(nhms),'can not specify an ESMF_Time and an integer time')
call ESMF_TimeGet(time,yy=year,mm=month,dd=day,h=hour,m=minute,s=second,rc=status)
_VERIFY(status)
end if
if (present(nymd)) then
_ASSERT(.not.present(time),'can not specify an ESMF_Time and an integer time')
year = nymd/10000
month = mod(nymd/100,100)
day = mod(nymd,100)
end if
if (present(nhms)) then
_ASSERT(.not.present(time),'can not specify an ESMF_Time and an integer time')
hour = nhms/10000
minute = mod(nhms/100,100)
second = mod(nhms,100)
end if
output_string = ""
output_length=len(output_string)
tmpl_length=len_trim(template)
i=0
istp=1
k=1
kstp=1
do while(i+istp <= tmpl_length)
i=i+istp
c0 = template(i:i)
if (c0 == "%") then
i1=i+1
c1=""
if (i1<=tmpl_length) c1=template(i1:i1)
select case(c1)
case("s")
if (present(experiment_id)) then
istp=2
m=min(k+len_trim(experiment_id)-1,output_length)
output_string(k:m)=experiment_id
k=m+1
cycle
else if (preserve_) then
output_string(k:k+1)="%s"
k=k+1
else
_FAIL("Using %s token with no experiment id")
end if
case("%")
istp=2
output_string(k:k)=c1
k=k+1
cycle
case default
c2=""
i2=i1+1
if(i2 <= tmpl_length) c2=template(i2:i2)
valid_token = check_token(c1//c2)
if (valid_token) then
istp=3
if (.not.preserve_) then
_ASSERT(present(nymd) .or. present(nhms) .or. present(time),'Using token with no time')
end if
sbuf = evaluate_token(c1//c2,year,month,day,hour,minute,second,preserve_)
kstp = len_trim(sbuf)
m=k+kstp-1
output_string(k:m)=sbuf
k=m+1
else
_FAIL("Invalid token in file template: "//c1//c2)
end if
end select
else
istp=1
output_string(k:k)=template(i:i)
k=k+1
end if
enddo
_RETURN(_SUCCESS)
end subroutine fill_grads_template