## helpers for VCwrapper

#### call documentation
function void VChelp(void)
    
   string VCdir = "@dotdir" ~ "/functions/VCwrapper"
    
if $sysinfo.os=="windows"
  if $sysinfo.wordlen==64 
      string command = "@VCdir" ~ "/64bit/VChelp.exe"
  else
      string command = "@VCdir" ~ "/32bit/VChelp.exe"
      endif
   !  "@command"

else
    
    string command = "@VCdir" ~ "/VCwrapper.pdf"
    ! xdg-open "@command" 
endif  
       
end function


#### plot stuff ##########################################
##########################################################

function void VClistplot(list P "list of time series",            
                      string lwidth[null] "linewidth",
                      string lcolor[null] "linecolor (Hex)",
                      string bcolor[null] "bandcolor (Hex)",
                      string bwidth[null] "bandwidth",  
                         string intens[null] "intensity ⋲ [.0, 1.] " )   
#                         
#### Plot defaults ########################################    
                      string defaultlinewidth = "3"
                      string defaultcolor = "32a852" 
                      string defaultintensity = ".1" 
                      string defaultbandwidth = "1.96"
###########################################################                           
    if !exists(lwidth)
        string lwidth = defaultlinewidth   
    endif
                
    if !exists(lcolor)
        string lcolor = defaultcolor
    endif
    
    if !exists(bcolor)
        string bcolor = lcolor
    endif
    
    if !exists(bwidth)
        string bwidth = defaultbandwidth
    endif
    
    if !exists(intens)
        string intens=defaultintensity
        endif
        
    scalar ncoeffs = nelem(P)
    ncoeffs = ncoeffs / 2             # number of coefficients
    loop i=1..ncoeffs                 # bandplots for all coefficients
        VCplot(P[2*i-1],P[2*i],varname(P[2*i-1]),lwidth,lcolor,bcolor,bwidth,intens)
    endloop
end function

function void VCplot (series coeff "coefficient",
                      series stderr "standard error",
                      string label[null] "label",
                      string lwidth[null] "linewidth",
                      string lcolor[null] "linecolor",
                      string bcolor[null] "bandcolor",
                      string bwidth[null] "bandwidth",
                      string intens[null] "intensity ⋲ [.0, 1.]") 
    if !exists(label)
        string label=varname(coeff)
    endif
    
    if !exists(lwidth)
        string lwidth = "3"    
    endif
                
    if !exists(lcolor)
        string lcolor = "0X32a852"
        else
        lcolor = "0X" ~lcolor
    endif
    
    if !exists(bcolor)
        string bcolor = lcolor
        else
        bcolor = "0X" ~bcolor
    endif
     if !exists(bwidth)
         string bwidth = "1.96"
     endif
     scalar bw =atof(bwidth)  
     

    if !exists(intens)
        string intens="0.1"
    endif
    
    plot coeff
               
       literal set linetype 1 lw "@lwidth"      # line width
       literal set linetype 1 lc rgb "@lcolor"  # line color 
       literal set style fill transparent solid @intens noborder 
                                                # intensity 
       literal set border 4095                  # border type       
       literal set ylabel "@label"              # label
         
      
       options band=coeff,stderr,bw band-style=fill,@bcolor 
                                                # band color
       options time-series with-lines           # line type                                         
       options --single-yaxis                   # all ordinates on one axis 
    end plot --output=display
end function


######################################################


function string VCoptions( string VCoptions[null] "options for VC")
    if !exists(VCoptions)
        string VCoptions=""
        endif
    return VCoptions
end function
 
    
function matrix str2vec(string s)
   # transforms a string with space-separated scalars to a vector.
    strings se=strsplit(s," ")
    matrix V={}
    loop i=1..nelem(se)
	 if !(atof(se[i])^2 >= 0 )
        funcerr "Some variance ratio is not a number. Please correct."
       endif
        V = V ~ atof(se[i])   
     endloop
    return V
end function

function string cleanoutput(const string s)
    # The problem is that the VCtextoutput.txt file 
    # has weird line endings (CR, seemingly MacOS 9)
    # So we cannot directly split on proper newlines.

    string out = ""
    
    # First check whether anything comes before the "Iteration"
    string temp = strsplit(s, "Iteration")[1]
    out += strlen(temp) ? temp : "" 
    
    # Next, skip all the Iteration parts and jump to the summary
    # out += strstr(s, "Accuracy") 
    
    # Discard the file saving echo message at the end...
    out = strsplit(out, "Output saved")[1]
    return out
end function
  

function string fwdsl(string in)
    # replace backward with forward slashes
    return strsub(in, sprintf("\\"), "/")
end function

function void L_VR_errorchk( list L, matrix VR)
    # checks if number of regressors == number of variance ratios
    errorif( rows(VR) > 1 && cols(VR) > 1, "VR input must be vector")
    errorif( nelem(L) != nelem(VR) + 1, "need same number of VRs as regressors")
end function
 
function void storeVCinput(list L, matrix VR, string fname[null])
    # stores the initial varianve ratios and the list comprising the
    # dependent variable and the regressors in a CSV file 
    # "from_gretl_to_VC.csv" that can be  processed by the VCG program.
    # Initial variance ratios are given in the second row before
    # the observations.

   if exists(fname) 
       string fn = strstrip(fname)
       scalar lenfn =strlen(fn)
       string endfn = substr(fn,lenfn-3,lenfn)
       if endfn != ".csv"
           funcerr "file must have csv extension"
           endif
    elif !exists(fname)
        string fname = "from_gretl_to_VC.csv" 
    endif

    # start with the fake obs
    matrix m = 999 ~ 666 ~ vec(VR)'
  
    # actual data
    m |= {$obsdate} ~ {L}
    
    cnameset(m, defarray("date") + varnames(L))
    store "@fname" --matrix=m  # no quiet option possible!
end function

function scalar checkshell(void)
    string setbuf
    outfile --buffer=setbuf
        set 
    end outfile
    strings setparts = strsplit(setbuf, "\n")
    return nelem(instrings(setparts, " shell_ok = 1")) # mind the leading blank!
end function

####




