'LINEA add-in

'HELP: Åpner dokumentasjon
'Inneholder subroutines som henter data/åpner hjelpefil
'	include .\..\toolbox_for_retrieving_data
'if @upper(%0)="HELP" or %0="?" then
'	call openDocumentation
'endif

'useful strings
	%graph	= "linea"
	%pre_existing_content 			= @wflookup("*")

	'make spool object with graphs based on annual data
	%pageaux="____xx"
	%cp=@pagename
	%pagesmpl=@pagesmpl
	%firstperiod=@word(%pagesmpl, 1)
	%firstyear= @datestr(@dateval(%firstperiod), "yyyy")
	%lastperiod = @word(%pagesmpl, 2)
	%lastyear= @datestr(@dateval(%lastperiod), "yyyy")
	%spoolaux= @getnextname("_spoolaux")
	%firstyear1 = @datestr(@dateadd(@dateval(%firstyear), -1, "Y"), "YYYY")

'sletter siden hvis den eksisterer (f.eks hvis programmet har stoppet opp av en grunn)
if @pageexist(%pageaux)=1 then
	pagedelete {%pageaux} 
endif

'options
	if @isempty(@equaloption("b"))=0 then
		%elemsmpl = @equaloption("b")
		else
			%elemsmpl = %firstyear
			if @hasoption("q")=1 or @hasoption("p")=1  then
				%elemsmpl = %firstperiod
			endif
	endif


	if @isempty(@equaloption("w"))=0 then
			!wildcardlimit = @val(@equaloption("w"))
		else
			!wildcardlimit = 30
	endif


	if @hasoption("q")=1 then
		%freq="q"
		%frequency= "Quarterly frequency"
		else
		%freq="a"
		%frequency= "Annual frequency"
	endif

	if @hasoption("p")=1 then
			if @pagefreq="M" then
				%frequency= "Monthly frequency"
			endif 
			if @pagefreq="D7" then
				%frequency= "Daily frequency (D5)"
			endif 

			if @pagefreq="D7" then
				%frequency= "Daily frequency (D7)"
			endif 

			if @pagefreq="W" then
				%frequency= "Weekly frequency"
			endif 

			if @pagefreq="Q" then
				%frequency= "Quarterly frequency"
			endif 

			if @pagefreq="A" then
				%frequency= "Annual frequency"
			endif 

	endif


'farger til grafene (sort legges til til slutt, se graf nedenfor
	%color1 = "@rgb(0,168,249)"  	'blue
	%color2 = "@rgb(41,126,37)" 	'green
	%color3 = "@rgb(230,22,7)" 		'red
	%color4 = "@rgb(127,127,127)" 	'gray
	%color5 = "@rgb(197,192,33)" 	'orange

'delete object if it exists
	delete(noerr) {%graph}

'auxiliary model object
	%m=@getnextname("zm")
	model {%m}


'check that series exists
	!test=0
	!i=-1
	while !test=0 
		!i=!i+1
		'check first if proper arguments are provided
			if @isempty(%{!i})=1 then
				!test=1
					if !i=0 then
						%prompt="No series has been entered when calling the LINEA-addin.  See the documentation for information about how to use this routine. Type the following in the command window to open the documentation: LINEA ? "
						@uiprompt(%prompt)
						stop
					endif
				else



				'check for ? og * sign
	
					' "*" can be both multiplication and wildcard .... 
					!wildcard=0 'not wildcard unless ...

					%mw=@getnextname("zmw")
					model {%mw}
					{%mw}.append xaux{!i}={%{!i}}
					%seriesmw = {%mw}.@exoglist
					if @instr(%{!i}, "*")>0 then

							if @isempty(%seriesmw)=1 then
								!wildcard=1
								else
								for %serz {%seriesmw}
									if @isobject(%serz)=0 then
										!wildcard=1
									endif
								next
							endif
					endif
					delete  {%mw}


					if @instr(%{!i}, "?")>0 or !wildcard=1 then
						%wflookup=@wflookup(%{!i}, "series")
							'do not continue if wildcard option finds more than x data series
							if @wcount(%wflookup)<=!wildcardlimit then
									%allarguments = %allarguments+ " " +  %wflookup
								else
								%auxstring=@getnextname("wflookupstr")
								string {%auxstring}=%wflookup
								show {%auxstring}
								%prompt=	"The wildcard character "+%{!i}+ " returned more than "+ @str(!wildcardlimit)+ " data series. The LINEA add-in will continue without graphing these series. You may increase the numer of allowed data series to be graphed with the w-option, e.g. LINEA(w=50)."
								@uiprompt(%prompt)
								delete {%auxstring}
							endif
							if @isempty(@trim(%wflookup))=1 then	
								%emptywildcard=%emptywildcard+", " +%{!i}
							endif

						else
							%allarguments = %allarguments+ " " +  %{!i}
					endif	
						
			endif	
	wend

	%emptywildcard=@mid(%emptywildcard,2)

