/*
 * DPUSER function idl2dpuser
 * Arguments: A string pointing to a filename of an IDL script
 * Returns: The IDL script translated to dpuser language
 */

function idl2dpuser, filename {
//filename = "airtovac.pro"

idl = import(filename, /text)

//Convert everything to lower case, since DPUSER is case-sensitive
for i=1, nelements(idl) {
	idl[i] = lower(idl[i])
}

// get function name
functionname = ""
for i=1, nelements(idl) {
print i
  if (strlen(idl[i]) > 10 && idl[i][1:9] == "function ") {
	  j = 10
		while (idl[i][j] != ",") {
		  functionname += idl[i][j]
			j++
		}
		idl[i] += " {"
	}
}

for i=1, nelements(idl) {
  if (strlen(idl[i]) > 4 && idl[i][1:4] == "pro ") {
		nn = nelements(idl[i])
		idl[i] = idl[i][5:nn]
		idl[i] = "procedure " + idl[i] + " {"
//		idl[i] = "procedure " + idl[i][5:nelements(idl[i])] + " {"
	}
}

// Comments in IDL are ; (semicolon), in DPUSER // (C++ style)
replace idl, ";", "//"

// get rid of all those whitespaces...
for i=1, nelements(idl) idl[i] = simplifywhitespace(idl[i])

// skip IDL's line continuation
i = 1
while (i < nelements(idl)) {
if (idl[i] != "") {
  if (right(idl[i], 1) == "$") {
	  idl[i] = idl[i][1:nelements(idl[i])-1]
		j = i + 1;
		while (right(idl[j], 1) == "$") {
	    idl[i] += idl[j][1:nelements(idl[j])-1]
			idl[j] = ""
			j++
		}
		idl[i] += idl[j]
		idl[j] = ""
		i += j-i
		idl[i] = simplifywhitespace(idl[i])
  }
}
	i++
}

// replace "ge" by >= etc.
replace idl, " ge ", " >= "
replace idl, " gt ", " > "
replace idl, " lt ", " < "
replace idl, " le ", " <= "
replace idl, " eq ", " == "
replace idl, " ne ", " != "

// flow control, i.e. begin, end[for,if] etc.
replace idl, " then", ""
replace idl, " begin", " {"
replace idl, "endif", "}"
replace idl, "endfor", "}"
replace idl, "endelse", "}"
replace idl, "end", "}"

// several commands on one line: "&" -> ";"
replace idl, " & ", " ; "

// strings
replace idl, "'", "\""

// replace some function names
replace idl, "n_elements", "nelements"
replace idl, "fltarr", "floatarray"
replace idl, "dblarr", "doublearray"
replace idl, "alog", "ln"
replace idl, "alog10", "log"
replace idl, "on_error", "// on_error"
replace idl, " mod ", " % "


// special values
replace idl, "!radeg", "(180/pi())"
replace idl, "!dpi", "pi()"

// return value
replace idl, "return,", functionname + " = "

// skip the check for number of arguments
i = 1
while (i < nelements(idl)) {
  if (strlen(idl[i]) > 15) {
		if (idl[i][1:14] == "if n_params() ") {
			j = i
			while (idl[j] != "}") {
				idl[j] = "// " + idl[j]
				j++
			}
			idl[j] = "// " + idl[j]
			i += j - i
		}
	}
	i++
}
idl2dpuser = idl
}

