Exemple #1
0
Cell *boolop(Node **a, int n)	/* a[0] || a[1], a[0] && a[1], !a[0] */
{
	Cell *x, *y;
	int i;

	x = execute(a[0]);
	i = istrue(x);
	tempfree(x);
	switch (n) {
	case BOR:
		if (i) return(true);
		y = execute(a[1]);
		i = istrue(y);
		tempfree(y);
		if (i) return(true);
		else return(false);
	case AND:
		if ( !i ) return(false);
		y = execute(a[1]);
		i = istrue(y);
		tempfree(y);
		if (i) return(true);
		else return(false);
	case NOT:
		if (i) return(false);
		else return(true);
	default:	/* can't happen */
		ERROR "unknown boolean operator %d", n FATAL;
	}
	return 0;	/*NOTREACHED*/
}
Exemple #2
0
static const char *ts_luaExec(DWORD *obj, int argc, const char** argv)
{
	// note: does not use Blockland file system atm, allows execution outside game folder, does not support zip
	
	if (argc < 3 || !istrue(argv[2]))
		Printf("Executing %s.", argv[1]);

	if (luaL_loadfile(gL, argv[1]) || lua_pcall(gL, 0, 1, 0))
	{
		showluaerror(gL, argc >= 3 && istrue(argv[2]));
		return "";
	}

	return lua_tostring(gL, -1);
}
Exemple #3
0
void toReadyLTS(thread p)
{
	LTS.ready[LTS.size%MAX]= (thread*)malloc(sizeof(thread));
	*(LTS.ready[LTS.size%MAX]) = p;
	if(LTS.running == NULL || istrue(p.TK)) expropiar(&LTS);
	LTS.size++;
}
Exemple #4
0
int istrue(int i) {
    if (!(strcmp(itoa(i), "0") == 0)) {
        return INT_MAX;
    } else {
        return !istrue(1 == 1);
    }
}
Exemple #5
0
void putsint(int i) {
    if (!istrue(i)) {
        puts("0");
    } else {
        puts(itoa(i));
    }
}
Exemple #6
0
void fun_jmp_true ()
{
    register INT16 offs = getint16 (infile);

    if (istrue())
        fseek(infile, (INT32) offs, SEEK_CUR);
}
Exemple #7
0
extern int getstatus() {
	int s;
	if (pipelength > 1)
		return !istrue();
	s = statuses[0];
	return (s&0xff) ? 1 : (s >> 8) & 0xff;
}
Exemple #8
0
// TorqueScript ConsoleFunction callbacks
static const char *ts_luaEval(DWORD* obj, int argc, const char** argv)
{
	if (luaL_loadbuffer(gL, argv[1], strlen(argv[1]), "input") || lua_pcall(gL, 0, 1, 0))
	{
		showluaerror(gL, argc >= 3 && istrue(argv[2]));
		return "";
	}

	return lua_tostring(gL, -1);
}
Exemple #9
0
void randToTop(amigo * a)
{
	int m = a->top, i=0;
	for(i = 0; i != a->size%MAX ; i++) {
		i%=MAX;
		if(istrue(a->ready[i]->TK)) m = i;
	}
	while(a->ready[m]!= NULL && a->ready[m]->DR == 0 ) m++;
	thread * t = a->ready[a->top%MAX];
	a->ready[a->top%MAX] = a->ready[m];
	a->ready[m] = t;
}
Exemple #10
0
Cell *dopa2(Node **a, int n)	/* a[0], a[1] { a[2] } */
{
	Cell *x;
	int pair;

	pair = (int) a[3];
	if (pairstack[pair] == 0) {
		x = execute(a[0]);
		if (istrue(x))
			pairstack[pair] = 1;
		tempfree(x);
	}
	if (pairstack[pair] == 1) {
		x = execute(a[1]);
		if (istrue(x))
			pairstack[pair] = 0;
		tempfree(x);
		x = execute(a[2]);
		return(x);
	}
	return(false);
}
Exemple #11
0
Cell *condexpr(Node **a, int n)	/* a[0] ? a[1] : a[2] */
{
	Cell *x;

	x = execute(a[0]);
	if (istrue(x)) {
		tempfree(x);
		x = execute(a[1]);
	} else {
		tempfree(x);
		x = execute(a[2]);
	}
	return(x);
}
Exemple #12
0
Cell *ifstat(Node **a, int n)	/* if (a[0]) a[1]; else a[2] */
{
	Cell *x;

	x = execute(a[0]);
	if (istrue(x)) {
		tempfree(x);
		x = execute(a[1]);
	} else if (a[2] != 0) {
		tempfree(x);
		x = execute(a[2]);
	}
	return(x);
}
Exemple #13
0
Cell *pastat(Node **a, int n)	/* a[0] { a[1] } */
{
	Cell *x;

	if (a[0] == 0)
		x = execute(a[1]);
	else {
		x = execute(a[0]);
		if (istrue(x)) {
			tempfree(x);
			x = execute(a[1]);
		}
	}
	return x;
}
Exemple #14
0
bool FromStringImpl<bool>(const char* data, size_t len) {
    if (len == 1) {
        if (data[0] == '0') {
            return false;
        } else if (data[0] == '1') {
            return true;
        }
    }
    TStringBuf buf(data, len);
    if (istrue(buf)) {
        return true;
    } else if (isfalse(buf)) {
        return false;
    }
    ythrow TFromStringException() << "cannot parse bool(" << Stroka(data, len) << ")";
}
Exemple #15
0
Cell *dostat(Node **a, int n)	/* do a[0]; while(a[1]) */
{
	Cell *x;

	for (;;) {
		x = execute(a[0]);
		if (isbreak(x))
			return true;
		if (isnext(x) || isnextfile(x) || isexit(x) || isret(x))
			return(x);
		tempfree(x);
		x = execute(a[1]);
		if (!istrue(x))
			return(x);
		tempfree(x);
	}
}
Exemple #16
0
Cell *whilestat(Node **a, int n)	/* while (a[0]) a[1] */
{
	Cell *x;

	for (;;) {
		x = execute(a[0]);
		if (!istrue(x))
			return(x);
		tempfree(x);
		x = execute(a[1]);
		if (isbreak(x)) {
			x = true;
			return(x);
		}
		if (isnext(x) || isexit(x) || isret(x))
			return(x);
		tempfree(x);
	}
}
Exemple #17
0
/* exitstatus -- turn a status list into an exit(2) value */
extern int exitstatus(List *status) {
	Term *term;
	char *s;
	unsigned long n;

	if (status == NULL)
		return 0;
	if (status->next != NULL)
		return istrue(status) ? 0 : 1;
	term = status->term;
	if (term->closure != NULL)
		return 1;

	s = term->str;
	if (*s == '\0')
		return 0;
	n = strtol(s, &s, 0);
	if (*s != '\0' || n > 255)
		return 1;
	return n;
}
Exemple #18
0
Cell *forstat(Node **a, int n)	/* for (a[0]; a[1]; a[2]) a[3] */
{
	Cell *x;

	x = execute(a[0]);
	tempfree(x);
	for (;;) {
		if (a[1]!=0) {
			x = execute(a[1]);
			if (!istrue(x)) return(x);
			else tempfree(x);
		}
		x = execute(a[3]);
		if (isbreak(x))		/* turn off break */
			return true;
		if (isnext(x) || isexit(x) || isret(x))
			return(x);
		tempfree(x);
		x = execute(a[2]);
		tempfree(x);
	}
}
/*
 * As in Impcore, the evaluator is still a [[switch]]:
 * <eval.c>=
 */