if @wcount(%allarguments)>0 then
		'check that series exists
			!test=0
			!i=-1
			for %arg {%allarguments}
				!i=!i+1
				%{!i}=%arg
				'check first if proper arguments are provided
					if @isempty(%{!i})=1 then
						!test=1
							if !i=0 then
								%prompt="No series has been entered when calling the LINEA-addin.  See the documentation for information about how to use this routine. Type the following in the command window to open the documentation: LINEA ? "
								@uiprompt(%prompt)
								stop
							endif
						else
						
						%pc=@left(%{!i},3)
		
						if @lower(%pc)="@pc" or @lower(@str(@val(%{!i})))<>"na" then
							%line=%line+ " "+%{!i} 
								if @lower(%pc)="@pc" then
								%pctxt="@pc-functions are not scaled."
									if @pagefreq="D7" or @pagefreq="D5"  or @pagefreq="W" then
										'cleanup
												%keep = %graph 'objects to keep
												%after_existing_content = @wlookup("*")
												%to_delete = @wnotin(@lower(%after_existing_content), @lower(%pre_existing_content)) 
												delete {%to_delete}

										@uiprompt("You cannot use @pc-functions on dayly or weekly frequency")
										stop
									endif	
								endif
							else
		
							%line=%line+ " ("+%{!i} +")/@elem("+%{!i}+","+%elemsmpl+") "
						endif
		
						'må legge variablene til modell for å sjekke hva som er variabler
						%series = %series +  " "+%{!i}
						{%m}.append xaux{!i}={%{!i}}
						%seriesm = {%m}.@exoglist
		

		
						'check to see that all variables exist
						if @isempty(%seriesm)=0 then
							for %exv  {%seriesm}
								if @isobject(%exv)=0 then
									delete {%m}
									%pagename=@pagename
									%prompt="The series " +@upper(%exv)+" does not exist in the workfile on page " +@upper(%pagename) +"."
									@uiprompt(%prompt)
									stop
								endif
							next
						endif
		
		
					endif
			next


		if @hasoption("p")=0 then
			'create auxiliary page and copy data
				pagecreate(page={%pageaux}) {%freq} {%firstyear1} {%lastyear}
		
					for %v {%seriesm}
						copy  {%cp}\{%v}   {%pageaux}\{%v}
					next
		endif
		
		'%line - find common scaling point
		smpl {%pagesmpl}
		%group=@getnextname("zgr")
		%groupv = @getnextname("zgrv")
		%smplgr = @pagesmpl
		group {%group}  {%seriesm}
		genr {%groupv}=@rnas({%group})
		'sjekker at det er noen tilfeller der alle gruppene har observasjoner 
		smpl {%pagesmpl} if  {%groupv}=0
		if @obssmpl>0 then
			smpl @all if  {%groupv}<>0
			genr {%groupv}=na
			smpl {%pagesmpl}
			%firstnonna={%groupv}.@first
			%line = @replace(@lower(%line), @lower(%elemsmpl), @lower(%firstnonna))
			%elemsmpl = %firstnonna
		endif
		smpl {%pagesmpl}

		'check for NA at scaling point
		if @hasoption("n")=0 and @isempty(%pctxt)=1 then
			for %sererr {%seriesm}
				%firstv={%sererr}.@first
					if @lower(%firstv)="none" then
							%errseries=%errseries+ " "+@upper(%sererr)
						else
							smpl {%elemsmpl} {%elemsmpl} if {%sererr}<>NA
							if @obssmpl=0 then
										%errseries=%errseries+ " "+@upper(%sererr)
							endif	
					endif
					%errmsg="The following series are NA at point of scaling: "
					smpl {%pagesmpl}
			next
		endif

		
			if @hasoption("n")=0 then
				%graphed = %line
				%indexinfo= "Index, "+%elemsmpl+" = 1."
				else
				%graphed = %series
				%indexinfo= ""
			endif
		
			if @hasoption("x")=1 then
				%xoption="x"
				%xoptionlegend="Left axis="+%0+"."
				else
				%xoption=""
			endif

	
		'make graph-object
