*! outseries.ado  v1.1.0  cfb 1531 revised to make use of file handling
* outseries.ado: Stata7 procedure to write each Q/M timeseries in a file to
*                a separate ASCII file in the cwd
*
program define outseries,rclass
syntax [varlist] [using/] [,Dir(string) Tin(string) Matlab]
qui tsset
local tv `r(timevar)'
local tu `r(unit1)'
if "`varlist'" == "" & "`using'" == "" {
	unab varlist: _all
	}
if "`using'" != "" {
	tempname ser
	file open `ser' using "`using'", read
	local en
	local varlist
	file read `ser' mne
	while r(eof)==0 {
		local varlist "`varlist' `mne'"
		local en = `en' + 1
		file read `ser' mne
		}
	file close `ser'
	di in gr _n "`en' series names read from file"
}
* if no 'dir' specified,
* create a timestamped directory into which data will be placed
* otherwise cd to that directory
local ss $S_DATE
local sfix=subinstr("`ss'"," ","-",.)
if "`dir'" == "" {
	mkdir "`sfix'"
	qui cd "`sfix'"
	}
else {
	qui cd "`dir'"
	}
* if 'tin' specified, use that in-clause
if "`tin'" !="" {
	local inc " if tin(`tin') "
	}
tempvar tt yr pyr
* write the series as separate files, adding year and part of year
qui gen `yr' = yofd(dofm(`tv'))
qui gen `pyr' = .
if "`tu'" == "m" {
	qui replace `pyr' = month(dofm(`tv'))
	}
else if "`tu'" == "q" {
	qui replace `pyr' = quarter(dofq(`tv'))
	}
foreach i of varlist `varlist' {
	local fn=substr("`i'",1,.)
	if "`matlab'" !="" {
		capt drop `tt'
		qui gen str12 `tt' = string(`i') `inc'
		qui replace `tt'=cond(match(`tt',"."),"NaN",`tt') `inc'
		qui outfile `yr' `pyr' `tt' `inc' using `fn'.dat, noquote replace
		}
	else {
		qui outfile `yr' `pyr' `i' `inc' using `fn'.txt, noquote comma replace
		}
	}
di _n "Your default directory is "
pwd
di _n "with contents:"
dir
end
exit