Value eval(Exp e, Env env) {
    checkoverflow(1000000 * sizeof(char *)); /* OMIT */
    switch (e->alt) {
    case LITERAL:
        /*
         * <evaluate [[e->u.literal]] and return the result>=
         */
        return e->u.literal;
    case VAR:   
        /*
         * Variables
         * 
         * Variable lookup and assignment are simpler than in
         * Impcore, because we have only one rule each. We
         * implement rho(x) by find(x, rho), we implement sigma
         * (l) by [[*]]l, and we update sigma(l) by assigning to
         * [[*]]l. [*]
         * <evaluate [[e->u.var]] and return the result>=
         */
        if (find(e->u.var, env) == NULL)
            error("variable %n not found", e->u.var);
        return *find(e->u.var, env);
    case SET:
        /*
         * [*] [*]
         * <evaluate [[e->u.set]] and return the result>=
         */
        if (find(e->u.set.name, env) == NULL)
            error("set unbound variable %n", e->u.set.name);
        return *find(e->u.set.name, env) = eval(e->u.set.exp, env);
    case IFX:
        /*
         * Conditional, iteration, and sequence
         * 
         * The implementations of the control-flow operations
         * are very much as in Impcore. We don't bother
         * repeating the operational semantics.
         * <evaluate [[e->u.ifx]] and return the result>=
         */
        if (istrue(eval(e->u.ifx.cond, env)))
            return eval(e->u.ifx.true, env);
        else
            return eval(e->u.ifx.false, env);
    case WHILEX:
        /*
         * <evaluate [[e->u.whilex]] and return the result>=
         */
        while (istrue(eval(e->u.whilex.cond, env)))
            eval(e->u.whilex.body, env);
        return falsev;
    case BEGIN:
        /*
         * <evaluate [[e->u.begin]] and return the result>=
         */
        {
            Explist el;
            Value v = falsev;
            for (el = e->u.begin; el; el = el->tl)
                v = eval(el->hd, env);
            return v;
        }
    case APPLY:
        /*
         * We handle application of primitives separately from
         * application of closures.
         * 
         * <evaluate [[e->u.apply]] and return the result>=
         */
        {
            Value     f  = eval    (e->u.apply.fn,      env);
            Valuelist vl = evallist(e->u.apply.actuals, env);

            switch (f.alt) {
            case PRIMITIVE:
                /*
                 * Applying a primitive is simpler than in our Impcore
                 * interpreter because we represent primitives by
                 * function pointers and tags. The tag is passed to the
                 * function, along with the arguments ([[vl]]), plus the
                 * abstract syntax [[e]], which is used in error
                 * messages.
                 * <apply [[f.u.primitive]] to [[vl]] and return the result>=
                 */
                return f.u.primitive.function(e, f.u.primitive.tag, vl);
            case CLOSURE:
                /*
                 * To apply a closure, we extend the closure's
                 * environment (rho_c in the operational semantics) with
                 * the bindings for the formal variables and then
                 * evaluate the body in that environment.
                 * <apply [[f.u.closure]] to [[vl]] and return the result>=
                 */
                {
                    Namelist nl = f.u.closure.lambda.formals;
                    checkargc(e, lengthNL(nl), lengthVL(vl));
                    return eval(f.u.closure.lambda.body,
                                bindalloclist(nl, vl, f.u.closure.env));
                }
            default:
                error("%e evaluates to non-function %v in %e", e->u.apply.fn, f,
                                                                             e);
            }
        }
    case LETX:
        /*
         * Let, let*, and letrec
         * 
         * Each expression in the [[let]] family uses its
         * internal names and expressions to create a new
         * environment, then evaluates the body in that
         * environment. The rules for creating the environment
         * depend on the keyword.
         * <evaluate [[e->u.letx]] and return the result>=
         */
        switch (e->u.letx.let) {
        case LET:
            /*
             * <if [[e->u.letx.nl]] contains a duplicate, complain of error in
                                                                       [[let]]>=
             */
            if (duplicatename(e->u.letx.nl) != NULL)
                error("bound name %n appears twice in let", duplicatename(e->
                                                                    u.letx.nl));
            /*
             * A \xlet expression evaluates the expressions to be
             * bound, then binds them all at once. The functions
             * [[evallist]] and [[bindalloclist]] do all the work.
             * <extend [[env]] by simultaneously binding [[el]] to [[nl]]>=
             */
            env = bindalloclist(e->u.letx.nl, evallist(e->u.letx.el, env), env);
            break;
        case LETSTAR:
            /*
             * A \xletstar expression binds a new name as each
             * expression is evaluated.
             * 
             * <extend [[env]] by sequentially binding [[el]] to [[nl]]>=
             */
            {
                Namelist nl;
                Explist el;

                for (nl = e->u.letx.nl, el = e->u.letx.el;
                     nl && el;
                     nl = nl->tl, el = el->tl)
                    env = bindalloc(nl->hd, eval(el->hd, env), env);
                assert(nl == NULL && el == NULL);
            }
            break;
        case LETREC:
            /*
             * <if [[e->u.letx.nl]] contains a duplicate, complain of error in
                                                                    [[letrec]]>=
             */
            if (duplicatename(e->u.letx.nl) != NULL)
                error("bound name %n appears twice in letrec", duplicatename(e->
                                                                    u.letx.nl));
            /*
             * Finally, \xletrec must bind each name to a location
             * before evaluating any of the expressions. The initial
             * contents of the new locations are unspecified. To be
             * faithful to the semantics, we compute all the values
             * before storing any of them.
             * <extend [[env]] by recursively binding [[el]] to [[nl]]>=
             */
            {
                Namelist nl;
                Valuelist vl;

                for (nl = e->u.letx.nl; nl; nl = nl->tl)    
                    env = bindalloc(nl->hd, unspecified(), env);
                vl = evallist(e->u.letx.el, env);
                for (nl = e->u.letx.nl;
                     nl && vl;
                     nl = nl->tl, vl = vl->tl)
                    *find(nl->hd, env) = vl->hd;
            }
            break;
        default:
            assert(0);
        }
        return eval(e->u.letx.body, env);
    case LAMBDAX:
        /*
         * Closures and function application
         * 
         * Wrapping a closure is simple; we need only to check
         * for duplicate names.
         * <evaluate [[e->u.lambdax]] and return the result>=
         */
        /*
         * Error checking
         * 
         * Here are a few bits of error checking that were
         * omitted from Chapter [->].
         * <if [[e->u.lambdax.formals]] contains a duplicate, call [[error]]>=
         */
        if (duplicatename(e->u.lambdax.formals) != NULL)
            error("formal parameter %n appears twice in lambda",
                  duplicatename(e->u.lambdax.formals));
        return mkClosure(e->u.lambdax, env);
    }
Exemple #20
0
object_t *eval_if(object_t *env, object_t *check, object_t *yes,
                 object_t *no) {
    return istrue(eval(check, env)) ? yes : no;
}
Exemple #21
0
extern bool walk(Node *n, bool parent) {
top:	sigchk();
	if (n == NULL) {
		if (!parent)
			exit(0);
		set(TRUE);
		return TRUE;
	}
	switch (n->type) {
	case nArgs: case nBackq: case nConcat: case nCount:
	case nFlat: case nLappend: case nRedir: case nVar:
	case nVarsub: case nWord:
		exec(glob(glom(n)), parent);	/* simple command */
		break;
	case nBody:
		walk(n->u[0].p, TRUE);
		WALK(n->u[1].p, parent);
		/* WALK doesn't fall through */
	case nNowait: {
		int pid;
		if ((pid = rc_fork()) == 0) {
#if defined(RC_JOB) && defined(SIGTTOU) && defined(SIGTTIN) && defined(SIGTSTP)
			setsigdefaults(FALSE);
			rc_signal(SIGTTOU, SIG_IGN);	/* Berkeleyized version: put it in a new pgroup. */
			rc_signal(SIGTTIN, SIG_IGN);
			rc_signal(SIGTSTP, SIG_IGN);
			setpgid(0, getpid());
#else
			setsigdefaults(TRUE);		/* ignore SIGINT, SIGQUIT, SIGTERM */
#endif
			mvfd(rc_open("/dev/null", rFrom), 0);
			walk(n->u[0].p, FALSE);
			exit(getstatus());
		}
		if (interactive)
			fprint(2, "%d\n", pid);
		varassign("apid", word(nprint("%d", pid), NULL), FALSE);
		redirq = NULL; /* kill pre-redir queue */
		break;
	}
	case nAndalso: {
		bool oldcond = cond;
		cond = TRUE;
		if (walk(n->u[0].p, TRUE)) {
			cond = oldcond;
			WALK(n->u[1].p, parent);
		} else
			cond = oldcond;
		break;
	}
	case nOrelse: {
		bool oldcond = cond;
		cond = TRUE;
		if (!walk(n->u[0].p, TRUE)) {
			cond = oldcond;
			WALK(n->u[1].p, parent);
		} else
			cond = oldcond;
		break;
	}
	case nBang:
		set(!walk(n->u[0].p, TRUE));
		break;
	case nIf: {
		bool oldcond = cond;
		Node *true_cmd = n->u[1].p, *false_cmd = NULL;
		if (true_cmd != NULL && true_cmd->type == nElse) {
			false_cmd = true_cmd->u[1].p;
			true_cmd = true_cmd->u[0].p;
		}
		cond = TRUE;
		if (!walk(n->u[0].p, TRUE))
			true_cmd = false_cmd; /* run the else clause */
		cond = oldcond;
		WALK(true_cmd, parent);
	}
	case nWhile: {
		Jbwrap j;
		Edata jbreak;
		Estack e1, e2;
		bool testtrue, oldcond = cond;
		cond = TRUE;
		if (!walk(n->u[0].p, TRUE)) { /* prevent spurious breaks inside test */
			cond = oldcond;
			break;
		}
		if (sigsetjmp(j.j, 1))
			break;
		jbreak.jb = &j;
		except(eBreak, jbreak, &e1);
		do {
			Edata block;
			block.b = newblock();
			cond = oldcond;
			except(eArena, block, &e2);
			walk(n->u[1].p, TRUE);
			testtrue = walk(n->u[0].p, TRUE);
			unexcept(); /* eArena */
			cond = TRUE;
		} while (testtrue);
		cond = oldcond;
		unexcept(); /* eBreak */
		break;
	}
	case nForin: {
		List *l, *var = glom(n->u[0].p);
		Jbwrap j;
		Estack e1, e2;
		Edata jbreak;
		if (sigsetjmp(j.j, 1))
			break;
		jbreak.jb = &j;
		except(eBreak, jbreak, &e1);
		for (l = listcpy(glob(glom(n->u[1].p)), nalloc); l != NULL; l = l->n) {
			Edata block;
			assign(var, word(l->w, NULL), FALSE);
			block.b = newblock();
			except(eArena, block, &e2);
			walk(n->u[2].p, TRUE);
			unexcept(); /* eArena */
		}
		unexcept(); /* eBreak */
		break;
	}
	case nSubshell:
		if (dofork(TRUE)) {
			setsigdefaults(FALSE);
			walk(n->u[0].p, FALSE);
			rc_exit(getstatus());
		}
		break;
	case nAssign:
		if (n->u[0].p == NULL)
			rc_error("null variable name");
		assign(glom(n->u[0].p), glob(glom(n->u[1].p)), FALSE);
		set(TRUE);
		break;
	case nPipe:
		dopipe(n);
		break;
	case nNewfn: {
		List *l = glom(n->u[0].p);
		if (l == NULL)
			rc_error("null function name");
		while (l != NULL) {
			if (dashex)
				prettyprint_fn(2, l->w, n->u[1].p);
			fnassign(l->w, n->u[1].p);
			l = l->n;
		}
		set(TRUE);
		break;
	}
	case nRmfn: {
		List *l = glom(n->u[0].p);
		while (l != NULL) {
			if (dashex)
				fprint(2, "fn %S\n", l->w);
			fnrm(l->w);
			l = l->n;
		}
		set(TRUE);
		break;
	}
	case nDup:
		redirq = NULL;
		break; /* Null command */
	case nMatch: {
		List *a = glob(glom(n->u[0].p)), *b = glom(n->u[1].p);
		if (dashex)
			fprint(2, (a != NULL && a->n != NULL) ? "~ (%L) %L\n" : "~ %L %L\n", a, " ", b, " ");
		set(lmatch(a, b));
		break;
	}
	case nSwitch: {
		List *v = glom(n->u[0].p);
		while (1) {
			do {
				n = n->u[1].p;
				if (n == NULL)
					return istrue();
			} while (n->u[0].p == NULL || n->u[0].p->type != nCase);
			if (lmatch(v, glom(n->u[0].p->u[0].p))) {
				for (n = n->u[1].p; n != NULL && (n->u[0].p == NULL || n->u[0].p->type != nCase); n = n->u[1].p)
					walk(n->u[0].p, TRUE);
				break;
			}
		}
		break;
	}
	case nPre: {
		List *v;
		if (n->u[0].p->type == nRedir || n->u[0].p->type == nDup) {
			if (redirq == NULL && !dofork(parent)) /* subshell on first preredir */
				break;
			setsigdefaults(FALSE);
			qredir(n->u[0].p);
			if (!haspreredir(n->u[1].p))
				doredirs(); /* no more preredirs, empty queue */
			walk(n->u[1].p, FALSE);
			rc_exit(getstatus());
			/* NOTREACHED */
		} else if (n->u[0].p->type == nAssign) {
			if (isallpre(n->u[1].p)) {
				walk(n->u[0].p, TRUE);
				WALK(n->u[1].p, parent);
			} else {
				Estack e;
				Edata var;
				v = glom(n->u[0].p->u[0].p);
				assign(v, glob(glom(n->u[0].p->u[1].p)), TRUE);
				var.name = v->w;
				except(eVarstack, var, &e);
				walk(n->u[1].p, parent);
				varrm(v->w, TRUE);
				unexcept(); /* eVarstack */
			}
		} else
			panic("unexpected node in preredir section of walk");
		break;
	}
	case nBrace:
		if (n->u[1].p == NULL) {
			WALK(n->u[0].p, parent);
		} else if (dofork(parent)) {
			setsigdefaults(FALSE);
			walk(n->u[1].p, TRUE); /* Do redirections */
			redirq = NULL;   /* Reset redirection queue */
			walk(n->u[0].p, FALSE); /* Do commands */
			rc_exit(getstatus());
			/* NOTREACHED */
		}
		break;
	case nEpilog:
		qredir(n->u[0].p);
		if (n->u[1].p != NULL) {
			WALK(n->u[1].p, parent); /* Do more redirections. */
		} else {
			doredirs();	/* Okay, we hit the bottom. */
		}
		break;
	case nNmpipe:
		rc_error("named pipes cannot be executed as commands");
		/* NOTREACHED */
	default:
		panic("unknown node in walk");
		/* NOTREACHED */
	}
	return istrue();
}
Exemple #22
0
void reader_navo_standard(char* fname, int fid, obsmeta* meta, model* m, observations* obs)
{
    int addbias = ADDBIAS_DEF;
    int ncid;
    int dimid_nobs;
    size_t nobs_local;
    int varid_lon, varid_lat, varid_sst, varid_sstb, varid_error, varid_time;
    double* lon = NULL;
    double* lat = NULL;
    double* sst = NULL;
    double* sstb = NULL;
    double* error_std = NULL;
    double* time = NULL;
    int year, month, day;
    char tunits[MAXSTRLEN];
    size_t tunits_len;
    double tunits_multiple, tunits_offset;
    char* basename;
    int model_vid;
    int k, i;

    for (i = 0; i < meta->npars; ++i) {
        if (strcasecmp(meta->pars[i].name, "ADDBIAS") == 0)
            addbias = (istrue(meta->pars[i].value)) ? 1 : 0;
        else
            enkf_quit("unknown PARAMETER \"%s\"\n", meta->pars[i].name);
    }
    enkf_printf("        ADDBIAS = %s\n", (addbias) ? "YES" : "NO");

    basename = strrchr(fname, '/');
    if (basename == NULL)
        basename = fname;
    else
        basename += 1;

    ncw_open(fname, NC_NOWRITE, &ncid);
    ncw_inq_dimid(fname, ncid, (ncw_dim_exists(ncid, "nobs")) ? "nobs" : "length", &dimid_nobs);
    ncw_inq_dimlen(fname, ncid, dimid_nobs, &nobs_local);
    enkf_printf("        nobs = %u\n", (unsigned int) nobs_local);

    if (nobs_local == 0) {
        ncw_close(fname, ncid);
        return;
    }

    ncw_inq_varid(fname, ncid, "lon", &varid_lon);
    lon = malloc(nobs_local * sizeof(double));
    ncw_get_var_double(fname, ncid, varid_lon, lon);

    ncw_inq_varid(fname, ncid, "lat", &varid_lat);
    lat = malloc(nobs_local * sizeof(double));
    ncw_get_var_double(fname, ncid, varid_lat, lat);

    ncw_inq_varid(fname, ncid, "sst", &varid_sst);
    sst = malloc(nobs_local * sizeof(double));
    ncw_get_var_double(fname, ncid, varid_sst, sst);

    if (addbias) {
        ncw_inq_varid(fname, ncid, "SST_bias", &varid_sstb);
        sstb = malloc(nobs_local * sizeof(double));
        ncw_get_var_double(fname, ncid, varid_sstb, sstb);
    }

    ncw_inq_varid(fname, ncid, "error", &varid_error);
    error_std = malloc(nobs_local * sizeof(double));
    ncw_get_var_double(fname, ncid, varid_error, error_std);

    ncw_inq_varid(fname, ncid, "GMT_time", &varid_time);
    time = malloc(nobs_local * sizeof(double));
    ncw_get_var_double(fname, ncid, varid_time, time);
    ncw_inq_attlen(fname, ncid, varid_time, "units", &tunits_len);
    ncw_get_att_text(fname, ncid, varid_time, "units", tunits);
    basename[13] = 0;
    if (!str2int(&basename[11], &day))
        enkf_quit("NAVO reader: could not convert file name \"%s\" to date", fname);
    basename[11] = 0;
    if (!str2int(&basename[9], &month))
        enkf_quit("NAVO reader: could not convert file name \"%s\" to date", fname);
    basename[9] = 0;
    if (!str2int(&basename[5], &year))
        enkf_quit("NAVO reader: could not convert file name \"%s\" to date", fname);
    snprintf(&tunits[tunits_len], MAXSTRLEN - tunits_len, " since %4d-%02d-%02d", year, month, day);

    ncw_close(fname, ncid);

    tunits_convert(tunits, &tunits_multiple, &tunits_offset);

    model_vid = model_getvarid(m, obs->obstypes[obstype_getid(obs->nobstypes, obs->obstypes, meta->type)].varname, 1);
    k = grid_gettoplayerid(model_getvargrid(m, model_vid));

    for (i = 0; i < (int) nobs_local; ++i) {
        observation* o;
        obstype* ot;

        obs_checkalloc(obs);
        o = &obs->data[obs->nobs];

        o->product = st_findindexbystring(obs->products, meta->product);
        assert(o->product >= 0);
        o->type = obstype_getid(obs->nobstypes, obs->obstypes, meta->type);
        assert(o->type >= 0);
        ot = &obs->obstypes[o->type];
        o->instrument = st_add_ifabscent(obs->instruments, "AVHRR", -1);
        o->id = obs->nobs;
        o->fid = fid;
        o->batch = 0;
        o->value = (addbias) ? sst[i] + sstb[i] : sst[i];
        o->std = error_std[i];
        o->lon = lon[i];
        o->lat = lat[i];
        o->depth = 0.0;
        o->status = model_xy2fij(m, model_vid, o->lon, o->lat, &o->fi, &o->fj);
        if (!obs->allobs && o->status == STATUS_OUTSIDEGRID)
            continue;
        if ((o->status == STATUS_OK) && (o->lon <= ot->xmin || o->lon >= ot->xmax || o->lat <= ot->ymin || o->lat >= ot->ymax || o->depth <= ot->zmin || o->depth >= ot->zmax))
            o->status = STATUS_OUTSIDEOBSDOMAIN;
        o->fk = (double) k;
        o->date = time[i] * tunits_multiple + tunits_offset;
        o->aux = -1;

        obs->nobs++;
    }

    free(lon);
    free(lat);
    free(sst);
    if (addbias)
        free(sstb);
    free(error_std);
    free(time);
}
/* eval.c 143a */
Value eval(Exp e, Env env) {
    checkoverflow(1000000 * sizeof(char *)); /* OMIT */
    switch (e->alt) {
    case LITERAL:
        /* evaluate [[e->u.literal]] and return the result 143b */
        return e->u.literal;
    case VAR:
        /* evaluate [[e->u.var]] and return the result 143c */
        if (find(e->u.var, env) == NULL)
            error("variable %n not found", e->u.var);
        return *find(e->u.var, env);
    case SET:
        /* evaluate [[e->u.set]] and return the result 143d */
        if (find(e->u.set.name, env) == NULL)
            error("set unbound variable %n", e->u.set.name);
        return *find(e->u.set.name, env) = eval(e->u.set.exp, env);
    case IFX:
        /* evaluate [[e->u.ifx]] and return the result 147a */
        if (istrue(eval(e->u.ifx.cond, env)))
            return eval(e->u.ifx.true, env);
        else
            return eval(e->u.ifx.false, env);
    case WHILEX:
        /* evaluate [[e->u.whilex]] and return the result 147b */
        while (istrue(eval(e->u.whilex.cond, env)))
            eval(e->u.whilex.body, env);
        return falsev;
    case BEGIN:
        /* evaluate [[e->u.begin]] and return the result 147c */
    {
        Explist el;
        Value v = falsev;
        for (el = e->u.begin; el; el = el->tl)
            v = eval(el->hd, env);
        return v;
    }
    case APPLY:
        /* evaluate [[e->u.apply]] and return the result 144b */
    {
        Value     f  = eval    (e->u.apply.fn,      env);
        Valuelist vl = evallist(e->u.apply.actuals, env);

        switch (f.alt) {
        case PRIMITIVE:

            /* apply [[f.u.primitive]] to [[vl]] and return the result 144d */
            return f.u.primitive.function(e, f.u.primitive.tag, vl);
        case CLOSURE:
            /* apply [[f.u.closure]] to [[vl]] and return the result 144e */
        {
            Namelist nl = f.u.closure.lambda.formals;
            checkargc(e, lengthNL(nl), lengthVL(vl));
            return eval(f.u.closure.lambda.body,
                        bindalloclist(nl, vl, f.u.closure.env));
        }
        default:
            error("%e evaluates to non-function %v in %e", e->u.apply.fn, f,
                  e);
        }
    }
    case LETX:
        /* evaluate [[e->u.letx]] and return the result 145c */
        switch (e->u.letx.let) {
        case LET:

            /* if [[e->u.letx.nl]] contains a duplicate, complain of error in [[let]] 715b */
            if (duplicatename(e->u.letx.nl) != NULL)
                error("bound name %n appears twice in let", duplicatename(e->
                        u.letx.nl));
            /* extend [[env]] by simultaneously binding [[el]] to [[nl]] 145d */
            env = bindalloclist(e->u.letx.nl, evallist(e->u.letx.el, env), env);
            break;
        case LETSTAR:
            /* extend [[env]] by sequentially binding [[el]] to [[nl]] 146a */
        {
            Namelist nl;
            Explist el;

            for (nl = e->u.letx.nl, el = e->u.letx.el;
                    nl && el;
                    nl = nl->tl, el = el->tl)
                env = bindalloc(nl->hd, eval(el->hd, env), env);
            assert(nl == NULL && el == NULL);
        }
        break;
        case LETREC:

            /* if [[e->u.letx.nl]] contains a duplicate, complain of error in [[letrec]] 715c */
            if (duplicatename(e->u.letx.nl) != NULL)
                error("bound name %n appears twice in letrec", duplicatename(e->
                        u.letx.nl));
            /* extend [[env]] by recursively binding [[el]] to [[nl]] 146b */
            {
                Namelist nl;
                Valuelist vl;

                for (nl = e->u.letx.nl; nl; nl = nl->tl)
                    env = bindalloc(nl->hd, unspecified(), env);
                vl = evallist(e->u.letx.el, env);
                for (nl = e->u.letx.nl;
                        nl && vl;
                        nl = nl->tl, vl = vl->tl)
                    *find(nl->hd, env) = vl->hd;
            }
            break;
        default:
            assert(0);
        }
        return eval(e->u.letx.body, env);
    case LAMBDAX:
        /* evaluate [[e->u.lambdax]] and return the result 144a */

        /* if [[e->u.lambdax.formals]] contains a duplicate, call [[error]] 715a */
        if (duplicatename(e->u.lambdax.formals) != NULL)
            error("formal parameter %n appears twice in lambda",
                  duplicatename(e->u.lambdax.formals));
        return mkClosure(e->u.lambdax, env);
    }
Exemple #24
0
/* eval -- evaluate a list, producing a list */
extern List *eval(List *list0, Binding *binding0, int flags) {
	Closure *volatile cp;
	List *fn;

	if (++evaldepth >= maxevaldepth)
		fail("es:eval", "max-eval-depth exceeded");

	Ref(List *, list, list0);
	Ref(Binding *, binding, binding0);
	Ref(char *, funcname, NULL);

restart:
	if (list == NULL) {
		RefPop3(funcname, binding, list);
		--evaldepth;
		return true;
	}
	assert(list->term != NULL);

	if ((cp = getclosure(list->term)) != NULL) {
		switch (cp->tree->kind) {
		    case nPrim:
			assert(cp->binding == NULL);
			list = prim(cp->tree->u[0].s, list->next, binding, flags);
			break;
		    case nThunk:
			list = walk(cp->tree->u[0].p, cp->binding, flags);
			break;
		    case nLambda:
			ExceptionHandler

				Push p;
				Ref(Tree *, tree, cp->tree);
				Ref(Binding *, context,
					       bindargs(tree->u[0].p,
							list->next,
							cp->binding));
				if (funcname != NULL)
					varpush(&p, "0",
						    mklist(mkterm(funcname,
								  NULL),
							   NULL));
				list = walk(tree->u[1].p, context, flags);
				if (funcname != NULL)
					varpop(&p);
				RefEnd2(context, tree);
	
			CatchException (e)

				if (termeq(e->term, "return")) {
					list = e->next;
					goto done;
				}
				throw(e);

			EndExceptionHandler
			break;
		    case nList: {
			list = glom(cp->tree, cp->binding, TRUE);
			list = append(list, list->next);
			goto restart;
		    }
		    default:
			panic("eval: bad closure node kind %d",
			      cp->tree->kind);
		    }
		goto done;
	}

	/* the logic here is duplicated in $&whatis */

	Ref(char *, name, getstr(list->term));
	fn = varlookup2("fn-", name, binding);
	if (fn != NULL) {
		funcname = name;
		list = append(fn, list->next);
		RefPop(name);
		goto restart;
	}
	if (isabsolute(name)) {
		char *error = checkexecutable(name);
		if (error != NULL)
			fail("$&whatis", "%s: %s", name, error);
		list = forkexec(name, list, flags & eval_inchild);
		RefPop(name);
		goto done;
	}
	RefEnd(name);

	fn = pathsearch(list->term);
	if (fn != NULL && fn->next == NULL
	    && (cp = getclosure(fn->term)) == NULL) {
		char *name = getstr(fn->term);
		list = forkexec(name, list, flags & eval_inchild);
		goto done;
	}

	list = append(fn, list->next);
	goto restart;

done:
	--evaldepth;
	if ((flags & eval_exitonfalse) && !istrue(list))
		exit(exitstatus(list));
	RefEnd2(funcname, binding);
	RefReturn(list);
}
Exemple #25
0
 Mm check_order(Mm n_in, i_o_t, Mm& n_out__o, Mm& w__o, Mm& trivalwin__o) {
   begin_scope
   n_in.setname("n_in"); 
   dMm(n_out); dMm(w); dMm(trivalwin); 
   
   call_stack_begin;
   // nargin, nargout entry code
   double old_nargin=nargin_val; if (!nargin_set) nargin_val=1.0;
   nargin_set=0;
   double old_nargout=nargout_val; if (!nargout_set) nargout_val=3.0;
   nargout_set=0;
   
   // translated code
   
   //CHECK_ORDER Checks the order passed to the window functions.
   // [N,W,TRIVALWIN] = CHECK_ORDER(N_ESTIMATE) will round N_ESTIMATE to the
   // nearest integer if it is not alreay an integer. In special cases (N is [],
   // 0, or 1), TRIVALWIN will be set to flag that W has been modified.
   
   //   Copyright 1988-2002 The MathWorks, Inc.
   //   $Revision: 1.6 $  $Date: 2002/04/15 01:07:36 $
   
   w = nop_M;
   trivalwin = 0.0;
   
   // Special case of negative orders:
   if (istrue(n_in<0.0)) {
     error(TM("Order cannot be less than zero."));
   }
   
   // Check if order is already an integer or empty
   // If not, round to nearest integer.
   if (istrue(isempty(n_in))||istrue(n_in==floor(n_in))) {
     n_out = n_in;
   } else {
     
     n_out = round(n_in);
     warning(TM("Rounding order to nearest integer."));
   }
   
   // Special cases:
   if (istrue(isempty(n_out))||istrue(n_out==0.0)) {
     w = zeros(0.0,1.0);
     // Empty matrix: 0-by-1
     trivalwin = 1.0;
     
   } else
   if (istrue(n_out==1.0)) {
     w = 1.0;
     trivalwin = 1.0;
     
   }
   
   call_stack_end;
   
   // nargin, nargout exit code
   nargin_val=old_nargin; nargout_val=old_nargout;
   
   // function exit code
   n_in.setname(NULL); 
   n_out__o=n_out; w__o=w; trivalwin__o=trivalwin; 
   return x_M;
   end_scope
 }
Exemple #26
0
 Mm AdcDynTest(Mm ADout, Mm fclk, Mm numbit, Mm NFFT, Mm V, Mm code, i_o_t, Mm& SNR__o, Mm& SINAD__o, Mm& SFDR__o, \
    Mm& ENOB__o, Mm& y__o) {
   begin_scope
   ADout.setname("ADout"); fclk.setname("fclk"); numbit.setname("numbit"); NFFT.setname("NFFT"); V.setname("V");  \
     code.setname("code"); 
   dMm(SNR); dMm(SINAD); dMm(SFDR); dMm(ENOB); dMm(y); dMm(ad_len_N); dMm(maxADout); dMm(AmpMax); dMm(t1); dMm(AmpMin) \
     ; dMm(t2); dMm(Vpp); dMm(ADout_w); dMm(AA); dMm(ad_len); dMm(ADout_spect); dMm(ADout_dB); dMm(maxdB); dMm(fin_v) \
     ; dMm(fin); dMm(freq_fin); dMm(data_ref); dMm(n); dMm(n_AdcDynTest_v0); dMm(data_ref_w); dMm(data_ref_spect);  \
     dMm(data_ref_dB); dMm(ref_dB); dMm(span); dMm(spanh_har); dMm(span_s); dMm(spectP); dMm(Pdc); dMm(Pdc_dB); dMm( \
     l); dMm(u); dMm(Ps); dMm(Ps_dB); dMm(Fh); dMm(Ph); dMm(Harbin); dMm(Ph_dB); dMm(har_num); dMm(har_num_AdcDynTest_v1) \
     ; dMm(tone); dMm(har_peak); dMm(har_bin); dMm(spectP_temp); dMm(i_); dMm(i_AdcDynTest_v2); dMm(disturb_len);  \
     dMm(spectP_disturb); dMm(Harbin_disturb); dMm(findSpac); dMm(findSpan); dMm(findStart); dMm(i_AdcDynTest_v3);  \
     dMm(spectP_disturb_peak); dMm(num); dMm(array_flag); dMm(jj); dMm(jj_AdcDynTest_v4); dMm(k); dMm(k_AdcDynTest_v5) \
     ; dMm(spectP_disturb_temp); dMm(Harbin_disturb_temp); dMm(Ph_disturb); dMm(Ph_disturb_dB); dMm(Fn_disturb); dMm( \
     i_AdcDynTest_v6); dMm(Pd_disturb); dMm(Pd_disturb_dB); dMm(Pd); dMm(Pd_dB); dMm(Pn); dMm(Pn_dB); dMm(Vin); dMm( \
     THD); dMm(HD); dMm(SNRFS); dMm(ENOBFS); 
   
   call_stack_begin;
   // nargin, nargout entry code
   double old_nargin=nargin_val; if (!nargin_set) nargin_val=6.0;
   nargin_set=0;
   double old_nargout=nargout_val; if (!nargout_set) nargout_val=5.0;
   nargout_set=0;
   
   // translated code
   
   // function [SNR, SFDR, SNRFS, SINAD, y, THD, HD, ENOB, ENOBFS, Pn_dB] = AdcDynTest( ADout, fclk, numbit, NFFT, V, code )
   // Pn_dB为底噪声,fclk为采样频率,numbit为采样精度,NFFT为FFT的深度,V为峰峰值,TPY和TPX分别为时域图的Y和X轴,code
   // 为1:补码,2:偏移码,3:格雷码。
   //例子:若采样时钟80MHZ,精度16为,峰峰值2v,时域图显示Y轴+-1V和X轴0-0.01ms,码源为补码
   //[SNR, SFDR, SNRFS, SINAD, THD, HD, ENOB, ENOBFS, Pn_dB] = calc_dynam_params( 80e6, 16, 32768, 2, 1, 0.01, 1 )
   
   if (istrue(code==1.0)) {
     if (istrue(numbit<16.0)) {
       ADout = fix(ADout/mpower(2.0,(16.0-numbit)));
     }
     ADout = ADout/mpower(2.0,(numbit-1.0));
     
   } else
   if (istrue(code==2.0)) {
     if (istrue(numbit<16.0)) {
       ADout = fix(ADout/mpower(2.0,(16.0-numbit)));
     }
     ADout = ADout/mpower(2.0,(numbit-1.0))-1.0;
   } else {
     
     if (istrue(numbit<16.0)) {
       ADout = fix(ADout/mpower(2.0,(16.0-numbit)));
     }
   }
   
   ADout = V/2.0*ADout;
   
   ad_len_N = length(ADout);
   
   maxADout = max(abs(ADout));
   /*[AmpMax,t1] = */max(ADout,i_o,AmpMax,t1);
   /*[AmpMin,t2] = */min(ADout,i_o,AmpMin,t2);
   Vpp = AmpMax-AmpMin;
   
   
   ADout_w = times(ADout,chebwin(ad_len_N,200.0));
   AA = zeros(NFFT-ad_len_N,1.0);
   ADout_w = (BR(ADout_w),semi,
   AA);
   ad_len = length(ADout_w);
   ADout_spect = fft(ADout_w,NFFT);
   ADout_dB = 20.0*log10(abs(ADout_spect));
   
   maxdB = max(ADout_dB(colon(1.0,1.0,ad_len/2.0)));
   fin_v = find(ADout_dB(colon(1.0,1.0,ad_len/2.0))==maxdB);
   
   fin = fin_v(1.0);
   freq_fin = (fin*fclk/ad_len);
   
   data_ref = zeros(ad_len_N,1.0);
   n_AdcDynTest_v0 = colon(1.0,1.0,ad_len_N); int n_AdcDynTest_i0;
   for (n_AdcDynTest_i0=0;n_AdcDynTest_i0<n_AdcDynTest_v0.cols();n_AdcDynTest_i0++) {
     forelem(n,n_AdcDynTest_v0,n_AdcDynTest_i0);
     
     data_ref(n) = V/2.0*sin((n-1.0)*(freq_fin)/fclk*2.0*pi);
   }
   data_ref_w = times(data_ref,chebwin(ad_len_N,200.0));
   
   data_ref_w = (BR(data_ref_w),semi,
   AA);
   data_ref_spect = fft(data_ref_w,NFFT);
   data_ref_dB = 20.0*log10(abs(data_ref_spect));
   ref_dB = max(data_ref_dB(colon(1.0,1.0,ad_len/2.0)));
   
   // $$$ figure( 1 )
   // $$$ plot( [0:round( ad_len / 2 ) - 1].*fclk / ad_len, - 20, ' - k' );
   // $$$ hold on;
   // $$$ plot( [0:50:round( ad_len / 2 ) - 1].*fclk / ad_len, - 40, ' - - k' );
   // $$$ hold on;
   // $$$ plot( [0:round( ad_len / 2 ) - 1].*fclk / ad_len, - 60, ' - k' );
   // $$$ hold on;
   // $$$ plot( [0:50:round( ad_len / 2 ) - 1].*fclk / ad_len, - 80, ' - - k' );
   // $$$ hold on;
   // $$$ plot( [0:round( ad_len / 2 ) - 1].*fclk / ad_len, - 100, ' - k' );
   // $$$ hold on;
   // $$$ plot( [0:50:round( ad_len / 2 ) - 1].*fclk / ad_len, - 120, ' - - k' );
   // $$$ hold on;
   // $$$ plot( [0:round( ad_len / 2 ) - 1].*fclk / ad_len, ADout_dB( 1:round( ad_len / 2 ) ) - ref_dB );
   // $$$ 
   // $$$ 
   // $$$ title( 'FFT PLOT' ); 
   // $$$ xlabel( 'ANALOG INPUT FREQUENCY ( MHz )' );
   // $$$ ylabel( 'AMPLITUDE ( dBFs )' );
   // $$$ a1 = axis; axis( [a1( 1 ) a1( 2 ) - 140 0] ); 
   
   //Calculate SNR, SINAD, THD and SFDR values
   //Find the signal bin number, DC = bin 1
   
   //Span of the DC on each side
   span = max(11.0);
   
   
   //Searching span for peak harmonics amp on each side 
   spanh_har = 4.0;
   //Span of the signal on each side
   span_s = 19.0;
   //8
   //Determine power spectrum
   spectP = times((abs(ADout_spect)),(abs(ADout_spect)));
   
   //Find DC offset power 
   Pdc = sum(spectP(colon(1.0,1.0,span)));
   
   Pdc_dB = sum(ADout_dB(colon(1.0,1.0,span)));
   //Extract overall signal power
   
   l = max(fin-span_s,1.0);
   u = min(fin+span_s,ad_len/2.0);
   Ps = sum(spectP(colon(l,1.0,u)));
   Ps_dB = sum(ADout_dB(colon(l,1.0,u)));
   //Vector / matrix to store both frequency and power of signal and harmonics
   Fh = nop_M;
   
   
   //The 1st element in the vector / matrix represents the signal, the next element represents
   //the 2nd harmonic, etc.
   Ph = nop_M;
   
   Harbin = nop_M;
   Ph_dB = nop_M;
   
   har_num_AdcDynTest_v1 = colon(1.0,1.0,11.0); int har_num_AdcDynTest_i1;
   for (har_num_AdcDynTest_i1=0;har_num_AdcDynTest_i1<har_num_AdcDynTest_v1.cols();har_num_AdcDynTest_i1++) {
     forelem(har_num,har_num_AdcDynTest_v1,har_num_AdcDynTest_i1);
     
     tone = rem((har_num*(fin-1.0)+1.0)/ad_len,1.0);
     
     if (istrue(tone>0.5)) {
       
       tone = 1.0-tone;
       
     }
     
     Fh = (BR(Fh),tone);
     
     
     l = max(1.0,round(tone*ad_len)-spanh_har);
     u = min(ad_len/2.0,round(tone*ad_len)+spanh_har);
     har_peak = max(spectP(colon(l,1.0,u)));
     
     har_bin = find(spectP(colon(l,1.0,u))==har_peak);
     har_bin = har_bin+round(tone*ad_len)-spanh_har-1.0;
     
     l = max(1.0,har_bin-spanh_har);
     u = min(ad_len/2.0,har_bin+spanh_har);
     Ph = (BR(Ph),sum(spectP(colon(l,1.0,u))));
     
     Ph_dB = (BR(Ph_dB),sum(ADout_dB(colon(l,1.0,u))));
     Harbin = (BR(Harbin),har_bin);
   }
   
   spectP_temp = spectP;
   
   i_AdcDynTest_v2 = colon(2.0,1.0,10.0); int i_AdcDynTest_i2;
   for (i_AdcDynTest_i2=0;i_AdcDynTest_i2<i_AdcDynTest_v2.cols();i_AdcDynTest_i2++) {
     forelem(i_,i_AdcDynTest_v2,i_AdcDynTest_i2);
     l = max(1.0,Harbin(i_)-spanh_har);
     u = min(ad_len/2.0,Harbin(i_)+spanh_har);
     spectP_temp(colon(l,1.0,u)) = 0.0;
   }
   l = max(1.0,fin-span_s);
   u = min(ad_len/2.0,fin+span_s);
   spectP_temp(colon(l,1.0,u)) = 0.0;
   spectP_temp(colon(1.0,1.0,span)) = 0.0;
   
   
   disturb_len = 19.0;
   spectP_disturb = zeros(1.0,disturb_len);
   Harbin_disturb = zeros(1.0,disturb_len);
   findSpac = 30.0;
   findSpan = (findSpac-1.0)/2.0;
   findStart = findSpan+1.0;
   
   i_AdcDynTest_v3 = colon(findStart,findSpac,ad_len/2.0); int i_AdcDynTest_i3;
   for (i_AdcDynTest_i3=0;i_AdcDynTest_i3<i_AdcDynTest_v3.cols();i_AdcDynTest_i3++) {
     forelem(i_,i_AdcDynTest_v3,i_AdcDynTest_i3);
     l = max(1.0,i_-findSpan);
     u = min(ad_len/2.0,i_+findSpan);
     /*[spectP_disturb_peak,num] = */max(spectP_temp(colon(l,1.0,u)),i_o,spectP_disturb_peak,num);
     
     if (istrue(spectP_disturb_peak>spectP_disturb(1.0))) {
       spectP_disturb(1.0) = spectP_disturb_peak;
       Harbin_disturb(1.0) = i_-findStart+num;
       array_flag = 1.0;
     } else {
       
       array_flag = 0.0;
     }
     if (istrue(array_flag==1.0)) {
       jj_AdcDynTest_v4 = colon(1.0,1.0,disturb_len-2.0); int jj_AdcDynTest_i4;
       for (jj_AdcDynTest_i4=0;jj_AdcDynTest_i4<jj_AdcDynTest_v4.cols();jj_AdcDynTest_i4++) {
         forelem(jj,jj_AdcDynTest_v4,jj_AdcDynTest_i4);
         k_AdcDynTest_v5 = colon(1.0,1.0,(disturb_len-jj)); int k_AdcDynTest_i5;
         for (k_AdcDynTest_i5=0;k_AdcDynTest_i5<k_AdcDynTest_v5.cols();k_AdcDynTest_i5++) {
           forelem(k,k_AdcDynTest_v5,k_AdcDynTest_i5);
           if (istrue(spectP_disturb(k)>spectP_disturb(k+1.0))) {
             spectP_disturb_temp = spectP_disturb(k);
             spectP_disturb(k) = spectP_disturb(k+1.0);
             spectP_disturb(k+1.0) = spectP_disturb_temp;
             Harbin_disturb_temp = Harbin_disturb(k);
             Harbin_disturb(k) = Harbin_disturb(k+1.0);
             Harbin_disturb(k+1.0) = Harbin_disturb_temp;
             
           }
         }
       }
     }
   }
   Ph_disturb = nop_M;
   Ph_disturb_dB = nop_M;
   Fn_disturb = Harbin_disturb/(ad_len);
   i_AdcDynTest_v6 = colon(1.0,1.0,disturb_len); int i_AdcDynTest_i6;
   for (i_AdcDynTest_i6=0;i_AdcDynTest_i6<i_AdcDynTest_v6.cols();i_AdcDynTest_i6++) {
     forelem(i_,i_AdcDynTest_v6,i_AdcDynTest_i6);
     l = max(1.0,Harbin_disturb(i_)-spanh_har);
     u = min(ad_len/2.0,Harbin_disturb(i_)+spanh_har);
     Ph_disturb = (BR(Ph_disturb),sum(spectP(colon(l,1.0,u))));
     Ph_disturb_dB = (BR(Ph_disturb_dB),sum(ADout_dB(colon(l,1.0,u))));
   }
   Pd_disturb = sum(Ph_disturb(colon(1.0,1.0,disturb_len)));
   Pd_disturb_dB = sum(Ph_disturb_dB(colon(1.0,1.0,disturb_len)));
   
   Pd = sum(Ph(colon(2.0,1.0,10.0)));
   Pd_dB = sum(Ph_dB(colon(2.0,1.0,10.0)));
   
   
   Pn = (sum(spectP(colon(1.0,1.0,ad_len/2.0)))-Pdc-Ps-Pd);
   Pn_dB = (sum(ADout_dB(colon(1.0,1.0,ad_len/2.0)))-Pdc_dB-Ps_dB-Pd_dB-Pd_disturb_dB)*2.0/ad_len-ref_dB;
   // Vin = 20*log10( Vpp / 2 );
   Vin = maxdB-ref_dB;
   SINAD = 10.0*log10(Ps/(Pn+Pd));
   SNR = 10.0*log10(Ps/Pn);
   
   // $$$ disp( 'THD is calculated from 2nd through 5th order harmonics' );
   THD = 10.0*log10(Pd/Ph(1.0));
   SFDR = 10.0*log10(Ph(1.0)/max(max(Ph(colon(2.0,1.0,10.0)),max(Ph_disturb(colon(1.0,1.0,disturb_len))))));
   
   // $$$ disp( 'Signal & Harmonic Power Components:' );
   HD = 10.0*log10(Ph(colon(1.0,1.0,10.0))/Ph(1.0));
   
   
   
   
   // $$$ hold on; 
   // $$$ 
   // $$$ plot( Fh( 2 )*fclk, ADout_dB( Harbin( 2 ) ) - ref_dB, 'rv', Fh( 3 )*fclk, ADout_dB( Harbin( 3 ) ) - ref_dB, 'rv', Fh( 4 )*fclk, ADout_dB( Harbin( 4 ) ) - ref_dB, 'rv', Fh( 5 )*fclk, ADout_dB( Harbin( 5 ) ) - ref_dB, 'rv', Fh( 6 )*fclk, ADout_dB( Harbin( 6 ) ) - ref_dB, 'rv', Fh( 7 )*fclk, ADout_dB( Harbin( 7 ) ) - ref_dB, 'rv', Fh( 8 )*fclk, ADout_dB( Harbin( 8 ) ) - ref_dB, 'rv', Fh( 9 )*fclk, ADout_dB( Harbin( 9 ) ) - ref_dB, 'rv', Fh( 10 )*fclk, ADout_dB( Harbin( 10 ) ) - ref_dB, 'rv' );
   // $$$ hold on;
   // $$$ plot( [0:round( ad_len / 2 ) - 1].*fclk / ad_len, Pn_dB, 'm - ' );
   // $$$ switch ( NFFT )
   // $$$  case 16384
   // $$$   NFFT_txt = '16K';
   // $$$  case 32768
   // $$$   NFFT_txt = '32K';
   // $$$  case 65536
   // $$$   NFFT_txt = '64K'; 
   // $$$ end
   // $$$ FRQ_txt = num2str( freq_fin / 1e6, '%2.1f' );
   // $$$ FRQ_txt = strcat( FRQ_txt, 'MHz' );
   // $$$ FFT_txt = strcat( NFFT_txt, ' FFT' );
   // $$$ FREQ_txt = strcat( num2str( fclk / 1e6, '%2d' ), 'MSPS' );
   // $$$ DBFS_txt = strcat( FRQ_txt, '@', num2str( maxdB - ref_dB, '%2.1f' ), 'dBFs' );
   // $$$ SNR_txt = strcat( 'SNR =', num2str( SNR, '% 2.3f' ), ' dBc' );
   // $$$ SFDR_txt = strcat( 'SFDR = ', num2str( SFDR, '% 2.3f' ), ' dBc' );
   // $$$ text( fclk*5.6 / 16, - 5, FFT_txt, 'HorizontalAlignment', 'left', 'Color', 'r' );
   // $$$ text( fclk*5.6 / 16, - 13, FREQ_txt, 'HorizontalAlignment', 'left', 'Color', 'r' );
   // $$$ text( fclk*5.6 / 16, - 21, DBFS_txt, 'HorizontalAlignment', 'left', 'Color', 'r' );
   // $$$ text( fclk*5.6 / 16, - 29, SNR_txt, 'HorizontalAlignment', 'left', 'Color', 'r' );
   // $$$ text( fclk*5.6 / 16, - 37, SFDR_txt, 'HorizontalAlignment', 'left', 'Color', 'r' );
   // $$$ text( Fh( 2 )*fclk, ADout_dB( Harbin( 2 ) ) - ref_dB + 2, '2', 'VerticalAlignmen', 'bottom', 'Color', 'r' );
   // $$$ text( Fh( 3 )*fclk, ADout_dB( Harbin( 3 ) ) - ref_dB + 2, '3', 'VerticalAlignmen', 'bottom', 'Color', 'r' );
   // $$$ text( Fh( 4 )*fclk, ADout_dB( Harbin( 4 ) ) - ref_dB + 2, '4', 'VerticalAlignmen', 'bottom', 'Color', 'r' );
   // $$$ text( Fh( 5 )*fclk, ADout_dB( Harbin( 5 ) ) - ref_dB + 2, '5', 'VerticalAlignmen', 'bottom', 'Color', 'r' );
   // $$$ text( Fh( 6 )*fclk, ADout_dB( Harbin( 6 ) ) - ref_dB + 2, '6', 'VerticalAlignmen', 'bottom', 'Color', 'r' );
   // $$$ text( Fh( 7 )*fclk, ADout_dB( Harbin( 7 ) ) - ref_dB + 2, '7', 'VerticalAlignmen', 'bottom', 'Color', 'r' );
   // $$$ text( Fh( 8 )*fclk, ADout_dB( Harbin( 8 ) ) - ref_dB + 2, '8', 'VerticalAlignmen', 'bottom', 'Color', 'r' );
   // $$$ text( Fh( 9 )*fclk, ADout_dB( Harbin( 9 ) ) - ref_dB + 2, '9', 'VerticalAlignmen', 'bottom', 'Color', 'r' );
   // $$$ text( Fh( 10 )*fclk, ADout_dB( Harbin( 10 ) ) - ref_dB + 2, '10', 'VerticalAlignmen', 'bottom', 'Color', 'r' );
   // $$$ hold on;
   // $$$ for i = 0:disturb_len / 2
   // $$$  hold on;
   // $$$  plot( Fn_disturb( disturb_len - i )*fclk, ADout_dB( Harbin_disturb( disturb_len - i ) ) - ref_dB, 'g*' );
   // $$$ end
   // $$$ hold off;
   // $$$ 
   // $$$ 
   // $$$ VPP_txt = strcat( num2str( Vpp, '%2.3f' ), ' Vpp' );
   // $$$ figure( 2 )
   // $$$ 
   // $$$ plot( [1:ad_len_N].*1e3 / fclk, ADout( 1:ad_len_N ) );
   // $$$ title( 'Time PLOT' ); 
   // $$$ xlabel( 'TIME ( ms )' );
   // $$$ ylabel( 'AMPLITUDE ( V )' );
   // $$$ hold on
   
   SNRFS = SNR+abs(maxdB-ref_dB);
   ENOB = (SINAD-1.76)/6.02;
   ENOBFS = ENOB+abs(maxdB-ref_dB)/6.02;
   HD = (BR(ADout_dB(max(Harbin(2.0),1.0))-ref_dB),ADout_dB(max(Harbin(2.0),1.0))-ref_dB,ADout_dB(max(Harbin(3.0) \
     ,1.0))-ref_dB,ADout_dB(max(Harbin(4.0),1.0))-ref_dB,ADout_dB(max(Harbin(5.0),1.0))-ref_dB,ADout_dB(max(Harbin( \
     6.0),1.0))-ref_dB,ADout_dB(max(Harbin(7.0),1.0))-ref_dB,ADout_dB(max(Harbin(8.0),1.0))-ref_dB,ADout_dB(max(Harbin( \
     9.0),1.0))-ref_dB,ADout_dB(max(Harbin(10.0),1.0))-ref_dB);
   
   y = ADout_dB-ref_dB;
   
   call_stack_end;
   
   // nargin, nargout exit code
   nargin_val=old_nargin; nargout_val=old_nargout;
   
   // function exit code
   ADout.setname(NULL); fclk.setname(NULL); numbit.setname(NULL); NFFT.setname(NULL); V.setname(NULL); code.setname( \
     NULL); 
   SNR__o=SNR; SINAD__o=SINAD; SFDR__o=SFDR; ENOB__o=ENOB; y__o=y; 
   return x_M;
   end_scope
 }