'		smpl {%firstyear} {%lastyear}
		smpl {%pagesmpl}
		graph {%graph}.line({%xoption}) {%graphed}


		'legger til feilmelding hvis noen serier ikke kan skaleres
		if @isempty(%errseries)=0 then
			{%graph}.addtext(-0.1, -0.57, font(12), textcolor(@rgb(151,0,0)))  {%errmsg}
			'kutter stringen med variabler hvis den er for lang ...
			if @wcount(%errseries)<5 then
					%errseriesmsg=%errseries
				else
					%errseriesmsg=@wleft(%errseries,4)+" ..."
			endif
			{%graph}.addtext(-0.1, -0.37, font(12), textcolor(@rgb(151,0,0))) {%errseriesmsg}
			!y1 	= -0.6-0.4
			!y2	= -0.37-0.4

			else 
			!y1 	= -0.6
			!y2	= -0.37

		endif
 

		'title
		if @isempty( %emptywildcard)=0 then
			%wildcardmessage="The wildcard(s) "+ %emptywildcard+" did not return any series."	
		endif		

		{%graph}.addtext(-0.1, !y1, font(b,14)) {%frequency}
		{%graph}.addtext(-0.1, !y2, font(12)) {%xoptionlegend} {%indexinfo} {%pctxt} {%wildcardmessage}

		{%graph}.addtext(ac, font(b)) ""
		{%graph}.legend -inbox position(BOTLEFT) display columns(2)
		
		
		'setelem
		for !g=0 to !i
			!elem=!g+1
			if !elem < 6 then
				{%graph}.setelem(!elem) legend(%{!g}) lcolor({%color{!elem}})  linewidth(2)
				else
				{%graph}.setelem(!elem) legend(%{!g}) linewidth(2)
			endif
		next
		
		!blackelement= @wcount(%graphed)
		{%graph}.setelem(!blackelement) lcolor(@rgb(0,0,0))
		
		

		!ys1 = 3.9
		!ys2=4.15
		!ys3=4.3
			'if p-option, need to move text downwards
			if @hasoption("p") then
				!ys1 = 3.9+0.25
				!ys2=4.15+0.25
				!ys3=4.3+0.25
			endif

		if @wcount(%graphed)<5 then
			{%graph}.addtext(-0.2, !ys1, textcolor(@rgb(0,0,0)),  font(Calibri,14) ) _____________________________________________________________
			{%graph}.addtext(-0.2, !ys2, font(8)) LINEA add-in: Type ´LINEA ?´ to open documentation.
			{%graph}.addtext(-0.2, !ys3, font(8)) Options: b= : base period, e.g. b=2015, n : no rescaling, p : plot with current frequency on active workpage, q : quarterly frequency. 

			else
			{%graph}.legend columns(auto)
		endif

		
		'show graph
		if @hasoption("p")=0 then
			copy {%graph} {%cp}\{%graph}
			pagedelete {%pageaux} 
			pageselect {%cp}
		endif
		smpl {%pagesmpl}
		show(max) {%graph}



		'cleanup
				%keep = %graph 'objects to keep
				%after_existing_content = @wlookup("*")
				%to_delete = @wnotin(@lower(%after_existing_content), @lower(%pre_existing_content)) 
				%to_delete = @wnotin(@lower(%to_delete), @lower(%keep)) 'Add the created spool to list of things to keep
				delete {%to_delete}

	else
'	statusline No arguments were provided to the LINEA add-in

	%prompt="No valid series has been entered when calling the LINEA-addin.  See the documentation for information about how to use this routine. Type the following in the command window to open the documentation: LINEA ? "
	@uiprompt(%prompt)
	stop


endif


