* version 0.0.1 :: 01/28/12 11:09 AM :: Created separate ado for part
*!version 0.0.2 :: 03/30/12 11:37 AM

//  Program     :  _cllct_appendFILE.ado
//  Author      : Joseph D. Wolfe & J. Scott Long
//  Description : Save graphs in single file (rtf, html, tex)
//  Requirements: >= Stata 10 (untested on previous versions)

capture clear  programs
program define _cllct_appendFILE, sclass

syntax,                         ///
    [                           ///
								/// Necessary options
    ahandle(string asis)        /// temp name of handle
    bhandle(string asis)        /// temp name of handle
    appfile(string asis)        /// temp name of file
    savefile(string asis)   	/// name of file name & loc if avail
								///
								/// Graphout options
	file_ext(string)            /// file extension (e.g., .rtf)
	fignum(numlist)             /// figure number
	tabnum(numlist)             /// figure number
	nocount                     /// don't count graphs
	fbarrier(numlist)           /// tex files
							    ///
								/// Statout options
	tabnum(numlist)             /// table number
    ]

//  #2
//  Set defaults

local SaveFileAs `"`savefile'"'

if "`fbarrier'" !="" {
	local brpkg  "\usepackage{placeins}"
	local break  "\FloatBarrier"
	local brnum  "`fbarrier'"
}

//  #2
//  append file

* locals to find end of file
local endflcxv   `"="""'
local endfltex   `"\end{document}"'
local endflrtf   `"}"'
local endflhtml  `"</body></html>"'
local endfl      `"`endfl`file_ext''"'

* open file with graphs
qui file open `ahandle'  using `appfile'   , read write
qui file open `bhandle'  using `macval(SaveFileAs)', read write
file seek `bhandle' query
local loc    = r(loc)
local end    = 0

* copy file to temporary file
while (`end'==0) {
	file seek  `bhandle' `loc'
	file read  `bhandle' line
	local end = r(eof)
	file seek  `bhandle' query
	local loc = r(loc)

	*check if file ends
	local checkend = 1
	if (`"`line'"' == `"`endfl'"') & (`"`file_ext'"'!="csv") {
		local  checkend   = 0
		while `checkend' == 0 {
			file seek  `bhandle' `loc'
			file read  `bhandle' newline
			local newend  = r(eof)
			file seek  `bhandle' query
			local newloc  = r(loc)
			local newline `"`line'"'
			if `"`newline'"'  != "" local checkend = 1
			if   `newend'     != 0  local checkend = 2
		}
	}
	if `checkend' == 2 continue, break

	*count graphs in tex file too
	  *1) add break to avoid "too many floats"
	  *2) add figure # before graph
	if "`nocount'"=="" & regexm(`"`line'"',"Figure [1-9]+") & "`float'"=="" {
		local fignum = `fignum'+1
	}
	if "`nocount'" == "" & regexm(`"`line'"', "Table [1-9]+")  {
		local tabnum = `tabnum'+1
	}
	if "`file_ext'" == "tex" & "`break'" != "" {
		if regexm(`"`line'"', `"`endfig'"') {
			local numgraph = `numgraph'+1
		}
		if regexm(`"`line'"', `"`break'"') {
			local numgraph =  0
		}
	if `numgraph' == `brnum' {
		local line `"`line' `break'"'
		local numgraph = 0
	}
	}
	*write line to append file
	file write `ahandle' `"`line'"' _n
 }

//  #3
//  Add sreturns

sreturn local fignum `fignum'
sreturn local tabnum `tabnum'

//  #4
//  Close

end
exit