*! version 1.0.0 24jul2013
*! Retry file operations on error
*! By Sergiy Radyakin

program fileop

	version 10.0

	local maxatt=`"$FILEOP_MAXATTEMPT"'
	local delay=`"$FILEOP_DELAY"'

	if (`"`maxatt'"'=="") local maxatt=10
	if (`"`delay'"'=="") local delay=1000

	local attempt=1
	local ecode=9999 // irrelevant non-zero code

	while (`attempt'<=`maxatt') {
	  capture noisily `0'
	  if !_rc {
		local ecode=0
		continue, break
	  }
	  local ecode=_rc
	  local attempt=`attempt'+1

	  if (`attempt'==`maxatt') local emsg ""
	  else local emsg =" Retrying."

	  if `attempt'<=`maxatt' display as result "Encountered error `ecode'.`emsg'"
	  sleep `delay'
	}

	if `ecode' error(`ecode')

end