diff --git a/src/frontend/arg.c b/src/frontend/arg.c index f44e7d197..2182d694e 100644 --- a/src/frontend/arg.c +++ b/src/frontend/arg.c @@ -4,8 +4,8 @@ Author: 1987 Jeffrey M. Hsu **********/ /* - This files contains the routines to evalute arguments to a command - and prompt the user if necessary. + This files contains the routines to evalute arguments to a command + and prompt the user if necessary. */ #include "ngspice/ngspice.h" @@ -16,119 +16,122 @@ Author: 1987 Jeffrey M. Hsu #include "arg.h" #include "variable.h" + static void common(char *string, struct wordlist *wl, struct comm *command); /* returns a private copy of the string */ -char *prompt(FILE *fp) +char * +prompt(FILE *fp) { char buf[100]; char *p; size_t n; if (!fgets(buf, sizeof(buf), fp)) - return NULL; + return NULL; n = strlen(buf) - 1; - buf[n] = '\0'; /* fgets leaves the \n */ + buf[n] = '\0'; /* fgets leaves the \n */ p = TMALLOC(char, n + 1); strcpy(p, buf); return p; } -int countargs(wordlist *wl) -{ - int number=0; +int +countargs(wordlist *wl) +{ + int number = 0; wordlist *w; - for (w = wl; w; w = w->wl_next) { - number++ ; - } - return(number); + for (w = wl; w; w = w->wl_next) + number++ ; + return (number); } -wordlist *process(wordlist *wlist) -{ +wordlist * +process(wordlist *wlist) +{ wlist = cp_variablesubst(wlist); wlist = cp_bquote(wlist); wlist = cp_doglob(wlist); return (wlist); - } -void arg_print(wordlist *wl, struct comm *command) -{ +void +arg_print(wordlist *wl, struct comm *command) +{ common("which variable", wl, command); - } -void arg_plot(wordlist *wl, struct comm *command) -{ +void +arg_plot(wordlist *wl, struct comm *command) +{ common("which variable", wl, command); - } -void arg_load(wordlist *wl, struct comm *command) + +void +arg_load(wordlist *wl, struct comm *command) { - /* just call com_load */ - command->co_func (wl); - + /* just call com_load */ + command->co_func(wl); } + void arg_let(wordlist *wl, struct comm *command) { - common("which vector", wl, command); - } -void arg_set(wordlist *wl, struct comm *command) + +void +arg_set(wordlist *wl, struct comm *command) { - common("which variable", wl, command); - } -void arg_display(wordlist *wl, struct comm *command) + +void +arg_display(wordlist *wl, struct comm *command) { NG_IGNORE(wl); NG_IGNORE(command); /* just return; display does the right thing */ - } + /* a common prompt routine */ static void common(char *string, struct wordlist *wl, struct comm *command) { - struct wordlist *w; char *buf; if (!countargs(wl)) { - outmenuprompt(string); - if ((buf = prompt(cp_in)) == NULL) /* prompt aborted */ - return; /* don't execute command */ - /* do something with the wordlist */ - w = wl_cons(buf, NULL); + outmenuprompt(string); + if ((buf = prompt(cp_in)) == NULL) /* prompt aborted */ + return; /* don't execute command */ + /* do something with the wordlist */ + w = wl_cons(buf, NULL); - w = process(w); - /* O.K. now call fn */ - command->co_func (w); + w = process(w); + /* O.K. now call fn */ + command->co_func(w); } - } + void outmenuprompt(char *string) { - fprintf(cp_out, "%s: ", string); - fflush(cp_out); - return; + fprintf(cp_out, "%s: ", string); + fflush(cp_out); + return; } diff --git a/src/frontend/aspice.c b/src/frontend/aspice.c index 931591384..f08e034a5 100644 --- a/src/frontend/aspice.c +++ b/src/frontend/aspice.c @@ -15,8 +15,9 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group #include "variable.h" #include "circuits.h" + # ifdef HAVE_SYS_WAIT_H - /* should be more tests here I think */ +/* should be more tests here I think */ # define OK_ASPICE # endif @@ -38,11 +39,11 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group #include "../misc/mktemp.h" /* - This is required for the GCC pre-processor and might be needed for others - Added to resolve ngspice bug 1293746 - http://sourceforge.net/tracker/index.php?func=detail&aid=1293746&group_id=38962&atid=423915 + This is required for the GCC pre-processor and might be needed for others + Added to resolve ngspice bug 1293746 + http://sourceforge.net/tracker/index.php?func=detail&aid=1293746&group_id=38962&atid=423915 */ -#if !defined(SOLARIS) && defined (__SVR4) && defined(__sun) +#if !defined(SOLARIS) && defined(__SVR4) && defined(__sun) # define SOLARIS #endif @@ -54,17 +55,18 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group static RETSIGTYPE sigchild(void); struct proc { - int pr_pid; /* The pid of the spice job. */ - char *pr_rawfile; /* The temporary raw file. */ - char *pr_name; /* The name of the spice run. */ - char *pr_inpfile; /* The name of the input file. */ - char *pr_outfile; /* The name of the (tmp) output file. */ - bool pr_saveout; /* Don't (void) unlink the output file */ - struct proc *pr_next; /* Link. */ -} ; + int pr_pid; /* The pid of the spice job. */ + char *pr_rawfile; /* The temporary raw file. */ + char *pr_name; /* The name of the spice run. */ + char *pr_inpfile; /* The name of the input file. */ + char *pr_outfile; /* The name of the (tmp) output file. */ + bool pr_saveout; /* Don't (void) unlink the output file */ + struct proc *pr_next; /* Link. */ +}; static struct proc *running = NULL; -static int numchanged = 0; /* How many children have changed in state. */ +static int numchanged = 0; /* How many children have changed in state. */ + void com_aspice(wordlist *wl) @@ -78,11 +80,11 @@ com_aspice(wordlist *wl) deck = wl->wl_word; if (!cp_getvar("spicepath", CP_STRING, spicepath)) { - if (!Spice_Path || !*Spice_Path) { - fprintf(cp_err, - "No spice-3 binary is available for the aspice command.\n"); - return; - } + if (!Spice_Path || !*Spice_Path) { + fprintf(cp_err, + "No spice-3 binary is available for the aspice command.\n"); + return; + } (void) strcpy(spicepath, Spice_Path); } @@ -113,11 +115,11 @@ com_aspice(wordlist *wl) if (pid == 0) { if (!(freopen(deck, "r", stdin))) { perror(deck); - exit (EXIT_BAD); + exit(EXIT_BAD); } if (!(freopen(output, "w", stdout))) { perror(output); - exit (EXIT_BAD); + exit(EXIT_BAD); } (void) dup2(fileno(stdout), fileno(stderr)); @@ -162,18 +164,19 @@ com_jobs(wordlist *wl) return; } + static RETSIGTYPE sigchild(void) { numchanged++; if (ft_asyncdb) fprintf(cp_err, "%d jobs done now\n", numchanged); - if (cp_cwait) { + if (cp_cwait) ft_checkkids(); - } return; } + /* This gets called every once in a while, and checks to see if any * jobs have finished. If they have it gets the data. The problem is * that wait(0) is probably more portable, but it can't tell @@ -184,8 +187,10 @@ sigchild(void) * On posix systems, wait() is: * pid_t wait(int *status); */ + int status; + void ft_checkkids(void) { @@ -203,47 +208,55 @@ ft_checkkids(void) while (numchanged > 0) { pid = wait(&status); if (pid == -1) { - fprintf(cp_err, - "ft_checkkids: Internal Error: should be %d jobs done but there aren't any.\n", - numchanged); + fprintf(cp_err, + "ft_checkkids: Internal Error: should be %d jobs done but there aren't any.\n", + numchanged); numchanged = 0; running = NULL; here = FALSE; return; } + for (p = running; p; p = p->pr_next) { if (p->pr_pid == pid) break; lp = p; } + if (p == NULL) { fprintf(cp_err, - "ft_checkkids: Internal Error: Process %d not a job!\n", + "ft_checkkids: Internal Error: Process %d not a job!\n", (int) pid); here = FALSE; return; } + if (p == running) running = p->pr_next; else lp->pr_next = p->pr_next; + fprintf(cp_out, "Job finished: %.60s\n", p->pr_name); numchanged--; ft_loadfile(p->pr_rawfile); (void) unlink(p->pr_rawfile); out_init(); + if (!(fp = fopen(p->pr_outfile, "r"))) { perror(p->pr_outfile); here = FALSE; return; } + while (fgets(buf, BSIZE_SP, fp)) out_send(buf); + (void) fclose(fp); if (!p->pr_saveout) (void) unlink(p->pr_outfile); printf("\n-----\n"); } + printf("\n"); #ifdef TIOCSTI (void) ioctl(0, TIOCSTI, "\022"); /* Reprint the line. */ @@ -252,6 +265,7 @@ ft_checkkids(void) return; } + /* Run a spice job remotely. See the description of the spice daemon for * the protocol. This is no longer 4.2 specific. */ @@ -267,8 +281,8 @@ com_rspice(wordlist *wl) size_t n; int to_serv[2], from_serv[2], err_serv[2]; int pid; - long pos; - int num; + long pos; + int num; char *p; /* Figure out where the spicedaemon is and connect to it. */ @@ -281,50 +295,50 @@ com_rspice(wordlist *wl) if (*rhost == '\0') { fprintf(cp_err, - "Error: there is no remote ngspice.host for this site -- set \"rhost\".\n"); - return; + "Error: there is no remote ngspice.host for this site -- set \"rhost\".\n"); + return; } if (*program == '\0') { fprintf(cp_err, -"Error: there is no remote spice program for this site -- set \"rprogram\".\n"); - return; + "Error: there is no remote spice program for this site -- set \"rprogram\".\n"); + return; } if (pipe(to_serv) < 0) { - perror("pipe to server"); - return; + perror("pipe to server"); + return; } if (pipe(from_serv) < 0) { - perror("pipe from server"); - return; + perror("pipe from server"); + return; } if (pipe(err_serv) < 0) { - perror("2nd pipe from server"); - return; + perror("2nd pipe from server"); + return; } - pid = fork( ); + pid = fork(); if (pid == 0) { - /* I am the "server" process */ - close(to_serv[1]); - close(from_serv[0]); - close(err_serv[0]); + /* I am the "server" process */ + close(to_serv[1]); + close(from_serv[0]); + close(err_serv[0]); - fclose(stdin); - fclose(stdout); - fclose(stderr); + fclose(stdin); + fclose(stdout); + fclose(stderr); - dup2(to_serv[0], 0); /* stdin */ - dup2(from_serv[1], 1); /* stdout */ - dup2(err_serv[1], 2); /* stderr */ + dup2(to_serv[0], 0); /* stdin */ + dup2(from_serv[1], 1); /* stdout */ + dup2(err_serv[1], 2); /* stderr */ - execlp(remote_shell, remote_shell, rhost, program, "-s", (void*)0); - /* system(com_buf); */ - perror(remote_shell); - exit(-1); + execlp(remote_shell, remote_shell, rhost, program, "-s", (void*)0); + /* system(com_buf); */ + perror(remote_shell); + exit(-1); } else if (pid == -1) { - perror("fork"); - return; + perror("fork"); + return; } /* I am the "client" side */ @@ -344,23 +358,23 @@ com_rspice(wordlist *wl) continue; /* Should be careful */ } while ((n = fread(buf, 1, BSIZE_SP, inp)) > 0) - (void) fwrite(buf, 1, strlen(buf), srv_input); - /* (void) write(s, buf, n); */ + (void) fwrite(buf, 1, strlen(buf), srv_input); + /* (void) write(s, buf, n); */ wl = wl->wl_next; - fclose(inp); + fclose(inp); } /* (void) write(s, "@\n", 3);*/ } else { if (ft_nutmeg || !ft_curckt) { fprintf(cp_err, "Error: no circuits loaded\n"); - fclose(srv_input); - fclose(serv); + fclose(srv_input); + fclose(serv); return; } - - inp_list(srv_input, ft_curckt->ci_deck, ft_curckt->ci_options, - LS_DECK); + + inp_list(srv_input, ft_curckt->ci_deck, ft_curckt->ci_options, LS_DECK); } + fclose(srv_input); /* Now wait for things to come through */ @@ -369,33 +383,36 @@ com_rspice(wordlist *wl) break; fputs(buf, cp_out); } + outfile = smktemp("rsp"); if ((out = fopen(outfile, "w+")) == NULL) { perror(outfile); (void) fclose(serv); return; } + if (p) - fputs(buf, out); - while ((n = fread(buf, 1, BSIZE_SP, serv)) != 0) { + fputs(buf, out); + + while ((n = fread(buf, 1, BSIZE_SP, serv)) != 0) (void) fwrite(buf, 1, n, out); - } + /* We hope that positioning info + error messages < pipe size */ - while (fgets(buf, BSIZE_SP, err_outp)) { - if (!strncmp("@@@", buf, 3)) { - if (sscanf(buf, "@@@ %ld %d", &pos, &num) != 2) { - fprintf(stderr, "Error reading rawdata: %s\n", buf); - continue; - } - if (fseek(out, pos, SEEK_SET)) - fprintf(stderr, - "Error adjusting rawfile: write \"%d\" at %ld\n", - num, pos); - else - fprintf(out, "%d", num); - } else - fprintf(stderr, "%s", buf); - } + while (fgets(buf, BSIZE_SP, err_outp)) + if (!strncmp("@@@", buf, 3)) { + if (sscanf(buf, "@@@ %ld %d", &pos, &num) != 2) { + fprintf(stderr, "Error reading rawdata: %s\n", buf); + continue; + } + if (fseek(out, pos, SEEK_SET)) + fprintf(stderr, + "Error adjusting rawfile: write \"%d\" at %ld\n", + num, pos); + else + fprintf(out, "%d", num); + } else { + fprintf(stderr, "%s", buf); + } (void) fclose(out); (void) fclose(serv); @@ -412,36 +429,36 @@ com_rspice(wordlist *wl) #else void -com_aspice( - wordlist *wl) +com_aspice(wordlist *wl) { - NG_IGNORE(wl); - fprintf(cp_err, "Asynchronous spice jobs are not available.\n"); - return; + NG_IGNORE(wl); + fprintf(cp_err, "Asynchronous spice jobs are not available.\n"); + return; } + void -com_jobs( - wordlist *wl) +com_jobs(wordlist *wl) { - NG_IGNORE(wl); - fprintf(cp_err, "Asynchronous spice jobs are not available.\n"); - return; + NG_IGNORE(wl); + fprintf(cp_err, "Asynchronous spice jobs are not available.\n"); + return; } + void ft_checkkids(void) { - return; + return; } + void -com_rspice( - wordlist *wl) +com_rspice(wordlist *wl) { - NG_IGNORE(wl); - fprintf(cp_err, "Remote spice jobs are not available.\n"); - return; + NG_IGNORE(wl); + fprintf(cp_err, "Remote spice jobs are not available.\n"); + return; } #endif diff --git a/src/frontend/breakp.c b/src/frontend/breakp.c index de3646902..4dfcf2ed5 100644 --- a/src/frontend/breakp.c +++ b/src/frontend/breakp.c @@ -18,12 +18,14 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group #include "completion.h" + static bool satisfied(struct dbcomm *d, struct plot *plot); static void printcond(struct dbcomm *d, FILE *fp); static int howmanysteps = 0; static int steps = 0; + /* Set a breakpoint. Possible commands are: * stop after n * stop when var cond val @@ -41,45 +43,47 @@ com_stop(wordlist *wl) double *val; while (wl) { - if (thisone == NULL) + if (thisone == NULL) { thisone = d = alloc(struct dbcomm); - else { + } else { d->db_also = alloc(struct dbcomm); d = d->db_also; } /* Figure out what the first condition is. */ - d->db_analysis = NULL; + d->db_analysis = NULL; if (eq(wl->wl_word, "after") && wl->wl_next) { d->db_type = DB_STOPAFTER; d->db_number = debugnumber; - if (!wl->wl_next->wl_word) - i = 0; - else { + if (!wl->wl_next->wl_word) { + i = 0; + } else { #ifdef HAVE_CTYPE_H - for (s = wl->wl_next->wl_word, i = 0; *s; s++) - if (!isdigit(*s)) - goto bad; - else - i = i * 10 + (*s - '0'); + for (s = wl->wl_next->wl_word, i = 0; *s; s++) + if (!isdigit(*s)) + goto bad; + else + i = i * 10 + (*s - '0'); #else - i = atoi(wl->wl_next->wl_word); /* etoi ??? */ + i = atoi(wl->wl_next->wl_word); /* etoi ??? */ #endif - } + } d->db_iteration = i; wl = wl->wl_next->wl_next; } else if (eq(wl->wl_word, "when") && wl->wl_next) { - /* cp_lexer(string) will not discriminate '=', so we have + /* cp_lexer(string) will not discriminate '=', so we have to do it here */ - if (strstr(wl->wl_next->wl_word,"=") && (!(wl->wl_next->wl_next) || - strstr(wl->wl_next->wl_next->wl_word,"when") || - strstr(wl->wl_next->wl_next->wl_word,"after"))) { + if (strstr(wl->wl_next->wl_word, "=") && + (!(wl->wl_next->wl_next) || + strstr(wl->wl_next->wl_next->wl_word, "when") || + strstr(wl->wl_next->wl_next->wl_word, "after"))) + { /* we have vec=val in a single word */ - wordlist * wln; - char** charr = TMALLOC(char*, 4) ; + wordlist *wln; + char **charr = TMALLOC(char*, 4); char *tok = copy(wl->wl_next->wl_word); - char *tokeq = strstr(tok,"="); - char *tokafter = copy(tokeq+1); + char *tokeq = strstr(tok, "="); + char *tokafter = copy(tokeq + 1); *tokeq = '\0'; charr[0] = tok; charr[1] = copy("eq"); @@ -89,8 +93,7 @@ com_stop(wordlist *wl) wl_splice(wl->wl_next, wln); } /* continue with parsing the enhanced wordlist */ - if (wl->wl_next->wl_next && - wl->wl_next->wl_next->wl_next) { + if (wl->wl_next->wl_next && wl->wl_next->wl_next->wl_next) { wl = wl->wl_next; d->db_number = debugnumber; d->db_type = DB_STOPWHEN; @@ -127,17 +130,20 @@ com_stop(wordlist *wl) else d->db_nodename2 = copy(wl->wl_word); wl = wl->wl_next; - } else + } else { goto bad; + } } } + if (thisone) { if (dbs) { for (d = dbs; d->db_next; d = d->db_next) ; d->db_next = thisone; - } else + } else { dbs = thisone; + } (void) sprintf(buf, "%d", debugnumber); cp_addkword(CT_DBNUMS, buf); debugnumber++; @@ -145,10 +151,12 @@ com_stop(wordlist *wl) return; -bad: fprintf(cp_err, "Syntax error parsing breakpoint specification.\n"); +bad: + fprintf(cp_err, "Syntax error parsing breakpoint specification.\n"); return; } + /* Trace a node (have wrd_point print it). Usage is "trace node ..."*/ void @@ -158,24 +166,24 @@ com_trce(wordlist *wl) return; } + /* Incrementally plot a value. This is just like trace. */ void com_iplot(wordlist *wl) { - /* settrace(wl, VF_PLOT); */ struct dbcomm *d, *td, *currentdb = NULL; char *s; /* We use a modified ad-hoc algorithm here where db_also denotes - vectors on the same command line and db_next denotes - separate iplot commands. */ + vectors on the same command line and db_next denotes + separate iplot commands. */ while (wl) { s = cp_unquote(wl->wl_word); d = alloc(struct dbcomm); - d->db_analysis = NULL; + d->db_analysis = NULL; d->db_number = debugnumber++; if (eq(s, "all")) { d->db_type = DB_IPLOTALL; @@ -188,17 +196,19 @@ com_iplot(wordlist *wl) currentdb = d; wl = wl->wl_next; } + if (dbs) { for (td = dbs; td->db_next; td = td->db_next) ; td->db_next = currentdb; - } else + } else { dbs = currentdb; + } return; - } + /* Step a number of iterations. */ void @@ -208,10 +218,13 @@ com_step(wordlist *wl) steps = howmanysteps = atoi(wl->wl_word); else steps = howmanysteps = 1; + com_resume(NULL); + return; } + /* Print out the currently active breakpoints and traces. If we are printing * to a file, assume that the file will be used for a later source and leave * off the event numbers (with UNIX, that is). -- I don't like this. @@ -230,24 +243,19 @@ com_sttus(wordlist *wl) for (d = dbs; d; d = d->db_next) { if (d->db_type == DB_TRACENODE) { if (isatty(fileno(cp_out))) - fprintf(cp_out, "%-4d trace %s", d->db_number, - d->db_nodename1); + fprintf(cp_out, "%-4d trace %s", d->db_number, d->db_nodename1); else fprintf(cp_out, "trace %s", d->db_nodename1); } else if (d->db_type == DB_IPLOT) { - if (isatty(fileno(cp_out))) { - fprintf(cp_out, "%-4d iplot %s", d->db_number, - d->db_nodename1); - } else { + if (isatty(fileno(cp_out))) + fprintf(cp_out, "%-4d iplot %s", d->db_number, d->db_nodename1); + else fprintf(cp_out, "iplot %s", d->db_nodename1); - } - for (dc = d->db_also; dc; dc = dc->db_also) { - fprintf(cp_out, " %s", dc->db_nodename1); - } + for (dc = d->db_also; dc; dc = dc->db_also) + fprintf(cp_out, " %s", dc->db_nodename1); } else if (d->db_type == DB_SAVE) { if (isatty(fileno(cp_out))) - fprintf(cp_out, "%-4d save %s", d->db_number, - d->db_nodename1); + fprintf(cp_out, "%-4d save %s", d->db_number, d->db_nodename1); else fprintf(cp_out, "save %s", d->db_nodename1); } else if (d->db_type == DB_TRACEALL) { @@ -265,8 +273,7 @@ com_sttus(wordlist *wl) fprintf(cp_out, "%-4d save all", d->db_number); else fprintf(cp_out, "save all"); - } else if ((d->db_type == DB_STOPAFTER) || - (d->db_type == DB_STOPWHEN)) { + } else if ((d->db_type == DB_STOPAFTER) || (d->db_type == DB_STOPWHEN)) { if (isatty(fileno(cp_out))) fprintf(cp_out, "%-4d stop", d->db_number); else @@ -275,21 +282,23 @@ com_sttus(wordlist *wl) } else if ((d->db_type == DB_DEADIPLOT)) { if (isatty(fileno(cp_out))) { fprintf(cp_out, "%-4d exiting iplot %s", d->db_number, - d->db_nodename1); + d->db_nodename1); } else { fprintf(cp_out, "exiting iplot %s", d->db_nodename1); } - for (dc = d->db_also; dc; dc = dc->db_also) { - fprintf(cp_out, " %s", dc->db_nodename1); - } - } else - fprintf(cp_err, - "com_sttus: Internal Error: bad db %d\n", d->db_type); + for (dc = d->db_also; dc; dc = dc->db_also) + fprintf(cp_out, " %s", dc->db_nodename1); + } else { + fprintf(cp_err, + "com_sttus: Internal Error: bad db %d\n", d->db_type); + } (void) putc('\n', cp_out); } + return; } + void dbfree(struct dbcomm *db) { @@ -301,9 +310,11 @@ dbfree(struct dbcomm *db) tfree(dd->db_nodename2); tfree(dd); } + return; } + /* Delete breakpoints and traces. Usage is delete [number ...] */ void @@ -326,21 +337,26 @@ com_delete(wordlist *wl) return; } } + while (wl) { - if (wl->wl_word) { + + if (wl->wl_word) { #ifdef HAVE_CTYPE_H - for (s = wl->wl_word, i = 0; *s; s++) - if (!isdigit(*s)) { - fprintf(cp_err, "Error: %s isn't a number.\n", - wl->wl_word); - goto bad; - } else - i = i * 10 + (*s - '0'); + for (s = wl->wl_word, i = 0; *s; s++) + if (!isdigit(*s)) { + fprintf(cp_err, "Error: %s isn't a number.\n", + wl->wl_word); + goto bad; + } else { + i = i * 10 + (*s - '0'); + } #else - i = atoi(wl->wl_next->wl_word); /* etoi ??? */ + i = atoi(wl->wl_next->wl_word); /* etoi ??? */ #endif - } else - i = 0; + } else { + i = 0; + } + for (d = dbs, dt = NULL; d; d = d->db_next) { if (d->db_number == i) { if (dt) @@ -354,11 +370,15 @@ com_delete(wordlist *wl) } dt = d; } -bad: wl = wl->wl_next; + + bad: + wl = wl->wl_next; } + return; } + /* Writedata calls this routine to see if it should keep going. If it * returns TRUE, then the run should resume. */ @@ -378,43 +398,47 @@ ft_bpcheck(struct plot *runplot, int iteration) for (d = dbs; d; d = d->db_next) { for (dt = d; dt; dt = dt->db_also) { switch (dt->db_type) { - case DB_TRACENODE: - case DB_TRACEALL: - case DB_IPLOT: - case DB_DEADIPLOT: - case DB_IPLOTALL: - case DB_SAVE: - case DB_SAVEALL: + case DB_TRACENODE: + case DB_TRACEALL: + case DB_IPLOT: + case DB_DEADIPLOT: + case DB_IPLOTALL: + case DB_SAVE: + case DB_SAVEALL: + goto more; + case DB_STOPAFTER: + if (iteration == dt->db_iteration) + break; + else goto more; - case DB_STOPAFTER: - if (iteration == dt->db_iteration) - break; - else - goto more; - case DB_STOPWHEN: - /* See if the condition is TRUE. */ - if (satisfied(dt, runplot)) - break; - else - goto more; - default: - fprintf(cp_err, "ft_bpcheck: Internal Error: bad db %d\n", - dt->db_type); + case DB_STOPWHEN: + /* See if the condition is TRUE. */ + if (satisfied(dt, runplot)) + break; + else + goto more; + default: + fprintf(cp_err, "ft_bpcheck: Internal Error: bad db %d\n", + dt->db_type); } } + if (dt == NULL) { /* It made it */ - fprintf(cp_err, "%-2d: condition met: stop ", - d->db_number); + fprintf(cp_err, "%-2d: condition met: stop ", d->db_number); printcond(d, cp_err); (void) putc('\n', cp_err); return (FALSE); } -more: /* Just continue */ ; + + more: /* Just continue */ + ; } + return (TRUE); } + /* This is called to determine whether a STOPWHEN is TRUE. */ static bool @@ -425,52 +449,52 @@ satisfied(struct dbcomm *d, struct plot *plot) if (d->db_nodename1) { if ((v1 = vec_fromplot(d->db_nodename1, plot)) == NULL) { - fprintf(cp_err, "Error: %s: no such node\n", - d->db_nodename1); + fprintf(cp_err, "Error: %s: no such node\n", d->db_nodename1); return (FALSE); } if (isreal(v1)) d1 = v1->v_realdata[v1->v_length - 1]; else d1 = realpart((v1->v_compdata[v1->v_length - 1])); - } else + } else { d1 = d->db_value1; + } if (d->db_nodename2) { if ((v2 = vec_fromplot(d->db_nodename2, plot)) == NULL) { - fprintf(cp_err, "Error: %s: no such node\n", - d->db_nodename2); + fprintf(cp_err, "Error: %s: no such node\n", d->db_nodename2); return (FALSE); } if (isreal(v2)) d2 = v2->v_realdata[v2->v_length - 1]; else d2 = realpart((v2->v_compdata[v2->v_length - 1])); - } else + } else { d2 = d->db_value2; + } switch (d->db_op) { - case DBC_EQU: - return (AlmostEqualUlps(d1, d2, 3) ? TRUE : FALSE); -// return ((d1 == d2) ? TRUE : FALSE); - case DBC_NEQ: - return ((d1 != d2) ? TRUE : FALSE); - case DBC_GTE: - return ((d1 >= d2) ? TRUE : FALSE); - case DBC_LTE: - return ((d1 <= d2) ? TRUE : FALSE); - case DBC_GT: - return ((d1 > d2) ? TRUE : FALSE); - case DBC_LT: - return ((d1 < d2) ? TRUE : FALSE); - default: - fprintf(cp_err, - "satisfied: Internal Error: bad cond %d\n", - d->db_op); - return (FALSE); + case DBC_EQU: + return (AlmostEqualUlps(d1, d2, 3) ? TRUE : FALSE); + // return ((d1 == d2) ? TRUE : FALSE); + case DBC_NEQ: + return ((d1 != d2) ? TRUE : FALSE); + case DBC_GTE: + return ((d1 >= d2) ? TRUE : FALSE); + case DBC_LTE: + return ((d1 <= d2) ? TRUE : FALSE); + case DBC_GT: + return ((d1 > d2) ? TRUE : FALSE); + case DBC_LT: + return ((d1 < d2) ? TRUE : FALSE); + default: + fprintf(cp_err, + "satisfied: Internal Error: bad cond %d\n", d->db_op); + return (FALSE); } } + /* Writedata calls this before it starts a run, to set the proper flags * on the dvecs. If a change is made during a break, then the routine * wrd_chtrace is used from these routines. We have to be clever with save: @@ -484,50 +508,51 @@ ft_trquery(void) return; } + static void printcond(struct dbcomm *d, FILE *fp) { struct dbcomm *dt; for (dt = d; dt; dt = dt->db_also) { - if (dt->db_type == DB_STOPAFTER) + if (dt->db_type == DB_STOPAFTER) { fprintf(fp, " after %d", dt->db_iteration); - else { + } else { if (dt->db_nodename1) - fprintf(fp, " when %s", - dt->db_nodename1); + fprintf(fp, " when %s", dt->db_nodename1); else fprintf(fp, " when %g", dt->db_value1); + switch (dt->db_op) { - case DBC_EQU: - fputs(" =", fp); - break; - case DBC_NEQ: - fputs(" <>", fp); - break; - case DBC_GT: - fputs(" >", fp); - break; - case DBC_LT: - fputs(" <", fp); - break; - case DBC_GTE: - fputs(" >=", fp); - break; - case DBC_LTE: - fputs(" <=", fp); - break; - default: - fprintf(cp_err, - "printcond: Internal Error: bad cond %d", - dt->db_op); + case DBC_EQU: + fputs(" =", fp); + break; + case DBC_NEQ: + fputs(" <>", fp); + break; + case DBC_GT: + fputs(" >", fp); + break; + case DBC_LT: + fputs(" <", fp); + break; + case DBC_GTE: + fputs(" >=", fp); + break; + case DBC_LTE: + fputs(" <=", fp); + break; + default: + fprintf(cp_err, + "printcond: Internal Error: bad cond %d", dt->db_op); } + if (dt->db_nodename2) fprintf(fp, " %s", dt->db_nodename2); else fprintf(fp, " %g", dt->db_value2); } } + return; } - diff --git a/src/frontend/breakp2.c b/src/frontend/breakp2.c index b923e248e..38f08de80 100644 --- a/src/frontend/breakp2.c +++ b/src/frontend/breakp2.c @@ -15,15 +15,17 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group #include "quote.h" #include "breakp2.h" + /* global linked list to store .save data and breakpoint data */ struct dbcomm *dbs = NULL; /* export for iplot */ /* used in breakp.c and breakp2.c */ int debugnumber = 1; + /* Analyse the data given by the .save card or 'save' command. Store the data in the global dbs struct. - */ +*/ /* Save a vector. */ @@ -34,6 +36,7 @@ com_save(wordlist *wl) return; } + /* Save a vector with the analysis type given (name). */ void com_save2(wordlist *wl, char *name) @@ -42,6 +45,7 @@ com_save2(wordlist *wl, char *name) return; } + void settrace(wordlist *wl, int what, char *name) { @@ -55,46 +59,52 @@ settrace(wordlist *wl, int what, char *name) d->db_analysis = name; if (eq(s, "all")) { switch (what) { - case VF_PRINT: - d->db_type = DB_TRACEALL; - break; -/* case VF_PLOT: - d->db_type = DB_IPLOTALL; - break; */ - case VF_ACCUM: - /* d->db_type = DB_SAVEALL; */ - d->db_nodename1 = copy(s); - d->db_type = DB_SAVE; - break; + case VF_PRINT: + d->db_type = DB_TRACEALL; + break; + /* case VF_PLOT: + d->db_type = DB_IPLOTALL; + break; */ + case VF_ACCUM: + /* d->db_type = DB_SAVEALL; */ + d->db_nodename1 = copy(s); + d->db_type = DB_SAVE; + break; } -/* wrd_chtrace(NULL, TRUE, what); */ + /* wrd_chtrace(NULL, TRUE, what); */ } else { switch (what) { - case VF_PRINT: - d->db_type = DB_TRACENODE; - break; -/* case VF_PLOT: - d->db_type = DB_IPLOT; - break; */ - case VF_ACCUM: - d->db_type = DB_SAVE; - break; + case VF_PRINT: + d->db_type = DB_TRACENODE; + break; +/* case VF_PLOT: + d->db_type = DB_IPLOT; + break; */ + case VF_ACCUM: + d->db_type = DB_SAVE; + break; } d->db_nodename1 = copy(s); -/* wrd_chtrace(s, TRUE, what); */ + /* wrd_chtrace(s, TRUE, what); */ } - tfree(s);/*DG avoid memoy leak */ + + tfree(s); /*DG avoid memoy leak */ + if (dbs) { for (td = dbs; td->db_next; td = td->db_next) ; td->db_next = d; - } else + } else { dbs = d; + } + wl = wl->wl_next; } + return; } + /* retrieve the save nodes from dbs into an array */ int ft_getSaves(struct save_info **savesp) @@ -110,18 +120,18 @@ ft_getSaves(struct save_info **savesp) if (!count) return (0); - + *savesp = array = TMALLOC(struct save_info, count); for (d = dbs; d; d = d->db_next) if (d->db_type == DB_SAVE) { array[i].used = 0; - if (d->db_analysis) - array[i].analysis = copy(d->db_analysis); - else - array[i].analysis = NULL; + if (d->db_analysis) + array[i].analysis = copy(d->db_analysis); + else + array[i].analysis = NULL; array[i++].name = copy(d->db_nodename1); - } - + } + return (count); } diff --git a/src/frontend/circuits.h b/src/frontend/circuits.h index 64fd622e4..b3415fca2 100644 --- a/src/frontend/circuits.h +++ b/src/frontend/circuits.h @@ -7,14 +7,9 @@ #define CIRCUITS_H_INCLUDED - struct subcirc { - char *sc_name; /* Whatever... */ -} ; - - - - + char *sc_name; /* Whatever... */ +}; #endif diff --git a/src/frontend/com_ahelp.c b/src/frontend/com_ahelp.c index 2dc727352..9e1aab771 100644 --- a/src/frontend/com_ahelp.c +++ b/src/frontend/com_ahelp.c @@ -26,22 +26,21 @@ com_ahelp(wordlist *wl) char slevel[256]; if (wl) { - com_help(wl); - return; + com_help(wl); + return; } out_init(); /* determine environment */ - if (plot_list->pl_next) { /* plots load */ - env |= E_HASPLOTS; - } else { - env |= E_NOPLOTS; - } + if (plot_list->pl_next) /* plots load */ + env |= E_HASPLOTS; + else + env |= E_NOPLOTS; /* determine level */ if (cp_getvar("level", CP_STRING, slevel)) { - switch (*slevel) { + switch (*slevel) { case 'b': level = 1; break; case 'i': level = 2; @@ -50,40 +49,40 @@ com_ahelp(wordlist *wl) break; default: level = 1; break; - } + } } else { - level = 1; + level = 1; } out_printf( - "For a complete description read the Spice3 User's Manual manual.\n"); + "For a complete description read the Spice3 User's Manual manual.\n"); out_printf( - "For a list of all commands type \"help all\", for a short\n"); + "For a list of all commands type \"help all\", for a short\n"); out_printf( - "description of \"command\", type \"help command\".\n"); + "description of \"command\", type \"help command\".\n"); /* sort the commands */ - for (n = 0; cp_coms[n].co_func != NULL; n++) { - cc[n] = &cp_coms[n]; - } + for (n = 0; cp_coms[n].co_func != NULL; n++) + cc[n] = &cp_coms[n]; + qsort(cc, (size_t) n, sizeof(struct comm *), hcomp); /* filter the commands */ - for (i=0; i< n; i++) { - com = cc[i]; - if ((com->co_env < (level << 13)) && (!(com->co_env & 4095) || - (env & com->co_env))) { - if ((com->co_spiceonly && ft_nutmeg) || (com->co_help == NULL)) { - continue; - } - out_printf("%s ", com->co_comname); - out_printf(com->co_help, cp_program); - out_send("\n"); - } + for (i = 0; i < n; i++) { + com = cc[i]; + if ((com->co_env < (level << 13)) && + (!(com->co_env & 4095) || (env & com->co_env))) + { + if ((com->co_spiceonly && ft_nutmeg) || (com->co_help == NULL)) + continue; + + out_printf("%s ", com->co_comname); + out_printf(com->co_help, cp_program); + out_send("\n"); + } } out_send("\n"); return; - } diff --git a/src/frontend/com_alias.c b/src/frontend/com_alias.c index 9835cd898..8c6c6fd10 100644 --- a/src/frontend/com_alias.c +++ b/src/frontend/com_alias.c @@ -12,7 +12,6 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group struct alias *cp_aliases = NULL; - /* Return NULL if no alias was found. We can get away with just * calling cp_histsubst now because the line will have gone onto the * history list by now and cp_histsubst will look in the right place. */ @@ -28,11 +27,13 @@ asubst(wordlist *wlist) wlist->wl_word++; /* FIXME !!!, free() will fail !!! */ return (NULL); } + for (al = cp_aliases; al; al = al->al_next) if (eq(word, al->al_name)) break; if (!al) return (NULL); + wl = cp_histsubst(wl_copy(al->al_text)); if (cp_didhsubst) { @@ -43,13 +44,13 @@ asubst(wordlist *wlist) /* If it had no history args, then append the rest of the wl */ wl_append(wl, wl_copy(wlist->wl_next)); } + return (wl); } - -/* MW. This function should not use cp_lastone, see cp_parse in cpshar.c - * Many things are deleted here and memory leak closed */ +/* MW. This function should not use cp_lastone, see cp_parse in cpshar.c + * Many things are deleted here and memory leak closed */ wordlist * cp_doalias(wordlist *wlist) { @@ -68,7 +69,7 @@ cp_doalias(wordlist *wlist) nextc = wl_find(cp_csep, comm); - if(nextc == comm) { /* skip leading `;' */ + if (nextc == comm) { /* skip leading `;' */ comm = comm->wl_next; continue; } @@ -120,10 +121,11 @@ cp_setalias(char *word, wordlist *wlist) cp_unalias(word); cp_addkword(CT_ALIASES, word); + if (cp_aliases == NULL) { al = cp_aliases = alloc(struct alias); - al->al_next = NULL; - al->al_prev = NULL; + al->al_next = NULL; + al->al_prev = NULL; } else { for (al = cp_aliases; al->al_next; al = al->al_next) { if (strcmp(al->al_name, word) > 0) @@ -146,6 +148,7 @@ cp_setalias(char *word, wordlist *wlist) al = cp_aliases; } } + al->al_name = copy(word); al->al_text = wl_copy(wlist); cp_striplist(al->al_text); @@ -156,32 +159,40 @@ cp_setalias(char *word, wordlist *wlist) return; } + void cp_unalias(char *word) { struct alias *al; cp_remkword(CT_ALIASES, word); + for (al = cp_aliases; al; al = al->al_next) if (eq(word, al->al_name)) break; + if (al == NULL) return; + if (al->al_next) al->al_next->al_prev = al->al_prev; - if (al->al_prev) + + if (al->al_prev) { al->al_prev->al_next = al->al_next; - else { + } else { al->al_next->al_prev = NULL; cp_aliases = al->al_next; } + wl_free(al->al_text); tfree(al->al_name); tfree(al); cp_remcomm(word); + return; } + void cp_paliases(char *word) { @@ -197,6 +208,7 @@ cp_paliases(char *word) return; } + /* The routine for the "alias" command. */ void @@ -211,6 +223,7 @@ com_alias(wordlist *wl) return; } + void com_unalias(wordlist *wl) { @@ -226,10 +239,12 @@ com_unalias(wordlist *wl) cp_aliases = NULL; wl = wl->wl_next; } + while (wl != NULL) { cp_unalias(wl->wl_word); wl = wl->wl_next; } + return; } diff --git a/src/frontend/com_cdump.c b/src/frontend/com_cdump.c index 5abc1d4c5..f1d91f93c 100644 --- a/src/frontend/com_cdump.c +++ b/src/frontend/com_cdump.c @@ -111,7 +111,7 @@ dodump(struct control *cc) tab(indent); if (cc->co_numtimes != 1) fprintf(cp_out, "continue %d\n", - cc->co_numtimes); + cc->co_numtimes); else fprintf(cp_out, "continue\n"); break; @@ -128,6 +128,7 @@ dodump(struct control *cc) fprintf(cp_out, "bad type %d\n", cc->co_type); break; } + return; } @@ -141,59 +142,62 @@ com_cdump(wordlist *wl) indent = 0; for (c = control[stackp]; c; c = c->co_next) dodump(c); + return; } + /* dump circuit matrix to stdout or file */ void com_mdump(wordlist *wl) { CKTcircuit *ckt = NULL; char *s; - + if (!ft_curckt || !ft_curckt->ci_ckt) { fprintf(cp_err, "Error: no circuit loaded.\n"); return; } ckt = ft_curckt->ci_ckt; - + if (ckt->CKTmatrix) - if (wl == NULL) + if (wl == NULL) { SMPprint(ckt->CKTmatrix , NULL); - else { + } else { s = cp_unquote(wl->wl_word); SMPprint(ckt->CKTmatrix , s); } else fprintf(cp_err, "Error: no matrix available.\n"); - + return; } + /* dump circuit matrix RHS to stdout or file */ void com_rdump(wordlist *wl) { CKTcircuit *ckt = NULL; char *s; - + if (!ft_curckt || !ft_curckt->ci_ckt) { fprintf(cp_err, "Error: no circuit loaded.\n"); return; } ckt = ft_curckt->ci_ckt; - + if ((ckt->CKTmatrix) && (ckt->CKTrhs)) - if (wl == NULL) + if (wl == NULL) { SMPprintRHS(ckt->CKTmatrix , NULL, ckt->CKTrhs, ckt->CKTirhs); - else { + } else { s = cp_unquote(wl->wl_word); SMPprintRHS(ckt->CKTmatrix , s, ckt->CKTrhs, ckt->CKTirhs); } else fprintf(cp_err, "Error: no matrix or RHS available.\n"); - + return; } diff --git a/src/frontend/com_chdir.c b/src/frontend/com_chdir.c index a53464140..a6d9a52ce 100644 --- a/src/frontend/com_chdir.c +++ b/src/frontend/com_chdir.c @@ -31,21 +31,21 @@ com_chdir(wordlist *wl) if (wl == NULL) { - s = getenv("HOME"); + s = getenv("HOME"); #ifdef HAVE_PWD_H - if (s == NULL) { - pw = getpwuid(getuid()); - if (pw == NULL) { - fprintf(cp_err, "Can't get your password entry\n"); - return; - } - s = pw->pw_dir; - } + if (s == NULL) { + pw = getpwuid(getuid()); + if (pw == NULL) { + fprintf(cp_err, "Can't get your password entry\n"); + return; + } + s = pw->pw_dir; + } #endif } else { s = cp_unquote(wl->wl_word); - copied = 1; + copied = 1; } @@ -54,16 +54,15 @@ com_chdir(wordlist *wl) perror(s); if (copied) - tfree(s); + tfree(s); #ifdef HAVE_GETCWD s = getcwd(localbuf, sizeof(localbuf)); if (s) - printf("Current directory: %s\n", s); + printf("Current directory: %s\n", s); else - fprintf(cp_err, "Can't get current working directory.\n"); + fprintf(cp_err, "Can't get current working directory.\n"); #endif return; - } diff --git a/src/frontend/com_compose.c b/src/frontend/com_compose.c index 4c5bbf136..94c5d9c6c 100644 --- a/src/frontend/com_compose.c +++ b/src/frontend/com_compose.c @@ -13,6 +13,7 @@ #include "com_compose.h" #include "completion.h" + /* Copy the data from a vector into a buffer with larger dimensions. */ static void dimxpand(struct dvec *v, int *newdims, double *data) @@ -24,7 +25,7 @@ dimxpand(struct dvec *v, int *newdims, double *data) for (i = 0; i < MAXDIMS; i++) ncount[i] = ocount[i] = 0; - + for (;;) { for (o = n = i = 0; i < v->v_numdims; i++) { for (j = i, t = u = 1; j < v->v_numdims; j++) { @@ -41,16 +42,17 @@ dimxpand(struct dvec *v, int *newdims, double *data) realpart(cdata[n]) = realpart(v->v_compdata[o]); imagpart(cdata[n]) = imagpart(v->v_compdata[o]); } + /* Now find the nextstrchr element... */ - for (i = v->v_numdims - 1; i >= 0; i--) { - if ((ocount[i] < v->v_dims[i] - 1) && - (ncount[i] < newdims[i] - 1)) { + for (i = v->v_numdims - 1; i >= 0; i--) + if ((ocount[i] < v->v_dims[i] - 1) && (ncount[i] < newdims[i] - 1)) { ocount[i]++; ncount[i]++; break; - } else + } else { ocount[i] = ncount[i] = 0; - } + } + if (i < 0) break; } @@ -59,8 +61,6 @@ dimxpand(struct dvec *v, int *newdims, double *data) } - - /* The general syntax is 'compose name parm = val ...' * The possible parms are: * start The value at which the vector should start. @@ -118,40 +118,46 @@ com_compose(wordlist *wl) bool realflag = TRUE; int dims[MAXDIMS]; struct dvec *result, *vecs = NULL, *v, *lv = NULL; - struct pnode *pn, *first_pn=NULL; + struct pnode *pn, *first_pn = NULL; bool reverse = FALSE; resname = cp_unquote(wl->wl_word); vec_remove(resname); wl = wl->wl_next; + if (eq(wl->wl_word, "values")) { /* Build up the vector from the rest of the line... */ wl = wl->wl_next; if ((pn = ft_getpnames(wl, TRUE)) == NULL) return; - first_pn = pn; + first_pn = pn; while (pn) { if ((v = ft_evaluate(pn)) == NULL) return; + if (!vecs) vecs = lv = v; else lv->v_link2 = v; + for (lv = v; lv->v_link2; lv = lv->v_link2) ; pn = pn->pn_next; } + /* Now make sure these are all of the same dimensionality. We * can coerce the sizes... */ dim = vecs->v_numdims; if (dim < 2) dim = (vecs->v_length > 1) ? 1 : 0; + if (dim == MAXDIMS) { fprintf(cp_err, "Error: max dimensionality is %d\n", MAXDIMS); return; } + for (v = vecs; v; v = v->v_link2) if (v->v_numdims < 2) v->v_dims[0] = v->v_length; @@ -162,13 +168,14 @@ com_compose(wordlist *wl) i = (v->v_length > 1) ? 1 : 0; if (i != dim) { fprintf(cp_err, - "Error: all vectors must be of the same dimensionality\n"); + "Error: all vectors must be of the same dimensionality\n"); return; } length++; if (iscomplex(v)) realflag = FALSE; } + for (i = 0; i < dim; i++) { dims[i] = vecs->v_dims[i]; for (v = vecs->v_link2; v; v = v->v_link2) @@ -179,6 +186,7 @@ com_compose(wordlist *wl) dims[dim - 1] = length; for (i = 0, blocksize = 1; i < dim - 1; i++) blocksize *= dims[i]; + if (realflag) data = TMALLOC(double, length * blocksize); else @@ -189,23 +197,20 @@ com_compose(wordlist *wl) */ for (v = vecs, i = 0; v; v = v->v_link2) { if (dim == 1) { - if (realflag && isreal(v)) + if (realflag && isreal(v)) { data[i] = v->v_realdata[0]; - else if (isreal(v)) { - realpart(cdata[i]) = - realpart(v->v_compdata[0]); + } else if (isreal(v)) { + realpart(cdata[i]) = realpart(v->v_compdata[0]); imagpart(cdata[i]) = 0.0; } else { - realpart(cdata[i]) = - realpart(v->v_compdata[0]); - imagpart(cdata[i]) = - imagpart(v->v_compdata[0]); + realpart(cdata[i]) = realpart(v->v_compdata[0]); + imagpart(cdata[i]) = imagpart(v->v_compdata[0]); } i++; continue; } - dimxpand(v, dims, (realflag ? (data + i * blocksize) : - (double *) (cdata + i * blocksize))); + dimxpand(v, dims, (realflag ? (data + i * blocksize) : + (double *) (cdata + i * blocksize))); } length *= blocksize; @@ -238,7 +243,7 @@ com_compose(wordlist *wl) val = wl->wl_word; if (*val != '=') { fprintf(cp_err, - "Error: bad syntax\n"); + "Error: bad syntax\n"); return; } val++; @@ -248,7 +253,7 @@ com_compose(wordlist *wl) val = wl->wl_word; } else { fprintf(cp_err, - "Error: bad syntax\n"); + "Error: bad syntax\n"); return; } } @@ -262,8 +267,7 @@ com_compose(wordlist *wl) startgiven = TRUE; if ((td = ft_numparse(&val, FALSE)) == NULL) { fprintf(cp_err, - "Error: bad parm %s = %s\n", - var, val); + "Error: bad parm %s = %s\n", var, val); return; } start = *td; @@ -271,8 +275,7 @@ com_compose(wordlist *wl) stopgiven = TRUE; if ((td = ft_numparse(&val, FALSE)) == NULL) { fprintf(cp_err, - "Error: bad parm %s = %s\n", - var, val); + "Error: bad parm %s = %s\n", var, val); return; } stop = *td; @@ -280,8 +283,7 @@ com_compose(wordlist *wl) stepgiven = TRUE; if ((td = ft_numparse(&val, FALSE)) == NULL) { fprintf(cp_err, - "Error: bad parm %s = %s\n", - var, val); + "Error: bad parm %s = %s\n", var, val); return; } step = *td; @@ -289,8 +291,7 @@ com_compose(wordlist *wl) centergiven = TRUE; if ((td = ft_numparse(&val, FALSE)) == NULL) { fprintf(cp_err, - "Error: bad parm %s = %s\n", - var, val); + "Error: bad parm %s = %s\n", var, val); return; } center = *td; @@ -298,8 +299,7 @@ com_compose(wordlist *wl) spangiven = TRUE; if ((td = ft_numparse(&val, FALSE)) == NULL) { fprintf(cp_err, - "Error: bad parm %s = %s\n", - var, val); + "Error: bad parm %s = %s\n", var, val); return; } span = *td; @@ -307,8 +307,7 @@ com_compose(wordlist *wl) meangiven = TRUE; if ((td = ft_numparse(&val, FALSE)) == NULL) { fprintf(cp_err, - "Error: bad parm %s = %s\n", - var, val); + "Error: bad parm %s = %s\n", var, val); return; } mean = *td; @@ -316,8 +315,7 @@ com_compose(wordlist *wl) sdgiven = TRUE; if ((td = ft_numparse(&val, FALSE)) == NULL) { fprintf(cp_err, - "Error: bad parm %s = %s\n", - var, val); + "Error: bad parm %s = %s\n", var, val); return; } sd = *td; @@ -325,8 +323,7 @@ com_compose(wordlist *wl) lingiven = TRUE; if ((td = ft_numparse(&val, FALSE)) == NULL) { fprintf(cp_err, - "Error: bad parm %s = %s\n", - var, val); + "Error: bad parm %s = %s\n", var, val); return; } lin = *td; @@ -334,8 +331,7 @@ com_compose(wordlist *wl) loggiven = TRUE; if ((td = ft_numparse(&val, FALSE)) == NULL) { fprintf(cp_err, - "Error: bad parm %s = %s\n", - var, val); + "Error: bad parm %s = %s\n", var, val); return; } log = (int)(*td); @@ -343,8 +339,7 @@ com_compose(wordlist *wl) decgiven = TRUE; if ((td = ft_numparse(&val, FALSE)) == NULL) { fprintf(cp_err, - "Error: bad parm %s = %s\n", - var, val); + "Error: bad parm %s = %s\n", var, val); return; } dec = (int)(*td); @@ -352,8 +347,7 @@ com_compose(wordlist *wl) gaussgiven = TRUE; if ((td = ft_numparse(&val, FALSE)) == NULL) { fprintf(cp_err, - "Error: bad parm %s = %s\n", - var, val); + "Error: bad parm %s = %s\n", var, val); return; } gauss = (int)(*td); @@ -361,8 +355,7 @@ com_compose(wordlist *wl) randmgiven = TRUE; if ((td = ft_numparse(&val, FALSE)) == NULL) { fprintf(cp_err, - "Error: bad parm %s = %s\n", - var, val); + "Error: bad parm %s = %s\n", var, val); return; } randm = (int)(*td); @@ -373,11 +366,10 @@ com_compose(wordlist *wl) } #ifdef LINT -/* XXX Now, doesn't this look just a little suspicious */ - if (centergiven || spangiven || meangiven || sdgiven || - poolgiven) + /* XXX Now, doesn't this look just a little suspicious */ + if (centergiven || spangiven || meangiven || sdgiven || poolgiven) j = k = l = m = q = inds = center + span + mean + sd + - log + dec + gauss + randm + pool; + log + dec + gauss + randm + pool; #endif /* Now see what we have... start and stop are pretty much * compatible with everything... @@ -386,19 +378,19 @@ com_compose(wordlist *wl) fprintf(cp_err, "Error: step cannot = 0.0\n"); return; } + if (startgiven && stopgiven && (start > stop)) { tt = start; start = stop; stop = tt; reverse = TRUE; } - if (lingiven + loggiven + decgiven + randmgiven + gaussgiven - > 1) { + + if (lingiven + loggiven + decgiven + randmgiven + gaussgiven > 1) { fprintf(cp_err, - "Error: can have at most one of (lin, log, dec, random, gauss)\n"); + "Error: can have at most one of (lin, log, dec, random, gauss)\n"); return; - } else if (lingiven + loggiven + decgiven + randmgiven + - gaussgiven == 0) { + } else if (lingiven + loggiven + decgiven + randmgiven + gaussgiven == 0) { /* Hmm, if we have a start, stop, and step we're ok. */ if (startgiven && stopgiven && stepgiven) { lingiven = TRUE; @@ -406,33 +398,31 @@ com_compose(wordlist *wl) stepgiven = FALSE; /* Problems below... */ } else { fprintf(cp_err, -"Error: either one of (lin, log, dec, random, gauss) must be given, or all\n"); + "Error: either one of (lin, log, dec, random, gauss) must be given, or all\n"); fprintf(cp_err, - "\tof (start, stop, and step) must be given.\n"); + "\tof (start, stop, and step) must be given.\n"); return; } } + if (lingiven) { /* Create a linear sweep... */ data = TMALLOC(double, (int) lin); if (stepgiven && startgiven && stopgiven) { - if (step != (stop - start) / lin * (reverse ? - -1 : 1)) { - fprintf(cp_err, - "Warning: bad step -- should be %g\n", - (stop - start) / lin * - (reverse ? -1 : 1)); + if (step != (stop - start) / lin * (reverse ? -1 : 1)) { + fprintf(cp_err, + "Warning: bad step -- should be %g\n", + (stop - start) / lin * (reverse ? -1 : 1)); stepgiven = FALSE; } - } + } if (!startgiven) { - if (stopgiven && stepgiven) { + if (stopgiven && stepgiven) start = stop - step * lin; - } else if (stopgiven) { + else if (stopgiven) start = stop - lin; - } else { + else start = 0; - } startgiven = TRUE; } if (!stopgiven) { @@ -441,17 +431,15 @@ com_compose(wordlist *wl) else stop = start + lin; stopgiven = TRUE; - } + } if (!stepgiven) { step = (stop - start) / lin; } if (reverse) - for (i = 0, tt = stop; i < lin; - i++, tt -= step) + for (i = 0, tt = stop; i < lin; i++, tt -= step) data[i] = tt; else - for (i = 0, tt = start; i < lin; - i++, tt += step) + for (i = 0, tt = start; i < lin; i++, tt += step) data[i] = tt; length = (int)lin; } else if (loggiven || decgiven) { @@ -462,10 +450,12 @@ com_compose(wordlist *wl) /* Create a gaussian distribution... */ } } + result = alloc(struct dvec); ZERO(result, struct dvec); result->v_name = copy(resname); result->v_type = type; + if (realflag) { result->v_flags = VF_REAL | VF_PERMANENT; result->v_realdata = data; @@ -473,12 +463,14 @@ com_compose(wordlist *wl) result->v_flags = VF_COMPLEX | VF_PERMANENT; result->v_compdata = cdata; } + result->v_length = length; result->v_numdims = 1; result->v_dims[0] = length; + vec_new(result); cp_addkword(CT_VECTOR, result->v_name); free_pnode(first_pn); - tfree(resname);/*DG: resname has been copied so its remains allocated: memory leak One can remove this and not copy resname*/ + tfree(resname); /*DG: resname has been copied so its remains allocated: memory leak One can remove this and not copy resname*/ return; } diff --git a/src/frontend/com_display.c b/src/frontend/com_display.c index a360d9bc6..22e61c261 100644 --- a/src/frontend/com_display.c +++ b/src/frontend/com_display.c @@ -22,7 +22,6 @@ dcomp(const void *d1, const void *d2) } - /* Display vector status, etc. Note that this only displays stuff * from the current plot, and you must do a setplot to see the rest of * it. */ @@ -37,13 +36,13 @@ com_display(wordlist *wl) /* Maybe he wants to know about just a few vectors. */ out_init(); + while (wl) { s = cp_unquote(wl->wl_word); d = vec_get(s); - tfree(s);/*DG to avoid the cp_unquote memory leak */ + tfree(s); /*DG to avoid the cp_unquote memory leak */ if (d == NULL) - fprintf(cp_err, "Error: no such vector as %s.\n", - wl->wl_word); + fprintf(cp_err, "Error: no such vector as %s.\n", wl->wl_word); else while (d) { pvec(d); @@ -53,27 +52,32 @@ com_display(wordlist *wl) return; wl = wl->wl_next; } + if (plot_cur) for (d = plot_cur->pl_dvecs; d; d = d->v_next) len++; + if (len == 0) { fprintf(cp_out, "There are no vectors currently active.\n"); return; } + out_printf("Here are the vectors currently active:\n\n"); dvs = TMALLOC(struct dvec *, len); for (d = plot_cur->pl_dvecs, i = 0; d; d = d->v_next, i++) dvs[i] = d; if (!cp_getvar("nosort", CP_BOOL, NULL)) - qsort(dvs, (size_t) len, sizeof (struct dvec *), dcomp); + qsort(dvs, (size_t) len, sizeof(struct dvec *), dcomp); + + out_printf("Title: %s\n", plot_cur->pl_title); + out_printf("Name: %s (%s)\nDate: %s\n\n", + plot_cur->pl_typename, plot_cur->pl_name, + plot_cur->pl_date); - out_printf("Title: %s\n", plot_cur->pl_title); - out_printf("Name: %s (%s)\nDate: %s\n\n", - plot_cur->pl_typename, plot_cur->pl_name, - plot_cur->pl_date); for (i = 0; i < len; i++) { d = dvs[i]; pvec(d); } + return; } diff --git a/src/frontend/com_dl.c b/src/frontend/com_dl.c index e0a40bddf..ce58d884b 100644 --- a/src/frontend/com_dl.c +++ b/src/frontend/com_dl.c @@ -4,22 +4,26 @@ #include <../spicelib/devices/dev.h> /*for load library commands*/ #include "com_dl.h" + #ifdef XSPICE -void com_codemodel(wordlist *wl){ - wordlist *ww; - for(ww = wl;ww;ww = ww->wl_next) - if(load_opus(wl->wl_word)) - fprintf(cp_err,"Error: Library %s couldn't be loaded!\n",ww->wl_word); - return; -} -#endif -#ifdef DEVLIB -void com_use(wordlist *wl){ - wordlist *ww; - for(ww = wl;ww;ww = ww->wl_next) - if(load_dev(wl->wl_word)) - fprintf(cp_err,"Error: Library %s couldn't be loaded!\n",ww->wl_word); - return; +void com_codemodel(wordlist *wl) +{ + wordlist *ww; + for (ww = wl; ww; ww = ww->wl_next) + if (load_opus(wl->wl_word)) + fprintf(cp_err, "Error: Library %s couldn't be loaded!\n", ww->wl_word); + return; } #endif + +#ifdef DEVLIB +void com_use(wordlist *wl) +{ + wordlist *ww; + for (ww = wl; ww; ww = ww->wl_next) + if (load_dev(wl->wl_word)) + fprintf(cp_err, "Error: Library %s couldn't be loaded!\n", ww->wl_word); + return; +} +#endif diff --git a/src/frontend/com_echo.c b/src/frontend/com_echo.c index 1e814f69f..fa316a21b 100644 --- a/src/frontend/com_echo.c +++ b/src/frontend/com_echo.c @@ -11,6 +11,7 @@ #include "quote.h" #include "ngspice/cpextern.h" + void com_echo(wordlist *wlist) { char*copyword; @@ -22,15 +23,15 @@ com_echo(wordlist *wlist) } while (wlist) { - /* fputs(cp_unquote(wlist->wl_word), cp_out); very bad the string allocated by cp_unquote could not be freed: memory leak*/ - copyword=cp_unquote(wlist->wl_word); - fputs(copyword, cp_out); - tfree(copyword); + /* fputs(cp_unquote(wlist->wl_word), cp_out); very bad the string allocated by cp_unquote could not be freed: memory leak*/ + copyword = cp_unquote(wlist->wl_word); + fputs(copyword, cp_out); + tfree(copyword); if (wlist->wl_next) fputs(" ", cp_out); wlist = wlist->wl_next; } + if (nl) fputs("\n", cp_out); } - diff --git a/src/frontend/com_fft.c b/src/frontend/com_fft.c index de3f4535c..59b28fa55 100644 --- a/src/frontend/com_fft.c +++ b/src/frontend/com_fft.c @@ -20,8 +20,10 @@ Author: 2008 Holger Vogt #include "../misc/misc_time.h" #include "ngspice/fftext.h" + static void fftext(double*, double*, long int, long int, int); + void com_fft(wordlist *wl) { @@ -76,85 +78,81 @@ com_fft(wordlist *wl) /* window functions - should have an average of one */ win = TMALLOC(double, tlen); { - char window[BSIZE_SP]; - double maxt = time[tlen-1]; - if (!cp_getvar("specwindow", CP_STRING, window)) - strcpy(window,"blackman"); - if (eq(window, "none")) - for(i=0; i span) { - win[i] = 0.0; - } else { + char window[BSIZE_SP]; + double maxt = time[tlen-1]; + if (!cp_getvar("specwindow", CP_STRING, window)) + strcpy(window, "blackman"); + if (eq(window, "none")) + for (i = 0; i < tlen; i++) win[i] = 1.0; - } - } - else if (eq(window, "triangle") || eq(window, "bartlet") || eq(window, "bartlett")) - for(i=0; i span) { - win[i] = 0.0; - } else { - win[i] = 2.0 - fabs(2+4*(time[i]-maxt)/span); - } - } - else if (eq(window, "hann") || eq(window, "hanning") || eq(window, "cosine")) - for(i=0; i span) { - win[i] = 0.0; - } else { - win[i] = 1.0 - cos(2*M_PI*(time[i]-maxt)/span); - } - } - else if (eq(window, "hamming")) - for(i=0; i span) { - win[i] = 0.0; - } else { - win[i] = 1.0 - 0.46/0.54*cos(2*M_PI*(time[i]-maxt)/span); - } - } - else if (eq(window, "blackman")) - for(i=0; i span) { - win[i] = 0; - } else { - win[i] = 1.0; - win[i] -= 0.50/0.42*cos(2*M_PI*(time[i]-maxt)/span); - win[i] += 0.08/0.42*cos(4*M_PI*(time[i]-maxt)/span); - } - } - else if (eq(window, "flattop")) - for(i=0; i span) { - win[i] = 0; - } else { - win[i] = 1.0; - win[i] -= 1.93*cos(2*M_PI*(time[i]-maxt)/span); - win[i] += 1.29*cos(4*M_PI*(time[i]-maxt)/span); - win[i] -= 0.388*cos(6*M_PI*(time[i]-maxt)/span); - win[i] += 0.032*cos(8*M_PI*(time[i]-maxt)/span); - } - } - else if (eq(window, "gaussian")) { - if (!cp_getvar("specwindoworder", CP_NUM, &order)) order = 2; - if (order < 2) order = 2; - sigma=1.0/order; - scale=0.83/sigma; - for(i=0; i span) { - win[i] = 0; - } else { - win[i] = scale*exp(-0.5*pow((time[i]-maxt/2)/(sigma*maxt/2),2)); - } - } - } else { - fprintf(cp_err, "Warning: unknown window type %s\n", window); - tfree(win); - return; - } + else if (eq(window, "rectangular")) + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) + win[i] = 0.0; + else + win[i] = 1.0; + } + else if (eq(window, "triangle") || eq(window, "bartlet") || eq(window, "bartlett")) + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) + win[i] = 0.0; + else + win[i] = 2.0 - fabs(2+4*(time[i]-maxt)/span); + } + else if (eq(window, "hann") || eq(window, "hanning") || eq(window, "cosine")) + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) + win[i] = 0.0; + else + win[i] = 1.0 - cos(2*M_PI*(time[i]-maxt)/span); + } + else if (eq(window, "hamming")) + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) + win[i] = 0.0; + else + win[i] = 1.0 - 0.46/0.54*cos(2*M_PI*(time[i]-maxt)/span); + } + else if (eq(window, "blackman")) + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) { + win[i] = 0; + } else { + win[i] = 1.0; + win[i] -= 0.50/0.42*cos(2*M_PI*(time[i]-maxt)/span); + win[i] += 0.08/0.42*cos(4*M_PI*(time[i]-maxt)/span); + } + } + else if (eq(window, "flattop")) + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) { + win[i] = 0; + } else { + win[i] = 1.0; + win[i] -= 1.93*cos(2*M_PI*(time[i]-maxt)/span); + win[i] += 1.29*cos(4*M_PI*(time[i]-maxt)/span); + win[i] -= 0.388*cos(6*M_PI*(time[i]-maxt)/span); + win[i] += 0.032*cos(8*M_PI*(time[i]-maxt)/span); + } + } + else if (eq(window, "gaussian")) { + if (!cp_getvar("specwindoworder", CP_NUM, &order)) + order = 2; + if (order < 2) + order = 2; + sigma = 1.0/order; + scale = 0.83/sigma; + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) + win[i] = 0; + else + win[i] = scale*exp(-0.5 * pow((time[i]-maxt/2)/(sigma*maxt/2), 2)); + } + } else { + fprintf(cp_err, "Warning: unknown window type %s\n", window); + tfree(win); + return; + } } names = ft_getpnames(wl, TRUE); @@ -172,8 +170,7 @@ com_fft(wordlist *wl) continue; } if (!isreal(vec)) { - fprintf(cp_err, "Error: %s isn't real!\n", - vec->v_name); + fprintf(cp_err, "Error: %s isn't real!\n", vec->v_name); vec = vec->v_link2; continue; } @@ -192,8 +189,8 @@ com_fft(wordlist *wl) } free_pnode_o(first_name); if (!ngood) { - tfree(win); - return; + tfree(win); + return; } plot_cur = plot_alloc("spectrum"); @@ -201,7 +198,7 @@ com_fft(wordlist *wl) plot_list = plot_cur; plot_cur->pl_title = copy((plot_cur->pl_next)->pl_title); plot_cur->pl_name = copy("Spectrum"); - plot_cur->pl_date = copy(datestring( )); + plot_cur->pl_date = copy(datestring()); freq = TMALLOC(double, fpts); f = alloc(struct dvec); @@ -213,23 +210,23 @@ com_fft(wordlist *wl) f->v_realdata = freq; vec_new(f); - for (i = 0; iv_realdata; /* real input data */ - fdvec[i] = TMALLOC(ngcomplex_t, fpts); /* complex output data */ - f = alloc(struct dvec); - ZERO(f, struct dvec); - f->v_name = vec_basename(vec); - f->v_type = SV_NOTYPE; - f->v_flags = (VF_COMPLEX | VF_PERMANENT); - f->v_length = fpts; - f->v_compdata = fdvec[i]; - vec_new(f); - vec = vec->v_link2; + tdvec[i] = vec->v_realdata; /* real input data */ + fdvec[i] = TMALLOC(ngcomplex_t, fpts); /* complex output data */ + f = alloc(struct dvec); + ZERO(f, struct dvec); + f->v_name = vec_basename(vec); + f->v_type = SV_NOTYPE; + f->v_flags = (VF_COMPLEX | VF_PERMANENT); + f->v_length = fpts; + f->v_compdata = fdvec[i]; + vec_new(f); + vec = vec->v_link2; } sign = 1; @@ -240,22 +237,22 @@ com_fft(wordlist *wl) reald = TMALLOC(double, size); imagd = TMALLOC(double, size); for (i = 0; ipl_scale) || + if (!isreal(plot_cur->pl_scale) || ((plot_cur->pl_scale)->v_type != SV_TIME)) { fprintf(cp_err, "Error: fft needs real time scale\n"); return; } - + tlen = (plot_cur->pl_scale)->v_length; time = (plot_cur->pl_scale)->v_realdata; span = time[tlen-1] - time[0]; delta_t = span/(tlen - 1); - + // get filter length from parameter input s = wl->wl_word; ave = ft_numparse(&s, FALSE); if (!ave || (*ave < 1.0)) { - fprintf(cp_out, "Number of averaged data points: %d\n", 1); + fprintf(cp_out, "Number of averaged data points: %d\n", 1); smooth = 1; + } else { + smooth = (int)(*ave); } - else smooth = (int)(*ave); - wl = wl->wl_next; - + + wl = wl->wl_next; + // size of input vector is power of two and larger than spice vector size = 1; mm = 0; @@ -331,96 +332,97 @@ com_psd(wordlist *wl) } // output vector has length of size/2 - fpts = size>>1; + fpts = size>>1; - // window function + // window function win = TMALLOC(double, tlen); { - char window[BSIZE_SP]; - double maxt = time[tlen-1]; - if (!cp_getvar("specwindow", CP_STRING, window)) - strcpy(window,"blackman"); - if (eq(window, "none")) - for(i=0; i span) { - win[i] = 0; - } else { + char window[BSIZE_SP]; + double maxt = time[tlen-1]; + if (!cp_getvar("specwindow", CP_STRING, window)) + strcpy(window, "blackman"); + if (eq(window, "none")) + for (i = 0; i < tlen; i++) win[i] = 1; - } - } - else if (eq(window, "hanning") || eq(window, "cosine")) - for(i=0; i span) { - win[i] = 0; - } else { - win[i] = 1 - cos(2*M_PI*(time[i]-maxt)/span); - } - } - else if (eq(window, "hamming")) - for(i=0; i span) { - win[i] = 0; - } else { - win[i] = 1 - 0.92/1.08*cos(2*M_PI*(time[i]-maxt)/span); - } - } - else if (eq(window, "triangle") || eq(window, "bartlet")) - for(i=0; i span) { - win[i] = 0; - } else { - win[i] = 2 - fabs(2+4*(time[i]-maxt)/span); - } - } - else if (eq(window, "blackman")) { - int order; - if (!cp_getvar("specwindoworder", CP_NUM, &order)) order = 2; - if (order < 2) order = 2; /* only order 2 supported here */ - for(i=0; i span) { - win[i] = 0; - } else { - win[i] = 1; - win[i] -= 0.50/0.42*cos(2*M_PI*(time[i]-maxt)/span); - win[i] += 0.08/0.42*cos(4*M_PI*(time[i]-maxt)/span); - } - } - } else if (eq(window, "gaussian")) { - if (!cp_getvar("specwindoworder", CP_NUM, &order)) order = 2; - if (order < 2) order = 2; - sigma=1.0/order; - scale=0.83/sigma; - for(i=0; i span) { - win[i] = 0; - } else { - win[i] = scale*exp(-0.5*pow((time[i]-maxt/2)/(sigma*maxt/2),2)); - } - } -/* int order; - double scale; - extern double erfc(double); - if (!cp_getvar("specwindoworder", CP_NUM, &order)) order = 2; - if (order < 2) order = 2; - scale = pow(2*M_PI/order,0.5)*(0.5-erfc(pow(order,0.5))); - for(i=0; i span) { - win[i] = 0; - } else { - win[i] = exp(-0.5*order*(1-2*(maxt-time[i])/span) - *(1-2*(maxt-time[i])/span))/scale; - } - } -*/ - } else { - fprintf(cp_err, "Warning: unknown window type %s\n", window); - tfree(win); - return; - } + else if (eq(window, "rectangular")) + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) + win[i] = 0; + else + win[i] = 1; + } + else if (eq(window, "hanning") || eq(window, "cosine")) + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) + win[i] = 0; + else + win[i] = 1 - cos(2*M_PI*(time[i]-maxt)/span); + } + else if (eq(window, "hamming")) + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) + win[i] = 0; + else + win[i] = 1 - 0.92/1.08*cos(2*M_PI*(time[i]-maxt)/span); + } + else if (eq(window, "triangle") || eq(window, "bartlet")) + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) + win[i] = 0; + else + win[i] = 2 - fabs(2+4*(time[i]-maxt)/span); + } + else if (eq(window, "blackman")) { + int order; + if (!cp_getvar("specwindoworder", CP_NUM, &order)) + order = 2; + if (order < 2) + order = 2; /* only order 2 supported here */ + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) { + win[i] = 0; + } else { + win[i] = 1; + win[i] -= 0.50/0.42*cos(2*M_PI*(time[i]-maxt)/span); + win[i] += 0.08/0.42*cos(4*M_PI*(time[i]-maxt)/span); + } + } + } else if (eq(window, "gaussian")) { + if (!cp_getvar("specwindoworder", CP_NUM, &order)) + order = 2; + if (order < 2) + order = 2; + sigma = 1.0/order; + scale = 0.83/sigma; + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) + win[i] = 0; + else + win[i] = scale*exp(-0.5 * pow((time[i]-maxt/2)/(sigma*maxt/2), 2)); + } + /* + * int order; + * double scale; + * extern double erfc(double); + * if (!cp_getvar("specwindoworder", CP_NUM, &order)) + * order = 2; + * if (order < 2) + * order = 2; + * scale = pow(2*M_PI/order, 0.5)*(0.5-erfc(pow(order, 0.5))); + * for (i = 0; i < tlen; i++) { + * if (maxt-time[i] > span) { + * win[i] = 0; + * } else { + * win[i] = exp(-0.5*order*(1-2*(maxt-time[i])/span) + * *(1-2*(maxt-time[i])/span))/scale; + * } + * } + */ + } else { + fprintf(cp_err, "Warning: unknown window type %s\n", window); + tfree(win); + return; + } } names = ft_getpnames(wl, TRUE); @@ -438,8 +440,7 @@ com_psd(wordlist *wl) continue; } if (!isreal(vec)) { - fprintf(cp_err, "Error: %s isn't real!\n", - vec->v_name); + fprintf(cp_err, "Error: %s isn't real!\n", vec->v_name); vec = vec->v_link2; continue; } @@ -457,16 +458,15 @@ com_psd(wordlist *wl) } } free_pnode_o(first_name); - if (!ngood) { - return; - } - + if (!ngood) + return; + plot_cur = plot_alloc("spectrum"); plot_cur->pl_next = plot_list; plot_list = plot_cur; plot_cur->pl_title = copy((plot_cur->pl_next)->pl_title); plot_cur->pl_name = copy("PSD"); - plot_cur->pl_date = copy(datestring( )); + plot_cur->pl_date = copy(datestring()); freq = TMALLOC(double, fpts + 1); f = alloc(struct dvec); @@ -478,22 +478,23 @@ com_psd(wordlist *wl) f->v_realdata = freq; vec_new(f); - for (i = 0; i <= fpts; i++) freq[i] = i*1./span*tlen/size; + for (i = 0; i <= fpts; i++) + freq[i] = i*1./span*tlen/size; tdvec = TMALLOC(double*, ngood); fdvec = TMALLOC(ngcomplex_t*, ngood); for (i = 0, vec = vlist; iv_realdata; /* real input data */ - fdvec[i] = TMALLOC(ngcomplex_t, fpts + 1); /* complex output data */ - f = alloc(struct dvec); - ZERO(f, struct dvec); - f->v_name = vec_basename(vec); - f->v_type = SV_NOTYPE; //vec->v_type; - f->v_flags = (VF_COMPLEX | VF_PERMANENT); - f->v_length = fpts + 1; - f->v_compdata = fdvec[i]; - vec_new(f); - vec = vec->v_link2; + tdvec[i] = vec->v_realdata; /* real input data */ + fdvec[i] = TMALLOC(ngcomplex_t, fpts + 1); /* complex output data */ + f = alloc(struct dvec); + ZERO(f, struct dvec); + f->v_name = vec_basename(vec); + f->v_type = SV_NOTYPE; //vec->v_type; + f->v_flags = (VF_COMPLEX | VF_PERMANENT); + f->v_length = fpts + 1; + f->v_compdata = fdvec[i]; + vec_new(f); + vec = vec->v_link2; } printf("PSD: Time span: %g s, input length: %lu, zero padding: %lu\n", span, size, size-tlen); @@ -501,169 +502,168 @@ com_psd(wordlist *wl) sign = 1; isreal = 1; - + reald = TMALLOC(double, size); imagd = TMALLOC(double, size); - -// scale = 0.66; + + // scale = 0.66; for (i = 0; i>1; - for (j=0; j> 1; - j = 0; - for (i=0;i>= 1; - } - j += k; - } + /* Do the bit reversal */ + i2 = n >> 1; + j = 0; + for (i = 0; i < n-1; i++) { + if (i < j) { + tx = x[i]; + ty = y[i]; + x[i] = x[j]; + y[i] = y[j]; + x[j] = tx; + y[j] = ty; + } + k = i2; + while (k <= j) { + j -= k; + k >>= 1; + } + j += k; + } - /* Compute the FFT */ - c1 = -1.0; - c2 = 0.0; - l2 = 1; - for (l=0;lwl_word; wl = wl->wl_next; } - if (!wl) { - return; - } + + if (!wl) + return; + if (cieq(fname, "temp") || cieq(fname, "tmp")) { fname = smktemp("gp"); /* Is this the correct name ? */ tempf = TRUE; @@ -33,13 +34,13 @@ com_gnuplot(wordlist *wl) /* Leave temp file sitting around so gnuplot can grab it from background. */ - if (tempf) { + if (tempf) tfree(fname); - } return; } + /* data printout to file plotargs */ void com_write_simple(wordlist *wl) @@ -51,9 +52,10 @@ com_write_simple(wordlist *wl) fname = wl->wl_word; wl = wl->wl_next; } - if (!wl) { - return; - } + + if (!wl) + return; + if (cieq(fname, "temp") || cieq(fname, "tmp")) { fname = smktemp("gp"); /* Is this the correct name ? */ tempf = TRUE; @@ -63,9 +65,8 @@ com_write_simple(wordlist *wl) /* Leave temp file sitting around so gnuplot can grab it from background. */ - if (tempf) { + if (tempf) tfree(fname); - } return; } diff --git a/src/frontend/com_hardcopy.c b/src/frontend/com_hardcopy.c index 7daf2889a..08b213c4f 100644 --- a/src/frontend/com_hardcopy.c +++ b/src/frontend/com_hardcopy.c @@ -34,7 +34,7 @@ com_hardcopy(wordlist *wl) #if defined(SYSTEM_PLOT5LPR) || defined(SYSTEM_PSLPR) char format[513]; #endif - int printed; + int printed; int hc_button; int foundit; @@ -51,47 +51,44 @@ com_hardcopy(wordlist *wl) tempf = TRUE; } - if (!cp_getvar("hcopydevtype", CP_STRING, buf)) { + if (!cp_getvar("hcopydevtype", CP_STRING, buf)) devtype = "postscript"; - } else { + else devtype = buf; - } /* enable screen plot selection for these display types */ foundit = 0; -// PushGraphContext(currentgraph); + // PushGraphContext(currentgraph); #ifdef HAS_WINDOWS if (!wl && hc_button) { - char* psfname; - GRAPH *tempgraph; - if (DevSwitch(devtype)) return; + char *psfname; + GRAPH *tempgraph; + if (DevSwitch(devtype)) + return; tempgraph = CopyGraph(currentgraph); - /* change .tmp to .ps */ + /* change .tmp to .ps */ psfname = strchr(fname, '.'); - if(psfname) - { + if (psfname) { *(psfname + 1) = 'p'; - *(psfname + 2) = 's'; - *(psfname + 3) = '\0'; + *(psfname + 2) = 's'; + *(psfname + 3) = '\0'; + } else { + fname = realloc(fname, strlen(fname)+4); + strcat(fname, ".ps"); } - else - { - fname=realloc(fname,strlen(fname)+4); - strcat(fname,".ps"); + tempgraph->devdep = fname; + if (NewViewport(tempgraph)) { + DevSwitch(NULL); + return; } - tempgraph->devdep = fname; - if (NewViewport(tempgraph)) { - DevSwitch(NULL); - return; - } - gr_resize(tempgraph); - gr_redraw(tempgraph); - DestroyGraph(tempgraph->graphid); - DevSwitch(NULL); - foundit = 1; + gr_resize(tempgraph); + gr_redraw(tempgraph); + DestroyGraph(tempgraph->graphid); + DevSwitch(NULL); + foundit = 1; } #endif @@ -102,38 +99,40 @@ com_hardcopy(wordlist *wl) REQUEST request; RESPONSE response; GRAPH *tempgraph; - + request.option = click_option; Input(&request, &response); - if (response.option == error_option) return; + if (response.option == error_option) + return; if (response.reply.graph) { - if (DevSwitch(devtype)) return; - tempgraph = CopyGraph(response.reply.graph); - tempgraph->devdep = fname; - if (NewViewport(tempgraph)) { - DevSwitch(NULL); - return; - } - /* save current graphics context */ - PushGraphContext(currentgraph); - currentgraph = tempgraph; - /* some operations in gr_resize, gr_redraw, and DevSwitch - will be done on currentgraph, not only on tempgraph */ - gr_resize(tempgraph); - gr_redraw(tempgraph); - DevSwitch(NULL); - /* retrieve current graphics context */ - PopGraphContext(); - DestroyGraph(tempgraph->graphid); - foundit = 1; - } + if (DevSwitch(devtype)) + return; + tempgraph = CopyGraph(response.reply.graph); + tempgraph->devdep = fname; + if (NewViewport(tempgraph)) { + DevSwitch(NULL); + return; + } + /* save current graphics context */ + PushGraphContext(currentgraph); + currentgraph = tempgraph; + /* some operations in gr_resize, gr_redraw, and DevSwitch + will be done on currentgraph, not only on tempgraph */ + gr_resize(tempgraph); + gr_redraw(tempgraph); + DevSwitch(NULL); + /* retrieve current graphics context */ + PopGraphContext(); + DestroyGraph(tempgraph->graphid); + foundit = 1; + } } #endif /* save current graphics context, because plotit() will create a new - currentgraph */ + currentgraph */ PushGraphContext(currentgraph); if (!foundit) { @@ -148,7 +147,8 @@ com_hardcopy(wordlist *wl) wl = process(wl); } - if (DevSwitch(devtype)) return; + if (DevSwitch(devtype)) + return; if (!wl || !plotit(wl, fname, NULL)) { printf("com_hardcopy: graph not defined\n"); @@ -174,7 +174,7 @@ com_hardcopy(wordlist *wl) #endif #ifdef SYSTEM_PSLPR if (!printed && !strcmp(devtype, "postscript")) { - /* note: check if that was a postscript printer XXX */ + /* note: check if that was a postscript printer XXX */ if (!cp_getvar("lprps", CP_STRING, format)) strcpy(format, SYSTEM_PSLPR); (void) sprintf(buf, format, device, fname); @@ -188,18 +188,18 @@ com_hardcopy(wordlist *wl) if (!printed) { if (!strcmp(devtype, "plot5")) { fprintf(cp_out, - "The file \"%s\" may be printed with the Unix \"plot\" command,\n", - fname); - fprintf(cp_out, - "\tor by using the '-g' flag to the Unix lpr command.\n"); + "The file \"%s\" may be printed with the Unix \"plot\" command,\n", + fname); + fprintf(cp_out, + "\tor by using the '-g' flag to the Unix lpr command.\n"); } else if (!strcmp(devtype, "postscript")) { fprintf(cp_out, - "\nThe file \"%s\" may be printed on a postscript printer.\n", - fname); + "\nThe file \"%s\" may be printed on a postscript printer.\n", + fname); } else if (!strcmp(devtype, "MFB")) { fprintf(cp_out, - "The file \"%s\" may be printed on a MFB device.\n", - fname); + "The file \"%s\" may be printed on a MFB device.\n", + fname); } } diff --git a/src/frontend/com_help.c b/src/frontend/com_help.c index 6000407c3..e47f42187 100644 --- a/src/frontend/com_help.c +++ b/src/frontend/com_help.c @@ -29,25 +29,25 @@ com_help(wordlist *wl) out_init(); out_moremode = FALSE; if (wl == NULL) { - out_printf("For a complete description " - "read the Spice3 User's Manual.\n"); + out_printf("For a complete description " + "read the Spice3 User's Manual.\n"); - if (!allflag) { - out_printf("For a list of all commands " - "type \"help all\", for a short\n" - "description of \"command\", " - "type \"help command\".\n"); - } + if (!allflag) { + out_printf("For a list of all commands " + "type \"help all\", for a short\n" + "description of \"command\", " + "type \"help command\".\n"); + } /* Sort the commands */ for (numcoms = 0; cp_coms[numcoms].co_func != NULL; numcoms++) ccc[numcoms] = &cp_coms[numcoms]; - qsort(ccc, (size_t) numcoms, sizeof (struct comm *), hcomp); + qsort(ccc, (size_t) numcoms, sizeof(struct comm *), hcomp); for (i = 0; i < numcoms; i++) { - if ((ccc[i]->co_spiceonly && ft_nutmeg) || - (ccc[i]->co_help == NULL) || - (!allflag && !ccc[i]->co_major)) + if ((ccc[i]->co_spiceonly && ft_nutmeg) || + (ccc[i]->co_help == NULL) || + (!allflag && !ccc[i]->co_major)) continue; out_printf("%s ", ccc[i]->co_comname); out_printf(ccc[i]->co_help, cp_program); @@ -71,10 +71,10 @@ com_help(wordlist *wl) for (al = cp_aliases; al; al = al->al_next) if (eq(al->al_name, wl->wl_word)) break; - if (al == NULL) - fprintf(cp_out, "Sorry, no help for %s.\n", - wl->wl_word); - else { + + if (al == NULL) { + fprintf(cp_out, "Sorry, no help for %s.\n", wl->wl_word); + } else { out_printf("%s is aliased to ", wl->wl_word); /* Minor badness here... */ wl_print(al->al_text, cp_out); @@ -84,6 +84,7 @@ com_help(wordlist *wl) wl = wl->wl_next; } } + out_send("\n"); return; } diff --git a/src/frontend/com_history.c b/src/frontend/com_history.c index 0d7c3ac8e..c3d244989 100644 --- a/src/frontend/com_history.c +++ b/src/frontend/com_history.c @@ -14,27 +14,28 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group /* Added GNU Readline Support -- Andrew Veliath */ #include #include -#endif /* HAVE_GNUREADLINE */ +#endif #ifdef HAVE_BSDEDITLINE /* SJB added edit line support 2005-05-05 */ #include -#endif /* HAVE_BSDEDITLINE */ +#endif -/* static declarations */ -static wordlist * dohsubst(char *string); -static wordlist * dohmod(char **string, wordlist *wl); -static wordlist * hpattern(char *buf); -static wordlist * hprefix(char *buf); -static wordlist * getevent(int num); + +static wordlist *dohsubst(char *string); +static wordlist *dohmod(char **string, wordlist *wl); +static wordlist *hpattern(char *buf); +static wordlist *hprefix(char *buf); +static wordlist *getevent(int num); #if !defined(HAVE_GNUREADLINE) && !defined(HAVE_BSDEDITLINE) static void freehist(int num); #endif -static char * dohs(char *pat, char *str); +static char *dohs(char *pat, char *str); struct histent *cp_lastone = NULL; -int cp_maxhistlength = 10000; /* Chris Inbody */ + +int cp_maxhistlength = 10000; /* Chris Inbody */ char cp_hat = '^'; char cp_bang = '!'; bool cp_didhsubst; @@ -42,6 +43,7 @@ bool cp_didhsubst; static struct histent *histlist = NULL; static int histlength = 0; + /* First check for a ^ at the beginning of the line, and then search * each word for !. Following this can be any of string, number, * ?string, -number ; then there may be a word specifier, the same as @@ -60,11 +62,12 @@ cp_histsubst(wordlist *wlist) cp_didhsubst = FALSE; if (*wlist->wl_word == cp_hat) { - (void) sprintf(buf, "%c%c:s%s", cp_bang, cp_bang, - wlist->wl_word); + (void) sprintf(buf, "%c%c:s%s", cp_bang, cp_bang, + wlist->wl_word); tfree(wlist->wl_word); wlist->wl_word = copy(buf); } + for (w = wlist; w; w = w->wl_next) { b = w->wl_word; for (s = b; *s; s++) @@ -76,8 +79,7 @@ cp_histsubst(wordlist *wlist) return (wlist); } if (b < s) { - (void) sprintf(buf, "%.*s%s", (int)(s-b), b, - n->wl_word); + (void) sprintf(buf, "%.*s%s", (int)(s-b), b, n->wl_word); tfree(n->wl_word); n->wl_word = copy(buf); } @@ -88,9 +90,11 @@ cp_histsubst(wordlist *wlist) break; } } + return (wlist); } + /* Do a history substitution on one word. Figure out which event is * being referenced, then do word selections and modifications, and * then stick anything left over on the end of the last word. @@ -111,9 +115,9 @@ dohsubst(char *string) return (NULL); } } else { - switch(*string) { + switch (*string) { - case '-': + case '-': wl = getevent(cp_event - scannum(++string)); if (!wl) return (NULL); @@ -121,7 +125,7 @@ dohsubst(char *string) string++; break; - case '?': + case '?': (void) strcpy(buf, string + 1); if ((s = strchr(buf, '?')) != NULL) *s = '\0'; @@ -132,12 +136,12 @@ dohsubst(char *string) return (wl_copy(wl)); break; - case '\0': /* Maybe this should be cp_event. */ + case '\0': /* Maybe this should be cp_event. */ wl = wl_cons(copy("!"), NULL); cp_didhsubst = FALSE; return (wl); - default: + default: if (isdigit(*string)) { wl = getevent(scannum(string)); if (!wl) @@ -147,7 +151,7 @@ dohsubst(char *string) } else { (void) strcpy(buf, string); for (s = ":^$*-%"; *s; s++) { - t =strchr(buf, *s); + t = strchr(buf, *s); if (t && ((t < r) || !r)) { r = t; string += r - buf; @@ -155,7 +159,7 @@ dohsubst(char *string) } if (r) *r = '\0'; - else + else while (*string) string++; if ((buf[0] == '\0') && cp_lastone) @@ -167,13 +171,16 @@ dohsubst(char *string) } } } + if (wl == NULL) { /* Shouldn't happen. */ fprintf(cp_err, "Event not found.\n"); return (NULL); } + nwl = dohmod(&string, wl_copy(wl)); if (!nwl) return (NULL); + if (*string) { for (wl = nwl; wl->wl_next; wl = wl->wl_next) ; @@ -181,9 +188,11 @@ dohsubst(char *string) tfree(wl->wl_word); wl->wl_word = copy(buf); } + return (nwl); } + static wordlist * dohmod(char **string, wordlist *wl) { @@ -202,10 +211,11 @@ anothermod: /* Now we know what wordlist we want. Take care of modifiers now. */ r = NULL; for (s = ":^$*-%"; *s; s++) { - t =strchr(*string, *s); + t = strchr(*string, *s); if (t && ((t < r) || (r == NULL))) r = t; } + if (!r) /* No more modifiers. */ return (wl); @@ -213,86 +223,89 @@ anothermod: if (**string == ':') (*string)++; - switch(**string) { - case '$': /* Last word. */ - eventhi = eventlo = numwords - 1; - break; - case '*': /* Words 1 through $ */ - if (numwords == 1) - return (NULL); - eventlo = 1; + switch (**string) { + case '$': /* Last word. */ + eventhi = eventlo = numwords - 1; + break; + case '*': /* Words 1 through $ */ + if (numwords == 1) + return (NULL); + eventlo = 1; + eventhi = numwords - 1; + break; + case '-': /* Words 0 through ... */ + eventlo = 0; + if (*(*string + 1)) + eventhi = scannum(*string + 1); + else eventhi = numwords - 1; - break; - case '-': /* Words 0 through ... */ - eventlo = 0; - if (*(*string + 1)) - eventhi = scannum(*string + 1); - else - eventhi = numwords - 1; - if (eventhi > numwords - 1) - eventhi = numwords - 1; - break; - case 'p': /* Print the command and don't execute it. + if (eventhi > numwords - 1) + eventhi = numwords - 1; + break; + case 'p': /* Print the command and don't execute it. * This doesn't work quite like csh. */ - wl_print(wl, cp_out); - (void) putc('\n', cp_out); - return (NULL); - case 's': /* Do a substitution. */ - for (w = wl; w; w = w->wl_next) { - s = dohs(*string + 1, w->wl_word); - if (s) { - tfree(w->wl_word); - w->wl_word = s; - if (globalsubst == FALSE) { - while (**string) - (*string)++; - break; - } - } - } - /* In case globalsubst is TRUE... */ - while (**string) - (*string)++; - break; - default: - if (!isdigit(**string)) { - fprintf(cp_err, "Error: %s: bad modifier.\n", - *string); - return (NULL); - } - i = scannum(*string); - if (i > eventhi) { - fprintf(cp_err, "Error: bad event number %d\n", - i); - return (NULL); - } - eventhi = eventlo = i; - while (isdigit(**string)) - (*string)++; - if (**string == '*') - eventhi = numwords - 1; - if (**string == '-') { - if (!isdigit(*(*string + 1))) - eventhi = numwords - 1; - else { - eventhi = scannum(++*string); - while (isdigit(**string)) + wl_print(wl, cp_out); + (void) putc('\n', cp_out); + return (NULL); + case 's': /* Do a substitution. */ + for (w = wl; w; w = w->wl_next) { + s = dohs(*string + 1, w->wl_word); + if (s) { + tfree(w->wl_word); + w->wl_word = s; + if (globalsubst == FALSE) { + while (**string) (*string)++; + break; } - } + } + } + /* In case globalsubst is TRUE... */ + while (**string) + (*string)++; + break; + default: + if (!isdigit(**string)) { + fprintf(cp_err, "Error: %s: bad modifier.\n", + *string); + return (NULL); + } + i = scannum(*string); + if (i > eventhi) { + fprintf(cp_err, "Error: bad event number %d\n", + i); + return (NULL); + } + eventhi = eventlo = i; + while (isdigit(**string)) + (*string)++; + if (**string == '*') + eventhi = numwords - 1; + if (**string == '-') { + if (!isdigit(*(*string + 1))) { + eventhi = numwords - 1; + } else { + eventhi = scannum(++*string); + while (isdigit(**string)) + (*string)++; + } + } } + /* Now change the word list accordingly and make another pass * if there is more of the substitute left. */ - + wl = wl_range(wl, eventlo, eventhi); numwords = wl_length(wl); if (**string && *++*string) goto anothermod; + return (wl); } + /* Look for an event with a pattern in it... */ static wordlist * @@ -305,14 +318,17 @@ hpattern(char *buf) fprintf(cp_err, "Bad pattern specification.\n"); return (NULL); } + for (hi = cp_lastone; hi; hi = hi->hi_prev) for (wl = hi->hi_wlist; wl; wl = wl->wl_next) if (substring(buf, wl->wl_word)) return (hi->hi_wlist); + fprintf(cp_err, "%s: event not found.\n", buf); return (NULL); } + static wordlist * hprefix(char *buf) { @@ -322,13 +338,16 @@ hprefix(char *buf) fprintf(cp_err, "Bad pattern specification.\n"); return (NULL); } + for (hi = cp_lastone; hi; hi = hi->hi_prev) if (hi->hi_wlist && prefix(buf, hi->hi_wlist->wl_word)) return (hi->hi_wlist); + fprintf(cp_err, "%s: event not found.\n", buf); return (NULL); } + /* Add a wordlist to the history list. (Done after the first parse.) Note * that if event numbers are given in a random order that's how they'll * show up in the history list. @@ -337,14 +356,14 @@ hprefix(char *buf) void cp_addhistent(int event, wordlist *wlist) { - /* MW. This test is not needed if everything works right - if (cp_lastone && !cp_lastone->hi_wlist) - fprintf(cp_err, "Internal error: bad history list\n"); */ - + /* MW. This test is not needed if everything works right + if (cp_lastone && !cp_lastone->hi_wlist) + fprintf(cp_err, "Internal error: bad history list\n"); */ + if (cp_lastone == NULL) { -/* MW. the begging - initialize histlength*/ - histlength = 1; - + /* MW. the begging - initialize histlength */ + histlength = 1; + cp_lastone = histlist = alloc(struct histent); cp_lastone->hi_prev = NULL; } else { @@ -352,6 +371,7 @@ cp_addhistent(int event, wordlist *wlist) cp_lastone->hi_next->hi_prev = cp_lastone; cp_lastone = cp_lastone->hi_next; } + cp_lastone->hi_next = NULL; cp_lastone->hi_event = event; cp_lastone->hi_wlist = wl_copy(wlist); @@ -362,8 +382,9 @@ cp_addhistent(int event, wordlist *wlist) return; } -/* Get a copy of the wordlist associated with an event. Error if out - * of range. + +/* Get a copy of the wordlist associated with an event. Error if out + * of range. */ static wordlist * @@ -374,14 +395,17 @@ getevent(int num) for (hi = histlist; hi; hi = hi->hi_next) if (hi->hi_event == num) break; + if (hi == NULL) { fprintf(cp_err, "%d: event not found.\n", num); return (NULL); } + return (wl_copy(hi->hi_wlist)); } -/* Print out history between eventhi and eventlo. + +/* Print out history between eventhi and eventlo. * This doesn't remember quoting, so 'hodedo' prints as hodedo. */ @@ -394,18 +418,20 @@ cp_hprint(int eventhi, int eventlo, bool rev) for (hi = histlist; hi->hi_next; hi = hi->hi_next) ; for (; hi; hi = hi->hi_prev) - if ((hi->hi_event <= eventhi) && - (hi->hi_event >= eventlo) && - hi->hi_wlist) { + if ((hi->hi_event <= eventhi) && + (hi->hi_event >= eventlo) && + hi->hi_wlist) + { fprintf(cp_out, "%d\t", hi->hi_event); wl_print(hi->hi_wlist, cp_out); (void) putc('\n', cp_out); } } else { for (hi = histlist; hi; hi = hi->hi_next) - if ((hi->hi_event <= eventhi) && - (hi->hi_event >= eventlo) && - hi->hi_wlist) { + if ((hi->hi_event <= eventhi) && + (hi->hi_event >= eventlo) && + hi->hi_wlist) + { fprintf(cp_out, "%d\t", hi->hi_event); wl_print(hi->hi_wlist, cp_out); (void) putc('\n', cp_out); @@ -414,6 +440,7 @@ cp_hprint(int eventhi, int eventlo, bool rev) return; } + #if !defined(HAVE_GNUREADLINE) && !defined(HAVE_BSDEDITLINE) /* This just gets rid of the first num entries on the history list, and @@ -427,29 +454,35 @@ freehist(int num) if (num < 1) return; + histlength -= num; hi = histlist; + while (num-- && histlist->hi_next) histlist = histlist->hi_next; + if (histlist->hi_prev) { histlist->hi_prev->hi_next = NULL; histlist->hi_prev = NULL; - } else - { + } else { fprintf(cp_err, "Internal error: history list mangled\n"); exit(0); /* Chris Inbody */ - } + } + while (hi->hi_next) { wl_free(hi->hi_wlist); hi = hi->hi_next; tfree(hi->hi_prev); } + wl_free(hi->hi_wlist); tfree(hi); return; } + #endif /* !defined(HAVE_GNUREADLINE) && !defined(HAVE_BSDEDITLINE) */ + /* Do a :s substitution. */ static char * @@ -461,15 +494,17 @@ dohs(char *pat, char *str) pat = copy(pat); /* Don't want to mangle anything. */ schar = *pat++; - s =strchr(pat, schar); + s = strchr(pat, schar); if (s == NULL) { fprintf(cp_err, "Bad substitute.\n"); return (NULL); } *s++ = '\0'; - p =strchr(s, schar); + + p = strchr(s, schar); if (p) *p = '\0'; + plen = (int) strlen(pat) - 1; for (i = 0; *str; str++) { if ((*str == *pat) && prefix(pat, str) && (ok == FALSE)) { @@ -477,16 +512,19 @@ dohs(char *pat, char *str) buf[i++] = *p; str += plen; ok = TRUE; - } else + } else { buf[i++] = *str; + } } buf[i] = '\0'; + if (ok) return (copy(buf)); else return (NULL); } + /* The "history" command. history [-r] [number] */ void @@ -502,26 +540,30 @@ com_history(wordlist *wl) #if defined(HAVE_GNUREADLINE) || defined(HAVE_BSDEDITLINE) /* Added GNU Readline Support -- Andrew Veliath */ { - HIST_ENTRY *he; - int i, N; + HIST_ENTRY *he; + int i, N; - N = (wl == NULL) ? history_length : atoi(wl->wl_word); + N = (wl == NULL) ? history_length : atoi(wl->wl_word); - if (N < 0) N = 0; - if (N > history_length) N = history_length; + if (N < 0) + N = 0; + if (N > history_length) + N = history_length; - if (rev) - for (i = history_length; i > 0 && N; --i, --N) { - he = history_get(i); - if (!he) return; - fprintf(cp_out, "%d\t%s\n", i, he->line); - } - else - for (i = history_length - N + 1; i <= history_length; ++i) { - he = history_get(i); - if (!he) return; - fprintf(cp_out, "%d\t%s\n", i, he->line); - } + if (rev) + for (i = history_length; i > 0 && N; --i, --N) { + he = history_get(i); + if (!he) + return; + fprintf(cp_out, "%d\t%s\n", i, he->line); + } + else + for (i = history_length - N + 1; i <= history_length; ++i) { + he = history_get(i); + if (!he) + return; + fprintf(cp_out, "%d\t%s\n", i, he->line); + } } #else if (wl == NULL) diff --git a/src/frontend/com_let.c b/src/frontend/com_let.c index 01289d6f3..42645c566 100644 --- a/src/frontend/com_let.c +++ b/src/frontend/com_let.c @@ -14,8 +14,8 @@ void com_let(wordlist *wl) { char *p, *q, *s; - int indices[MAXDIMS]; - int numdims; + int indices[MAXDIMS]; + int numdims; wordlist fake_wl; int need_open; int offset, length; @@ -38,85 +38,87 @@ com_let(wordlist *wl) /* extract indices */ numdims = 0; if ((rhs = strchr(p, '=')) != NULL) { - *rhs++ = 0; + *rhs++ = 0; } else { - fprintf(cp_err, "Error: bad let syntax\n"); - tfree(p); - return; + fprintf(cp_err, "Error: bad let syntax\n"); + tfree(p); + return; } + if ((s = strchr(p, '[')) != NULL) { - need_open = 0; - *s++ = 0; - while (!need_open || *s == '[') { - depth = 0; - if (need_open) - s++; - for (q = s; *q && (*q != ']' && (*q != ',' || depth > 0)); q++) { - switch (*q) { - case '[': - depth += 1; - break; - case ']': - depth -= 1; - break; - } - } + need_open = 0; + *s++ = 0; + while (!need_open || *s == '[') { + depth = 0; + if (need_open) + s++; + for (q = s; *q && (*q != ']' && (*q != ',' || depth > 0)); q++) { + switch (*q) { + case '[': + depth += 1; + break; + case ']': + depth -= 1; + break; + } + } - if (depth != 0 || !*q) { - printf("syntax error specifying index\n"); - tfree(p); - return; - } + if (depth != 0 || !*q) { + printf("syntax error specifying index\n"); + tfree(p); + return; + } - if (*q == ']') - need_open = 1; - else - need_open = 0; - if (*q) - *q++ = 0; + if (*q == ']') + need_open = 1; + else + need_open = 0; - /* evaluate expression between s and q */ - /* va, indexing */ - fake_wl.wl_word = s; - nn = ft_getpnames(&fake_wl, TRUE); - if (!nn) { - /* XXX error message */ - tfree(p); - return; - } - t = ft_evaluate(nn); - if (!t) { - fprintf(cp_err, "Error: Can't evaluate %s\n", s); - free_pnode(nn); - tfree(p); - return; - } - if (!isreal(t) || t->v_link2 || t->v_length != 1 || !t->v_realdata) - { - fprintf(cp_err, "Error: index is not a scalar.\n"); - goto quit; - } - j = (int)floor(t->v_realdata[0]+0.5); /* ignore sanity checks for now, va, which checks? */ + if (*q) + *q++ = 0; - if (j < 0) { - printf("negative index (%d) is not allowed\n", j); - goto quit; - } + /* evaluate expression between s and q */ + /* va, indexing */ + fake_wl.wl_word = s; + nn = ft_getpnames(&fake_wl, TRUE); + if (!nn) { + /* XXX error message */ + tfree(p); + return; + } + t = ft_evaluate(nn); + if (!t) { + fprintf(cp_err, "Error: Can't evaluate %s\n", s); + free_pnode(nn); + tfree(p); + return; + } + if (!isreal(t) || t->v_link2 || t->v_length != 1 || !t->v_realdata) { + fprintf(cp_err, "Error: index is not a scalar.\n"); + goto quit; + } + j = (int)floor(t->v_realdata[0]+0.5); /* ignore sanity checks for now, va, which checks? */ - indices[numdims++] = j; + if (j < 0) { + printf("negative index (%d) is not allowed\n", j); + goto quit; + } - /* va: garbage collection for t, if pnode nn is no simple value */ - if (nn!=NULL && nn->pn_value==NULL && t!=NULL) vec_free(t); - free_pnode(nn); /* frees also t, if pnode nn is simple value */ + indices[numdims++] = j; - for (s = q; *s && isspace(*s); s++) - ; - } + /* va: garbage collection for t, if pnode nn is no simple value */ + if (nn != NULL && nn->pn_value == NULL && t != NULL) + vec_free(t); + free_pnode(nn); /* frees also t, if pnode nn is simple value */ + + for (s = q; *s && isspace(*s); s++) + ; + } } /* vector name at p */ for (q = p + strlen(p) - 1; *q <= ' ' && p <= q; q--) - ; + ; *++q = 0; @@ -131,13 +133,13 @@ com_let(wordlist *wl) fake_wl.wl_word = rhs; nn = ft_getpnames(&fake_wl, TRUE); if (nn == NULL) { - /* XXX error message */ + /* XXX error message */ tfree(p); return; } t = ft_evaluate(nn); if (!t) { - fprintf(cp_err, "Error: Can't evaluate %s\n", rhs); + fprintf(cp_err, "Error: Can't evaluate %s\n", rhs); free_pnode(nn); tfree(p); return; @@ -149,44 +151,44 @@ com_let(wordlist *wl) n = vec_get(p); if (n) { - /* re-allocate? */ - /* vec_free(n); */ - newvec = 0; + /* re-allocate? */ + /* vec_free(n); */ + newvec = 0; } else { - if (numdims) { - fprintf(cp_err, "Can't assign into a subindex of a new vector\n"); - goto quit; - } + if (numdims) { + fprintf(cp_err, "Can't assign into a subindex of a new vector\n"); + goto quit; + } - /* create and assign a new vector */ - n = alloc(struct dvec); - ZERO(n, struct dvec); - n->v_name = copy(p); - n->v_type = t->v_type; - n->v_flags = (t->v_flags | VF_PERMANENT); - n->v_length = t->v_length; + /* create and assign a new vector */ + n = alloc(struct dvec); + ZERO(n, struct dvec); + n->v_name = copy(p); + n->v_type = t->v_type; + n->v_flags = (t->v_flags | VF_PERMANENT); + n->v_length = t->v_length; - if ((t->v_numdims)<=1) { // changed from "!t->v_numdims" by Friedrich Schmidt - n->v_numdims = 1; - n->v_dims[0] = n->v_length; - } else { - n->v_numdims = t->v_numdims; - for (i = 0; i < t->v_numdims; i++) - n->v_dims[i] = t->v_dims[i]; - } + if ((t->v_numdims) <= 1) { // changed from "!t->v_numdims" by Friedrich Schmidt + n->v_numdims = 1; + n->v_dims[0] = n->v_length; + } else { + n->v_numdims = t->v_numdims; + for (i = 0; i < t->v_numdims; i++) + n->v_dims[i] = t->v_dims[i]; + } - if (isreal(t)) - n->v_realdata = TMALLOC(double, n->v_length); - else - n->v_compdata = TMALLOC(ngcomplex_t, n->v_length); - newvec = 1; - vec_new(n); + if (isreal(t)) + n->v_realdata = TMALLOC(double, n->v_length); + else + n->v_compdata = TMALLOC(ngcomplex_t, n->v_length); + newvec = 1; + vec_new(n); } /* fix-up dimensions; va, also for v_dims */ - if (n->v_numdims < 1 || n->v_dims[0]==0 ) { - n->v_numdims = 1; - n->v_dims[0] = n->v_length; + if (n->v_numdims < 1 || n->v_dims[0] == 0 ) { + n->v_numdims = 1; + n->v_dims[0] = n->v_length; } /* Compare dimensions */ @@ -195,38 +197,38 @@ com_let(wordlist *wl) cube = 1; for (i = n->v_numdims - 1; i >= numdims; i--) - cube *= n->v_dims[i]; + cube *= n->v_dims[i]; for (i = numdims - 1; i >= 0; i--) { - offset += cube * indices[i]; - if (i < n->v_numdims) { - cube *= n->v_dims[i]; - length /= n->v_dims[i]; - } + offset += cube * indices[i]; + if (i < n->v_numdims) { + cube *= n->v_dims[i]; + length /= n->v_dims[i]; + } } /* length is the size of the unit refered to */ /* cube ends up being the length */ if (length > t->v_length) { - fprintf(cp_err, "left-hand expression is too small (need %d)\n", - length * cube); - if (newvec) - n->v_flags &= ~VF_PERMANENT; - goto quit; + fprintf(cp_err, "left-hand expression is too small (need %d)\n", + length * cube); + if (newvec) + n->v_flags &= ~VF_PERMANENT; + goto quit; } if (isreal(t) != isreal(n)) { - fprintf(cp_err, - "Types of vectors are not the same (real vs. complex)\n"); - if (newvec) - n->v_flags &= ~VF_PERMANENT; - goto quit; + fprintf(cp_err, + "Types of vectors are not the same (real vs. complex)\n"); + if (newvec) + n->v_flags &= ~VF_PERMANENT; + goto quit; } else if (isreal(t)) { - bcopy(t->v_realdata, n->v_realdata + offset, - (size_t) length * sizeof (double)); + bcopy(t->v_realdata, n->v_realdata + offset, + (size_t) length * sizeof(double)); } else { - bcopy(t->v_compdata, n->v_compdata + offset, - (size_t) length * sizeof(ngcomplex_t)); + bcopy(t->v_compdata, n->v_compdata + offset, + (size_t) length * sizeof(ngcomplex_t)); } n->v_minsignal = 0.0; /* How do these get reset ??? */ @@ -235,11 +237,12 @@ com_let(wordlist *wl) n->v_scale = t->v_scale; if (newvec) - cp_addkword(CT_VECTOR, n->v_name); + cp_addkword(CT_VECTOR, n->v_name); quit: /* va: garbage collection for t, if pnode nn is no simple value */ - if (nn!=NULL && nn->pn_value==NULL && t!=NULL) vec_free(t); + if (nn != NULL && nn->pn_value == NULL && t != NULL) + vec_free(t); free_pnode(nn); /* frees also t, if pnode nn is simple value */ tfree(p); return; diff --git a/src/frontend/com_measure2.c b/src/frontend/com_measure2.c index 67ad7af8a..71e5a579f 100644 --- a/src/frontend/com_measure2.c +++ b/src/frontend/com_measure2.c @@ -18,685 +18,682 @@ #include "breakp2.h" typedef enum { - MEASUREMENT_OK = 0, - MEASUREMENT_FAILURE = 1 - } MEASURE_VAL_T ; + MEASUREMENT_OK = 0, + MEASUREMENT_FAILURE = 1 +} MEASURE_VAL_T; #define MEASURE_DEFAULT -1 #define MEASURE_LAST_TRANSITION -2 typedef struct measure { - char *result; + char *result; - char *m_vec; // name of the output variable which determines the beginning of the measurement - char *m_vec2; // second output variable to measure if applicable - char *m_analysis; // analysis type (tran, dc or ac) - char m_vectype; // type of vector m_vec (vm, vi, vr, vp, vdb) - char m_vectype2; // type of vector m_vec2 (vm, vi, vr, vp, vdb) - int m_rise; // count number of rise events - int m_fall; // count number of fall events - int m_cross; // count number of rise/fall aka cross events - double m_val; // value of the m_ver at which the counter for crossing, rises or falls is incremented by one - double m_td; // amount of delay before the measurement should start - double m_from; // measure only in a time window - starting time of window - double m_to; // measurement window - ending time - double m_at; // measure at the specified time - double m_measured; // what we measured - double m_measured_at; // what we measured at the given time + char *m_vec; // name of the output variable which determines the beginning of the measurement + char *m_vec2; // second output variable to measure if applicable + char *m_analysis; // analysis type (tran, dc or ac) + char m_vectype; // type of vector m_vec (vm, vi, vr, vp, vdb) + char m_vectype2; // type of vector m_vec2 (vm, vi, vr, vp, vdb) + int m_rise; // count number of rise events + int m_fall; // count number of fall events + int m_cross; // count number of rise/fall aka cross events + double m_val; // value of the m_ver at which the counter for crossing, rises or falls is incremented by one + double m_td; // amount of delay before the measurement should start + double m_from; // measure only in a time window - starting time of window + double m_to; // measurement window - ending time + double m_at; // measure at the specified time + double m_measured; // what we measured + double m_measured_at; // what we measured at the given time -} MEASURE, *MEASUREPTR ; +} MEASURE, *MEASUREPTR; typedef enum AnalysisType { - AT_UNKNOWN, AT_DELAY, AT_TRIG, - AT_FIND, AT_WHEN, - AT_AVG, AT_MIN, AT_MAX, AT_RMS, AT_PP, - AT_INTEG, AT_DERIV, - AT_ERR, AT_ERR1, AT_ERR2, AT_ERR3, AT_MIN_AT, AT_MAX_AT -} ANALYSIS_TYPE_T ; + AT_UNKNOWN, AT_DELAY, AT_TRIG, + AT_FIND, AT_WHEN, + AT_AVG, AT_MIN, AT_MAX, AT_RMS, AT_PP, + AT_INTEG, AT_DERIV, + AT_ERR, AT_ERR1, AT_ERR2, AT_ERR3, AT_MIN_AT, AT_MAX_AT +} ANALYSIS_TYPE_T; + /** return precision (either 5 or value of environment variable NGSPICE_MEAS_PRECISION) */ int measure_get_precision(void) { - char *env_ptr; - int precision = 5; + char *env_ptr; + int precision = 5; - if (( env_ptr = getenv("NGSPICE_MEAS_PRECISION")) != NULL) { - precision = atoi(env_ptr); - } + if ((env_ptr = getenv("NGSPICE_MEAS_PRECISION")) != NULL) + precision = atoi(env_ptr); - return precision; -} /* end measure_get_precision() */ + return precision; +} -static void measure_errMessage(char *mName, char *mFunction, char *trigTarg, char *errMsg, int chk_only) + +static void +measure_errMessage(char *mName, char *mFunction, char *trigTarg, char *errMsg, int chk_only) { - - if(!(chk_only)){ - printf("\nError: measure %s %s(%s) : ", mName, mFunction, trigTarg); - printf("%s",errMsg); -// printf("\tmeasure '%s' failed\n", mName); - } - return; -} /* end measure_errMessage() */ + if (!chk_only) { + printf("\nError: measure %s %s(%s) : ", mName, mFunction, trigTarg); + printf("%s", errMsg); + // printf("\tmeasure '%s' failed\n", mName); + } + return; +} /* If you have a vector vm(out), extract 'm' to meas->m_vectype and v(out) to meas->m_vec (without 'm') */ -static -void correct_vec(MEASUREPTR meas) +static void +correct_vec(MEASUREPTR meas) { - char *vec, *vecfirst, newvec[BSIZE_SP]; - char *vec2, newvec2[BSIZE_SP]; + char *vec, *vecfirst, newvec[BSIZE_SP]; + char *vec2, newvec2[BSIZE_SP]; - vec = meas->m_vec; - /* return if not of type VM() etc */ - if ((*vec != 'v') || (!strstr(vec, "("))) return; - - if (*(++vec) != '(') { - vecfirst = copy(meas->m_vec); - vecfirst[1] = '\0'; - meas->m_vectype = *vec; - sprintf(newvec, "%s%s", vecfirst, strstr(meas->m_vec, "(")); - tfree(meas->m_vec); - tfree(vecfirst); - meas->m_vec = copy(newvec); - } + vec = meas->m_vec; + /* return if not of type VM() etc */ + if ((*vec != 'v') || (!strstr(vec, "("))) return; - vec2 = meas->m_vec2; - if (vec2 && (*(++vec2) != '(')) { - vecfirst = copy(meas->m_vec); - vecfirst[1] = '\0'; - meas->m_vectype2 = *vec2; - sprintf(newvec, "%s%s", vecfirst, strstr(meas->m_vec2, "(")); - tfree(meas->m_vec2); - tfree(vecfirst); - meas->m_vec2 = copy(newvec2); - } - return; + if (*(++vec) != '(') { + vecfirst = copy(meas->m_vec); + vecfirst[1] = '\0'; + meas->m_vectype = *vec; + sprintf(newvec, "%s%s", vecfirst, strstr(meas->m_vec, "(")); + tfree(meas->m_vec); + tfree(vecfirst); + meas->m_vec = copy(newvec); + } + + vec2 = meas->m_vec2; + if (vec2 && (*(++vec2) != '(')) { + vecfirst = copy(meas->m_vec); + vecfirst[1] = '\0'; + meas->m_vectype2 = *vec2; + sprintf(newvec, "%s%s", vecfirst, strstr(meas->m_vec2, "(")); + tfree(meas->m_vec2); + tfree(vecfirst); + meas->m_vec2 = copy(newvec2); + } + return; } + /* Returns a value from a complex vector *values, depending on meas->m_vectype */ -static double get_value( - MEASUREPTR meas, /*in: pointer to mesurement structure */ - struct dvec *values, /*in: vector of complex values */ - int idx /*in: index of vector value to be read out */ -) { - double ar, bi, tt; +static double +get_value( + MEASUREPTR meas, /*in: pointer to mesurement structure */ + struct dvec *values, /*in: vector of complex values */ + int idx /*in: index of vector value to be read out */ + ) +{ + double ar, bi, tt; - ar = values->v_compdata[idx].cx_real; - bi = values->v_compdata[idx].cx_imag; + ar = values->v_compdata[idx].cx_real; + bi = values->v_compdata[idx].cx_imag; - if ((meas->m_vectype == 'm') || (meas->m_vectype == 'M')) - { - return sqrt(ar*ar + bi*bi); /* magnitude */ - } - else if ((meas->m_vectype == 'r') || (meas->m_vectype == 'R')) - { - return ar; /* real value */ - } - else if ((meas->m_vectype == 'i') || (meas->m_vectype == 'I')) - { - return bi; /* imaginary value */ - } - else if ((meas->m_vectype == 'p') || (meas->m_vectype == 'P')) - { - return radtodeg(atan2(bi, ar)); /* phase (in degrees) */ - } - else if ((meas->m_vectype == 'd') || (meas->m_vectype == 'D')) - { - tt = sqrt(ar*ar + bi*bi); /* dB of magnitude */ - return 20.0 * log10(tt); - } - else - return ar; /* default: real value */ + if ((meas->m_vectype == 'm') || (meas->m_vectype == 'M')) { + return sqrt(ar*ar + bi*bi); /* magnitude */ + } else if ((meas->m_vectype == 'r') || (meas->m_vectype == 'R')) { + return ar; /* real value */ + } else if ((meas->m_vectype == 'i') || (meas->m_vectype == 'I')) { + return bi; /* imaginary value */ + } else if ((meas->m_vectype == 'p') || (meas->m_vectype == 'P')) { + return radtodeg(atan2(bi, ar)); /* phase (in degrees) */ + } else if ((meas->m_vectype == 'd') || (meas->m_vectype == 'D')) { + tt = sqrt(ar*ar + bi*bi); /* dB of magnitude */ + return 20.0 * log10(tt); + } else { + return ar; /* default: real value */ + } } + /* Returns interpolated value. If ac simulation, exploit vector type with complex data for y */ static double measure_interpolate( - struct dvec *xScale, /* in: vector of independent variables, if ac: complex vector, - but only real part used */ - struct dvec *values, /* in: vector of dependent variables, if ac: complex vector */ - int i, /* in: index of first interpolation value */ - int j, /* in: index of second interpolation value */ - double var_value, /* in: variable, whose counterpart is sought by interpolation */ - char x_or_y , /* in: if 'x', then look for y, if 'y' then look for x */ - MEASUREPTR meas /* pointer to measurement structure */ -) { - double slope; - double yint; - double result; + struct dvec *xScale, /* in: vector of independent variables, if ac: complex vector, + but only real part used */ + struct dvec *values, /* in: vector of dependent variables, if ac: complex vector */ + int i, /* in: index of first interpolation value */ + int j, /* in: index of second interpolation value */ + double var_value, /* in: variable, whose counterpart is sought by interpolation */ + char x_or_y , /* in: if 'x', then look for y, if 'y' then look for x */ + MEASUREPTR meas /* pointer to measurement structure */ + ) +{ + double slope; + double yint; + double result; - if (cieq (meas->m_analysis,"ac")) { - /* get values from complex y vector according to meas->m_vectype, - x vector uses only real part of complex data (frequency).*/ - slope = (get_value(meas, values, j) - get_value(meas, values, i)) / - (xScale->v_compdata[j].cx_real - xScale->v_compdata[i].cx_real); - yint = get_value(meas, values, i) - slope*xScale->v_compdata[i].cx_real; - } - else { - slope = (values->v_realdata[j] - values->v_realdata[i]) / - (xScale->v_realdata[j] - xScale->v_realdata[i]); - yint = values->v_realdata[i] - slope*xScale->v_realdata[i]; - } + if (cieq (meas->m_analysis, "ac")) { + /* get values from complex y vector according to meas->m_vectype, + x vector uses only real part of complex data (frequency).*/ + slope = (get_value(meas, values, j) - get_value(meas, values, i)) / + (xScale->v_compdata[j].cx_real - xScale->v_compdata[i].cx_real); + yint = get_value(meas, values, i) - slope*xScale->v_compdata[i].cx_real; + } else { + slope = (values->v_realdata[j] - values->v_realdata[i]) / + (xScale->v_realdata[j] - xScale->v_realdata[i]); + yint = values->v_realdata[i] - slope*xScale->v_realdata[i]; + } - if ( x_or_y == 'x' ) result = (var_value - yint)/slope; - else result = slope*var_value + yint; + if (x_or_y == 'x') + result = (var_value - yint)/slope; + else + result = slope*var_value + yint; - return result; -} /* end measure_interpolate() */ + return result; +} /* ----------------------------------------------------------------- * Function: Given an operation string returns back the measure type - * one of the enumerated type ANALSYS_TYPE_T. * ----------------------------------------------------------------- */ -static ANALYSIS_TYPE_T measure_function_type( char *operation ) +static ANALYSIS_TYPE_T +measure_function_type(char *operation) { - char *mFunction ; /* operation */ - ANALYSIS_TYPE_T mFunctionType ; /* type of requested function */ + char *mFunction; /* operation */ + ANALYSIS_TYPE_T mFunctionType; /* type of requested function */ mFunction = cp_unquote(operation); // Functions - if (strcasecmp(mFunction,"DELAY")==0) + if (strcasecmp(mFunction, "DELAY") == 0) mFunctionType = AT_DELAY; - else if (strcasecmp(mFunction,"TRIG")==0) + else if (strcasecmp(mFunction, "TRIG") == 0) mFunctionType = AT_DELAY; - else if (strcasecmp(mFunction,"TARG")==0) + else if (strcasecmp(mFunction, "TARG") == 0) mFunctionType = AT_DELAY; - else if (strcasecmp(mFunction,"FIND")==0) + else if (strcasecmp(mFunction, "FIND") == 0) mFunctionType = AT_FIND; - else if (strcasecmp(mFunction,"WHEN")==0) + else if (strcasecmp(mFunction, "WHEN") == 0) mFunctionType = AT_WHEN; - else if (strcasecmp(mFunction,"AVG")==0) + else if (strcasecmp(mFunction, "AVG") == 0) mFunctionType = AT_AVG; - else if (strcasecmp(mFunction,"MIN")==0) + else if (strcasecmp(mFunction, "MIN") == 0) mFunctionType = AT_MIN; - else if (strcasecmp(mFunction,"MAX")==0) + else if (strcasecmp(mFunction, "MAX") == 0) mFunctionType = AT_MAX; - else if (strcasecmp(mFunction,"MIN_AT")==0) + else if (strcasecmp(mFunction, "MIN_AT") == 0) mFunctionType = AT_MIN_AT; - else if (strcasecmp(mFunction,"MAX_AT")==0) + else if (strcasecmp(mFunction, "MAX_AT") == 0) mFunctionType = AT_MAX_AT; - else if (strcasecmp(mFunction,"RMS")==0) + else if (strcasecmp(mFunction, "RMS") == 0) mFunctionType = AT_RMS; - else if (strcasecmp(mFunction,"PP")==0) + else if (strcasecmp(mFunction, "PP") == 0) mFunctionType = AT_PP; - else if (strcasecmp(mFunction,"INTEG")==0) + else if (strcasecmp(mFunction, "INTEG") == 0) mFunctionType = AT_INTEG; - else if (strcasecmp(mFunction,"DERIV")==0) + else if (strcasecmp(mFunction, "DERIV") == 0) mFunctionType = AT_DERIV; - else if (strcasecmp(mFunction,"ERR")==0) + else if (strcasecmp(mFunction, "ERR") == 0) mFunctionType = AT_ERR; - else if (strcasecmp(mFunction,"ERR1")==0) + else if (strcasecmp(mFunction, "ERR1") == 0) mFunctionType = AT_ERR1; - else if (strcasecmp(mFunction,"ERR2") == 0) + else if (strcasecmp(mFunction, "ERR2") == 0) mFunctionType = AT_ERR2; - else if (strcasecmp(mFunction,"ERR3") == 0) + else if (strcasecmp(mFunction, "ERR3") == 0) mFunctionType = AT_ERR3; else mFunctionType = AT_UNKNOWN; - return( mFunctionType) ; + return (mFunctionType); +} -} /* end measure_function_type() */ /* ----------------------------------------------------------------- * Function: Parse the measurement line and extract any variables in * the statement and call com_save2 to instantiate the variable as a * measurement vector in the transient analysis. * ----------------------------------------------------------------- */ -int measure_extract_variables( char *line ) +int +measure_extract_variables(char *line) { - /* Various formats for measure statement: - * .MEASURE {DC|AC|TRAN} result TRIG trig_variable VAL=val - * + - * + - * + TARG targ_variable VAL=val - * + - * + - * - * .MEASURE {DC|AC|TRAN} result WHEN out_variable=val - * + - * + - * - * .MEASURE {DC|AC|TRAN} result WHEN out_variable=out_variable2 - * + - * + - * - * .MEASURE {DC|AC|TRAN} result FIND out_variable WHEN out_variable2=val - * + - * + - * - * .MEASURE {DC|AC|TRAN} result FIND out_variable WHEN out_variable2=out_variable3 - * + - * + - * - * .MEASURE {DC|AC|TRAN} result FIND out_variable AT=val - * + - * - * .MEASURE {DC|AC|TRAN} result {AVG|MIN|MAX|MIN_AT|MAX_AT|PP|RMS} out_variable - * + - * - * .MEASURE {DC|AC|TRAN} result INTEG out_variable - * + - * - * .MEASURE {DC|AC|TRAN} result DERIV out_variable AT=val - * - * .MEASURE {DC|AC|TRAN} result DERIV out_variable WHEN out_variable2=val - * + - * + - * - * .MEASURE {DC|AC|TRAN} result DERIV out_variable WHEN out_variable2=out_variable3 - * + - * + - * ----------------------------------------------------------------- */ + /* Various formats for measure statement: + * .MEASURE {DC|AC|TRAN} result TRIG trig_variable VAL=val + * + + * + + * + TARG targ_variable VAL=val + * + + * + + * + * .MEASURE {DC|AC|TRAN} result WHEN out_variable=val + * + + * + + * + * .MEASURE {DC|AC|TRAN} result WHEN out_variable=out_variable2 + * + + * + + * + * .MEASURE {DC|AC|TRAN} result FIND out_variable WHEN out_variable2=val + * + + * + + * + * .MEASURE {DC|AC|TRAN} result FIND out_variable WHEN out_variable2=out_variable3 + * + + * + + * + * .MEASURE {DC|AC|TRAN} result FIND out_variable AT=val + * + + * + * .MEASURE {DC|AC|TRAN} result {AVG|MIN|MAX|MIN_AT|MAX_AT|PP|RMS} out_variable + * + + * + * .MEASURE {DC|AC|TRAN} result INTEG out_variable + * + + * + * .MEASURE {DC|AC|TRAN} result DERIV out_variable AT=val + * + * .MEASURE {DC|AC|TRAN} result DERIV out_variable WHEN out_variable2=val + * + + * + + * + * .MEASURE {DC|AC|TRAN} result DERIV out_variable WHEN out_variable2=out_variable3 + * + + * + + * ----------------------------------------------------------------- */ - int status ; /* return status */ - char *item ; /* parsing item */ - char *measure ; /* measure keyword */ - char *analysis ; /* analysis option */ - char *variable, *variable2 ; /* variable to trace */ - wordlist *measure_var ; /* wordlist of measurable */ - ANALYSIS_TYPE_T op ; /* measure function type */ + int status; /* return status */ + char *item; /* parsing item */ + char *measure; /* measure keyword */ + char *analysis; /* analysis option */ + char *variable, *variable2; /* variable to trace */ + wordlist *measure_var; /* wordlist of measurable */ + ANALYSIS_TYPE_T op; /* measure function type */ - status = TRUE; - measure = gettok(&line); - if(!(measure)){ - return(status) ; - } - analysis = gettok(&line); - if(!(analysis)){ - return(status) ; - } - if( (strcasecmp(analysis,"DC")==0) || - (strcasecmp(analysis,"AC")==0) || - (strcasecmp(analysis,"TRAN")==0) ){ - analysis = copy(analysis) ; - } else { - /* sometimes operation is optional - for now just pick trans */ - analysis = copy("TRAN") ; - } - do { - item = gettok(&line) ; - if( item ){ - op = measure_function_type(item) ; - if( op != AT_UNKNOWN ){ - /* We have a variable/complex variable coming next */ - variable = gettok_iv(&line) ; - variable2 = NULL; - if (*line == '=') variable2 = gettok_iv(&line) ; - if( variable ){ - size_t len = strlen(item); - if( item[len-1] == '=' ){ - } else { - /* We may have something like V(n1)=1 - or v(n1)=2 , same with i() */ - measure_var = gettoks(variable) ; - com_save2(measure_var, analysis); - status = FALSE; - } + status = TRUE; + measure = gettok(&line); + if (!measure) + return (status); + + analysis = gettok(&line); + if (!analysis) + return (status); + + if ((strcasecmp(analysis, "DC") == 0) || + (strcasecmp(analysis, "AC") == 0) || + (strcasecmp(analysis, "TRAN") == 0)) { + analysis = copy(analysis); + } else { + /* sometimes operation is optional - for now just pick trans */ + analysis = copy("TRAN"); + } + + do { + item = gettok(&line); + if (item) { + op = measure_function_type(item); + if (op != AT_UNKNOWN) { + /* We have a variable/complex variable coming next */ + variable = gettok_iv(&line); + variable2 = NULL; + if (*line == '=') + variable2 = gettok_iv(&line); + if (variable) { + size_t len = strlen(item); + if (item[len-1] == '=') { + } else { + /* We may have something like V(n1)=1 + or v(n1)=2 , same with i() */ + measure_var = gettoks(variable); + com_save2(measure_var, analysis); + status = FALSE; + } + } + if (variable2) { + /* We may have something like v(n1)=v(n2) + v(n2) is handled here, same with i() */ + measure_var = gettoks(variable2); + com_save2(measure_var, analysis); + status = FALSE; + } } - if( variable2 ){ - /* We may have something like v(n1)=v(n2) - v(n2) is handled here, same with i() */ - measure_var = gettoks(variable2) ; - com_save2(measure_var, analysis); - status = FALSE; - } - } - } - } while(line && *line) ; + } + } while(line && *line); + + return (status); +} - return( status ) ; -} /* end measure_extract_variables() */ /* ----------------------------------------------------------------- * Function: process a WHEN measurement statement which has been * parsed into a measurement structure. * ----------------------------------------------------------------- */ -static void com_measure_when( +static void +com_measure_when( MEASUREPTR meas /* in : parsed measurement structure */ -) { + ) +{ + int i, first; + int riseCnt = 0; + int fallCnt = 0; + int crossCnt = 0; + int section = -1; + int measurement_pending; + int init_measured_value; + bool ac_check = FALSE, sp_check = FALSE, dc_check = FALSE, tran_check = FALSE; + bool has_d2 = FALSE; + double value, prevValue, value2, prevValue2; + double scaleValue, prevScaleValue; - int i, first; - int riseCnt = 0; - int fallCnt = 0; - int crossCnt = 0; - int section = -1; - int measurement_pending; - int init_measured_value; - bool ac_check = FALSE, sp_check = FALSE, dc_check = FALSE, tran_check = FALSE ; - bool has_d2 = FALSE; - double value, prevValue, value2, prevValue2; - double scaleValue, prevScaleValue; + enum ValSide { S_ABOVE_VAL, S_BELOW_VAL }; + enum ValEdge { E_RISING, E_FALLING }; - enum ValSide { S_ABOVE_VAL, S_BELOW_VAL }; - enum ValEdge { E_RISING, E_FALLING }; + struct dvec *d, *d2, *dScale; - struct dvec *d, *d2, *dScale; + d = vec_get(meas->m_vec); - d = vec_get(meas->m_vec); + if (meas->m_vec2) { + d2 = vec_get(meas->m_vec2); + has_d2 = TRUE; + } else { + d2 = NULL; + } - if (meas->m_vec2) { - d2 = vec_get(meas->m_vec2); - has_d2 = TRUE; - } else { - d2 = NULL; - } + dScale = plot_cur->pl_scale; - dScale = plot_cur->pl_scale; + if (d == NULL) { + fprintf(cp_err, "Error: no such vector as %s.\n", meas->m_vec); + return; + } - if (d == NULL) { - fprintf(cp_err, "Error: no such vector as %s.\n", meas->m_vec); - return; - } + if (has_d2 && (d2 == NULL)) { + fprintf(cp_err, "Error: no such vector as %s.\n", meas->m_vec2); + return; + } + if (dScale == NULL) { + fprintf(cp_err, "Error: no scale vector.\n"); + return; + } - if (has_d2 && (d2 == NULL)) { - fprintf(cp_err, "Error: no such vector as %s.\n", meas->m_vec2); - return; - } - if (dScale == NULL) { - fprintf(cp_err, "Error: no scale vector.\n"); - return; - } + prevValue = 0.; + prevValue2 = 0.; + prevScaleValue = 0.; + first = 0; + measurement_pending = 0; + init_measured_value = 1; - prevValue =0.; - prevValue2 =0.; - prevScaleValue =0.; - first =0; - measurement_pending=0; - init_measured_value=1; - /* ----------------------------------------------------------------- * Take the string tests outside of the loop for speed. * ----------------------------------------------------------------- */ - if (cieq (meas->m_analysis,"ac")) - ac_check = TRUE ; - else if (cieq (meas->m_analysis,"sp")) - sp_check = TRUE ; - else if (cieq (meas->m_analysis,"dc")) - dc_check = TRUE ; + if (cieq (meas->m_analysis, "ac")) + ac_check = TRUE; + else if (cieq (meas->m_analysis, "sp")) + sp_check = TRUE; + else if (cieq (meas->m_analysis, "dc")) + dc_check = TRUE; else - tran_check = TRUE; - - for (i=0; i < d->v_length; i++) { + tran_check = TRUE; - if (ac_check) { - if (d->v_compdata) - value = get_value(meas, d, i); //d->v_compdata[i].cx_real; - else + for (i = 0; i < d->v_length; i++) { + + if (ac_check) { + if (d->v_compdata) + value = get_value(meas, d, i); //d->v_compdata[i].cx_real; + else + value = d->v_realdata[i]; + scaleValue = dScale->v_compdata[i].cx_real; + } else if (sp_check) { + if (d->v_compdata) + value = get_value(meas, d, i); //d->v_compdata[i].cx_real; + else + value = d->v_realdata[i]; + scaleValue = dScale->v_realdata[i]; + } else { value = d->v_realdata[i]; - scaleValue = dScale->v_compdata[i].cx_real; - } - else if (sp_check) { - if (d->v_compdata) - value = get_value(meas, d, i); //d->v_compdata[i].cx_real; - else - value = d->v_realdata[i]; - scaleValue = dScale->v_realdata[i]; - } - else { - value = d->v_realdata[i]; - scaleValue = dScale->v_realdata[i]; - } + scaleValue = dScale->v_realdata[i]; + } - if (has_d2) { - if (ac_check) { - if (d2->v_compdata) - value2 = get_value(meas, d2, i); //d->v_compdata[i].cx_real; - else + if (has_d2) { + if (ac_check) { + if (d2->v_compdata) + value2 = get_value(meas, d2, i); //d->v_compdata[i].cx_real; + else + value2 = d2->v_realdata[i]; + } else if (sp_check) { + if (d2->v_compdata) + value2 = get_value(meas, d2, i); //d->v_compdata[i].cx_real; + else + value2 = d2->v_realdata[i]; + } else { value2 = d2->v_realdata[i]; - } - else if (sp_check) { - if (d2->v_compdata) - value2 = get_value(meas, d2, i); //d->v_compdata[i].cx_real; - else - value2 = d2->v_realdata[i]; - } - else { - value2 = d2->v_realdata[i]; - } - } else { - value2 = NAN; - } + } + } else { + value2 = NAN; + } - /* 'dc' is special: it may start at an arbitrary scale value. - Use m_td to store this value, a delay TD does not make sense */ - if ((dc_check) && (i==0)) - meas->m_td = scaleValue; - /* if analysis tran, suppress values below TD */ - if ((tran_check) && (scaleValue < meas->m_td)) - continue; - /* if analysis ac, sp, suppress values below 0 */ - else if (((ac_check)||(sp_check)) && (scaleValue < 0)) - continue; + /* 'dc' is special: it may start at an arbitrary scale value. + Use m_td to store this value, a delay TD does not make sense */ + if ((dc_check) && (i == 0)) + meas->m_td = scaleValue; + /* if analysis tran, suppress values below TD */ + if ((tran_check) && (scaleValue < meas->m_td)) + continue; + /* if analysis ac, sp, suppress values below 0 */ + else if (((ac_check)||(sp_check)) && (scaleValue < 0)) + continue; - /* if 'dc': reset first if scale jumps back to origin */ - if ((first > 1) && (dc_check && (meas->m_td == scaleValue))) - first = 1; + /* if 'dc': reset first if scale jumps back to origin */ + if ((first > 1) && (dc_check && (meas->m_td == scaleValue))) + first = 1; - if (first == 1) { - if (has_d2) { - // initialise - crossCnt =0; - if (value < value2) { - section = S_BELOW_VAL; - if ( (prevValue <= value2) && (value >= value2) ) { - fallCnt =1; - crossCnt =1; + if (first == 1) { + if (has_d2) { + // initialise + crossCnt = 0; + if (value < value2) { + section = S_BELOW_VAL; + if ((prevValue <= value2) && (value >= value2)) { + fallCnt = 1; + crossCnt = 1; + } + + } else { + section = S_ABOVE_VAL; + if ((prevValue <= value2) && (value >= value2)) { + riseCnt = 1; + crossCnt = 1; + } + } + fflush(stdout); + } else { + // initialise + crossCnt = 0; + if (value < meas->m_val) { + section = S_BELOW_VAL; + if ((prevValue <= meas->m_val) && (value >= meas->m_val)) { + fallCnt = 1; + crossCnt = 1; + } + + } else { + section = S_ABOVE_VAL; + if ((prevValue <= meas->m_val) && (value >= meas->m_val)) { + riseCnt = 1; + crossCnt = 1; + } + } + fflush(stdout); + } + } + + if (first > 1) { + if (has_d2) { + if ((section == S_BELOW_VAL) && (value >= value2)) { + section = S_ABOVE_VAL; + crossCnt++; + riseCnt++; + if (meas->m_fall != MEASURE_LAST_TRANSITION) { + /* we can measure rise/cross transition if the user + * has not requested a last fall transition */ + measurement_pending = 1; + } + + } else if ((section == S_ABOVE_VAL) && (value <= value2)) { + section = S_BELOW_VAL; + crossCnt++; + fallCnt++; + if (meas->m_rise != MEASURE_LAST_TRANSITION) { + /* we can measure fall/cross transition if the user + * has not requested a last rise transition */ + measurement_pending = 1; + } } - } else { - section = S_ABOVE_VAL; - if ( (prevValue <= value2) && (value >= value2) ) { - riseCnt =1; - crossCnt =1; - } - } - fflush( stdout ) ; - } - else { - // initialise - crossCnt =0; - if (value < meas->m_val) { - section = S_BELOW_VAL; - if ( (prevValue <= meas->m_val) && (value >= meas->m_val) ) { - fallCnt =1; - crossCnt =1; - } - - } else { - section = S_ABOVE_VAL; - if ( (prevValue <= meas->m_val) && (value >= meas->m_val) ) { - riseCnt =1; - crossCnt =1; - } - } - fflush( stdout ) ; - } - } - - if (first > 1) { - if (has_d2) { - if ( (section == S_BELOW_VAL) && (value >= value2) ) { - section = S_ABOVE_VAL; - crossCnt++; - riseCnt++; - if( meas->m_fall != MEASURE_LAST_TRANSITION ){ - /* we can measure rise/cross transition if the user - * has not requested a last fall transition */ - measurement_pending=1; - } - - } else if ( (section == S_ABOVE_VAL) && (value <= value2) ) { - section = S_BELOW_VAL; - crossCnt++; - fallCnt++; - if( meas->m_rise != MEASURE_LAST_TRANSITION ){ - /* we can measure fall/cross transition if the user - * has not requested a last rise transition */ - measurement_pending=1; - } - } - - if ((crossCnt == meas->m_cross) || (riseCnt == meas->m_rise) || (fallCnt == meas->m_fall)) { - /* user requested an exact match of cross, rise, or fall - * exit when we meet condition */ + if ((crossCnt == meas->m_cross) || (riseCnt == meas->m_rise) || (fallCnt == meas->m_fall)) { + /* user requested an exact match of cross, rise, or fall + * exit when we meet condition */ // meas->m_measured = prevScaleValue + (value2 - prevValue) * (scaleValue - prevScaleValue) / (value - prevValue); - meas->m_measured = prevScaleValue + (prevValue2 - prevValue) * (scaleValue - prevScaleValue) / (value - prevValue - value2 + prevValue2); - return; - } - if ( measurement_pending ){ - if( (meas->m_cross == MEASURE_DEFAULT) && (meas->m_rise == MEASURE_DEFAULT) && (meas->m_fall == MEASURE_DEFAULT) ){ - /* user didn't request any option, return the first possible case */ - meas->m_measured = prevScaleValue + (prevValue2 - prevValue) * (scaleValue - prevScaleValue) / (value - prevValue - value2 + prevValue2); - return; - } else if( (meas->m_cross == MEASURE_LAST_TRANSITION) || (meas->m_rise == MEASURE_LAST_TRANSITION) || (meas->m_fall == MEASURE_LAST_TRANSITION) ){ - meas->m_measured = prevScaleValue + (prevValue2 - prevValue) * (scaleValue - prevScaleValue) / (value - prevValue - value2 + prevValue2); - /* no return - look for last */ - init_measured_value=0; + meas->m_measured = prevScaleValue + (prevValue2 - prevValue) * (scaleValue - prevScaleValue) / (value - prevValue - value2 + prevValue2); + return; } - measurement_pending=0; - } - } - else { - if ( (section == S_BELOW_VAL) && (value >= meas->m_val) ) { - section = S_ABOVE_VAL; - crossCnt++; - riseCnt++; - if( meas->m_fall != MEASURE_LAST_TRANSITION ){ - /* we can measure rise/cross transition if the user - * has not requested a last fall transition */ - measurement_pending=1; + if (measurement_pending) { + if ((meas->m_cross == MEASURE_DEFAULT) && (meas->m_rise == MEASURE_DEFAULT) && (meas->m_fall == MEASURE_DEFAULT)) { + /* user didn't request any option, return the first possible case */ + meas->m_measured = prevScaleValue + (prevValue2 - prevValue) * (scaleValue - prevScaleValue) / (value - prevValue - value2 + prevValue2); + return; + } else if ((meas->m_cross == MEASURE_LAST_TRANSITION) || (meas->m_rise == MEASURE_LAST_TRANSITION) || (meas->m_fall == MEASURE_LAST_TRANSITION)) { + meas->m_measured = prevScaleValue + (prevValue2 - prevValue) * (scaleValue - prevScaleValue) / (value - prevValue - value2 + prevValue2); + /* no return - look for last */ + init_measured_value = 0; + } + measurement_pending = 0; + } + } else { + if ((section == S_BELOW_VAL) && (value >= meas->m_val)) { + section = S_ABOVE_VAL; + crossCnt++; + riseCnt++; + if (meas->m_fall != MEASURE_LAST_TRANSITION) { + /* we can measure rise/cross transition if the user + * has not requested a last fall transition */ + measurement_pending = 1; + } + + } else if ((section == S_ABOVE_VAL) && (value <= meas->m_val)) { + section = S_BELOW_VAL; + crossCnt++; + fallCnt++; + if (meas->m_rise != MEASURE_LAST_TRANSITION) { + /* we can measure fall/cross transition if the user + * has not requested a last rise transition */ + measurement_pending = 1; + } } - } else if ( (section == S_ABOVE_VAL) && (value <= meas->m_val) ) { - section = S_BELOW_VAL; - crossCnt++; - fallCnt++; - if( meas->m_rise != MEASURE_LAST_TRANSITION ){ - /* we can measure fall/cross transition if the user - * has not requested a last rise transition */ - measurement_pending=1; + if ((crossCnt == meas->m_cross) || (riseCnt == meas->m_rise) || (fallCnt == meas->m_fall)) { + /* user requested an exact match of cross, rise, or fall + * exit when we meet condition */ + meas->m_measured = prevScaleValue + (meas->m_val - prevValue) * (scaleValue - prevScaleValue) / (value - prevValue); + return; } - } - - if ((crossCnt == meas->m_cross) || (riseCnt == meas->m_rise) || (fallCnt == meas->m_fall)) { - /* user requested an exact match of cross, rise, or fall - * exit when we meet condition */ - meas->m_measured = prevScaleValue + (meas->m_val - prevValue) * (scaleValue - prevScaleValue) / (value - prevValue); - return; - } - if ( measurement_pending ){ - if( (meas->m_cross == MEASURE_DEFAULT) && (meas->m_rise == MEASURE_DEFAULT) && (meas->m_fall == MEASURE_DEFAULT) ){ - /* user didn't request any option, return the first possible case */ - meas->m_measured = prevScaleValue + (meas->m_val - prevValue) * (scaleValue - prevScaleValue) / (value - prevValue); - return; - } else if( (meas->m_cross == MEASURE_LAST_TRANSITION) || (meas->m_rise == MEASURE_LAST_TRANSITION) || (meas->m_fall == MEASURE_LAST_TRANSITION) ){ - meas->m_measured = prevScaleValue + (meas->m_val - prevValue) * (scaleValue - prevScaleValue) / (value - prevValue); - /* no return - look for last */ - init_measured_value=0; + if (measurement_pending) { + if ((meas->m_cross == MEASURE_DEFAULT) && (meas->m_rise == MEASURE_DEFAULT) && (meas->m_fall == MEASURE_DEFAULT)) { + /* user didn't request any option, return the first possible case */ + meas->m_measured = prevScaleValue + (meas->m_val - prevValue) * (scaleValue - prevScaleValue) / (value - prevValue); + return; + } else if ((meas->m_cross == MEASURE_LAST_TRANSITION) || (meas->m_rise == MEASURE_LAST_TRANSITION) || (meas->m_fall == MEASURE_LAST_TRANSITION)) { + meas->m_measured = prevScaleValue + (meas->m_val - prevValue) * (scaleValue - prevScaleValue) / (value - prevValue); + /* no return - look for last */ + init_measured_value = 0; + } + measurement_pending = 0; } - measurement_pending=0; - } - } - } - first ++; + } + } + first ++; - prevValue = value; - if (has_d2) - prevValue2 = value2; - prevScaleValue = scaleValue; - } + prevValue = value; + if (has_d2) + prevValue2 = value2; + prevScaleValue = scaleValue; + } - if ( init_measured_value ){ - meas->m_measured = NAN; - } - return; + if (init_measured_value) + meas->m_measured = NAN; + + return; } + /* ----------------------------------------------------------------- * Function: process an AT measurement statement which has been * parsed into a measurement structure. We make sure to interpolate * the value when appropriate. * ----------------------------------------------------------------- */ -static void measure_at( - MEASUREPTR meas, /* in : parsed "at" data */ - double at /* in: time to perform measurement */ -) { +static void +measure_at( + MEASUREPTR meas, /* in : parsed "at" data */ + double at /* in: time to perform measurement */ + ) +{ + int i; + double value, pvalue, svalue, psvalue; + bool ac_check = FALSE, sp_check = FALSE, dc_check = FALSE, tran_check = FALSE; + struct dvec *d, *dScale; - int i; - double value, pvalue, svalue, psvalue; - bool ac_check = FALSE, sp_check = FALSE, dc_check = FALSE, tran_check = FALSE ; - struct dvec *d, *dScale; + psvalue = pvalue = 0; + d = vec_get(meas->m_vec); + dScale = plot_cur->pl_scale; - psvalue = pvalue = 0; - d = vec_get(meas->m_vec); - dScale = plot_cur->pl_scale; + if (d == NULL) { + fprintf(cp_err, "Error: no such vector as %s.\n", meas->m_vec); + return; + } - if (d == NULL) { - fprintf(cp_err, "Error: no such vector as %s.\n", meas->m_vec); - return; - } + if (dScale == NULL) { + fprintf(cp_err, "Error: no such vector time, frequency or dc.\n"); + return; + } - if (dScale == NULL) { - fprintf(cp_err, "Error: no such vector time, frequency or dc.\n"); - return; - } - /* ----------------------------------------------------------------- * Take the string tests outside of the loop for speed. * ----------------------------------------------------------------- */ - if (cieq (meas->m_analysis,"ac")) - ac_check = TRUE ; - else if (cieq (meas->m_analysis,"sp")) - sp_check = TRUE ; - else if (cieq (meas->m_analysis,"dc")) - dc_check = TRUE ; + if (cieq (meas->m_analysis, "ac")) + ac_check = TRUE; + else if (cieq (meas->m_analysis, "sp")) + sp_check = TRUE; + else if (cieq (meas->m_analysis, "dc")) + dc_check = TRUE; else - tran_check = TRUE; - - for (i=0; i < d->v_length; i++) { - if (ac_check) { - if (d->v_compdata) - value = get_value(meas, d, i); //d->v_compdata[i].cx_real; - else { + tran_check = TRUE; + + for (i = 0; i < d->v_length; i++) { + if (ac_check) { + if (d->v_compdata) { + value = get_value(meas, d, i); //d->v_compdata[i].cx_real; + } else { + value = d->v_realdata[i]; + // fprintf(cp_err, "Warning: 'meas ac' input vector is real!\n"); + } + svalue = dScale->v_compdata[i].cx_real; + } else if (sp_check) { + if (d->v_compdata) + value = get_value(meas, d, i); //d->v_compdata[i].cx_real; + else + value = d->v_realdata[i]; + svalue = dScale->v_realdata[i]; + } else { value = d->v_realdata[i]; -// fprintf(cp_err, "Warning: 'meas ac' input vector is real!\n"); - } - svalue = dScale->v_compdata[i].cx_real; - } - else if (sp_check) { - if (d->v_compdata) - value = get_value(meas, d, i); //d->v_compdata[i].cx_real; - else - value = d->v_realdata[i]; - svalue = dScale->v_realdata[i]; - } - else { - value = d->v_realdata[i]; - svalue = dScale->v_realdata[i]; - } + svalue = dScale->v_realdata[i]; + } - if ( (i > 0) && (psvalue <= at) && (svalue >= at) ) { - meas->m_measured = pvalue + (at - psvalue) * (value - pvalue) / (svalue - psvalue); - return; - } - else if (dc_check && (i > 0) && (psvalue >= at) && (svalue <= at) ) { - meas->m_measured = pvalue + (at - psvalue) * (value - pvalue) / (svalue - psvalue); - return; - } + if ((i > 0) && (psvalue <= at) && (svalue >= at)) { + meas->m_measured = pvalue + (at - psvalue) * (value - pvalue) / (svalue - psvalue); + return; + } else if (dc_check && (i > 0) && (psvalue >= at) && (svalue <= at)) { + meas->m_measured = pvalue + (at - psvalue) * (value - pvalue) / (svalue - psvalue); + return; + } - psvalue = svalue; - pvalue = value; - } + psvalue = svalue; + pvalue = value; + } - meas->m_measured = NAN; - return; + meas->m_measured = NAN; + return; } @@ -706,664 +703,697 @@ static void measure_at( * the value here when we have m_from and m_to constraints * so this * function is slightly wrong. Need to fix in future rev. * ----------------------------------------------------------------- */ -static void measure_minMaxAvg( - MEASUREPTR meas, /* in : parsed measurement data request */ - ANALYSIS_TYPE_T mFunctionType /* in: one of AT_AVG, AT_MIN, AT_MAX, AT_MIN_AT, AT_MAX_AT */ -) { +static void +measure_minMaxAvg( + MEASUREPTR meas, /* in : parsed measurement data request */ + ANALYSIS_TYPE_T mFunctionType /* in: one of AT_AVG, AT_MIN, AT_MAX, AT_MIN_AT, AT_MAX_AT */ + ) +{ + int i, avgCnt; + struct dvec *d, *dScale; + double value, svalue, mValue, mValueAt; + int first; + bool ac_check = FALSE, sp_check = FALSE, dc_check = FALSE, tran_check = FALSE; - int i, avgCnt; - struct dvec *d, *dScale; - double value, svalue, mValue, mValueAt; - int first; - bool ac_check = FALSE, sp_check = FALSE, dc_check = FALSE, tran_check = FALSE ; + mValue = 0; + mValueAt = svalue = 0; + meas->m_measured = NAN; + meas->m_measured_at = NAN; + first = 0; + avgCnt = 0; - mValue =0; - mValueAt = svalue =0; - meas->m_measured = NAN; - meas->m_measured_at = NAN; - first =0; - avgCnt =0; + d = vec_get(meas->m_vec); + if (d == NULL) { + fprintf(cp_err, "Error: no such vector as %s.\n", meas->m_vec); + return; + } - d = vec_get(meas->m_vec); - if (d == NULL) { - fprintf(cp_err, "Error: no such vector as %s.\n", meas->m_vec); - return; - } - /* ----------------------------------------------------------------- * Take the string tests outside of the loop for speed. * ----------------------------------------------------------------- */ - if (cieq (meas->m_analysis,"ac")) - ac_check = TRUE ; - else if (cieq (meas->m_analysis,"sp")) - sp_check = TRUE ; - else if (cieq (meas->m_analysis,"dc")) - dc_check = TRUE ; + if (cieq (meas->m_analysis, "ac")) + ac_check = TRUE; + else if (cieq (meas->m_analysis, "sp")) + sp_check = TRUE; + else if (cieq (meas->m_analysis, "dc")) + dc_check = TRUE; else - tran_check = TRUE; + tran_check = TRUE; - if (ac_check || sp_check) - dScale = vec_get("frequency"); - else if (tran_check) - dScale = vec_get("time"); - else if (dc_check) - dScale = vec_get("v-sweep"); - else {/* error */ - fprintf(cp_err, "Error: no such analysis type as %s.\n", meas->m_analysis); - return; - } - if (dScale == NULL) { - fprintf(cp_err, "Error: no such vector as time, frquency or v-sweep.\n"); - return; - } - - for (i=0; i < d->v_length; i++) { - if (ac_check) { - if (d->v_compdata) - value = get_value(meas, d, i); //d->v_compdata[i].cx_real; - else { - value = d->v_realdata[i]; -// fprintf(cp_err, "Warning: 'meas ac' input vector is real!\n"); - } - svalue = dScale->v_compdata[i].cx_real; - } - else if (sp_check) { - if (d->v_compdata) - value = get_value(meas, d, i); //d->v_compdata[i].cx_real; - else - value = d->v_realdata[i]; - svalue = dScale->v_realdata[i]; - } - else { - value = d->v_realdata[i]; - svalue = dScale->v_realdata[i]; - } + if (ac_check || sp_check) { + dScale = vec_get("frequency"); + } else if (tran_check) { + dScale = vec_get("time"); + } else if (dc_check) { + dScale = vec_get("v-sweep"); + } else { /* error */ + fprintf(cp_err, "Error: no such analysis type as %s.\n", meas->m_analysis); + return; + } - /* dc: start from pos or neg scale value */ - if (dc_check) { - if ((svalue < meas->m_from) || (svalue > meas->m_to)) - continue; - } - /* all others: start from neg scale value */ - else { - if (svalue < meas->m_from) - continue; + if (dScale == NULL) { + fprintf(cp_err, "Error: no such vector as time, frquency or v-sweep.\n"); + return; + } - if ((meas->m_to != 0.0e0) && (svalue > meas->m_to) ) - break; - } - - if (first ==0) { - mValue = value; - mValueAt = svalue; - first =1; - - } else { - switch (mFunctionType) { - case AT_MIN: - case AT_MIN_AT: { - if (value <= mValue) { - mValue = value; - mValueAt = svalue; + for (i = 0; i < d->v_length; i++) { + if (ac_check) { + if (d->v_compdata) { + value = get_value(meas, d, i); //d->v_compdata[i].cx_real; + } else { + value = d->v_realdata[i]; + // fprintf(cp_err, "Warning: 'meas ac' input vector is real!\n"); } - break; - } - case AT_MAX_AT: - case AT_MAX: { - if (value >= mValue) { - mValue = value; - mValueAt = svalue; + svalue = dScale->v_compdata[i].cx_real; + } else if (sp_check) { + if (d->v_compdata) + value = get_value(meas, d, i); //d->v_compdata[i].cx_real; + else + value = d->v_realdata[i]; + svalue = dScale->v_realdata[i]; + } else { + value = d->v_realdata[i]; + svalue = dScale->v_realdata[i]; + } + + if (dc_check) { + /* dc: start from pos or neg scale value */ + if ((svalue < meas->m_from) || (svalue > meas->m_to)) + continue; + } else { + /* all others: start from neg scale value */ + if (svalue < meas->m_from) + continue; + + if ((meas->m_to != 0.0e0) && (svalue > meas->m_to)) + break; + } + + if (first == 0) { + mValue = value; + mValueAt = svalue; + first = 1; + + } else { + switch (mFunctionType) { + case AT_MIN: + case AT_MIN_AT: { + if (value <= mValue) { + mValue = value; + mValueAt = svalue; + } + break; + } + case AT_MAX_AT: + case AT_MAX: { + if (value >= mValue) { + mValue = value; + mValueAt = svalue; + } + break; + } + case AT_AVG: { + mValue = mValue + value; + avgCnt ++; + break; + } + default : + fprintf(cp_err, "Error: improper min/max/avg call.\n"); } - break; - } - case AT_AVG: { - mValue = mValue + value; - avgCnt ++; - break; - } - default : - fprintf(cp_err, "Error: improper min/max/avg call.\n"); - } - } - } + } + } - switch (mFunctionType) - { - case AT_AVG: { - meas->m_measured = (mValue / avgCnt); - meas->m_measured_at = svalue; - break; - } - case AT_MIN: - case AT_MAX: - case AT_MIN_AT: - case AT_MAX_AT: { - meas->m_measured = mValue; - meas->m_measured_at = mValueAt; - break; - } - default : - fprintf(cp_err, "Error: improper min/max/avg call.\n"); - } - return; + switch (mFunctionType) + { + case AT_AVG: { + meas->m_measured = (mValue / avgCnt); + meas->m_measured_at = svalue; + break; + } + case AT_MIN: + case AT_MAX: + case AT_MIN_AT: + case AT_MAX_AT: { + meas->m_measured = mValue; + meas->m_measured_at = mValueAt; + break; + } + default : + fprintf(cp_err, "Error: improper min/max/avg call.\n"); + } + return; } + /* ----------------------------------------------------------------- * Function: process an RMS or INTEG statement which has been * parsed into a measurement structure. Here we do interpolate * the starting and stopping time window so the answer is correct. * ----------------------------------------------------------------- */ -static void measure_rms_integral( - MEASUREPTR meas, /* in : parsed measurement data request */ - ANALYSIS_TYPE_T mFunctionType /* in: one of AT_RMS, or AT_INTEG */ -) { - int i; /* counter */ - int xy_size ; /* # of temp array elements */ - struct dvec *d, *xScale; /* value and indpendent (x-axis) vectors */ - double value, xvalue; /* current value and independent value */ - double *x ; /* temp x array */ - double *y ; /* temp y array */ - double toVal ; /* to time value */ - double *width ; /* temp width array */ - double sum1 ; /* first sum */ - double sum2 ; /* second sum */ - double sum3 ; /* third sum */ - int first; - bool ac_check = FALSE, sp_check = FALSE, dc_check = FALSE, tran_check = FALSE ; +static void +measure_rms_integral( + MEASUREPTR meas, /* in : parsed measurement data request */ + ANALYSIS_TYPE_T mFunctionType /* in: one of AT_RMS, or AT_INTEG */ + ) +{ + int i; /* counter */ + int xy_size; /* # of temp array elements */ + struct dvec *d, *xScale; /* value and indpendent (x-axis) vectors */ + double value, xvalue; /* current value and independent value */ + double *x; /* temp x array */ + double *y; /* temp y array */ + double toVal; /* to time value */ + double *width; /* temp width array */ + double sum1; /* first sum */ + double sum2; /* second sum */ + double sum3; /* third sum */ + int first; + bool ac_check = FALSE, sp_check = FALSE, dc_check = FALSE, tran_check = FALSE; - xvalue =0; - meas->m_measured = NAN; - meas->m_measured_at = NAN; - first =0; + xvalue = 0; + meas->m_measured = NAN; + meas->m_measured_at = NAN; + first = 0; - if (cieq (meas->m_analysis,"ac")) - ac_check = TRUE ; - else if (cieq (meas->m_analysis,"sp")) - sp_check = TRUE ; - else if (cieq (meas->m_analysis,"dc")) - dc_check = TRUE ; + if (cieq (meas->m_analysis, "ac")) + ac_check = TRUE; + else if (cieq (meas->m_analysis, "sp")) + sp_check = TRUE; + else if (cieq (meas->m_analysis, "dc")) + dc_check = TRUE; else - tran_check = TRUE; + tran_check = TRUE; - d = vec_get(meas->m_vec); - if (d == NULL) { - fprintf(cp_err, "Error: no such vector as %s.\n", meas->m_vec); - return; - } + d = vec_get(meas->m_vec); + if (d == NULL) { + fprintf(cp_err, "Error: no such vector as %s.\n", meas->m_vec); + return; + } - if (ac_check || sp_check) - xScale = vec_get("frequency"); - else if (tran_check) - xScale = vec_get("time"); - else if (dc_check) - xScale = vec_get("v-sweep"); - else {/* error */ - fprintf(cp_err, "Error: no such analysis type as %s.\n", meas->m_analysis); - return; - } + if (ac_check || sp_check) { + xScale = vec_get("frequency"); + } else if (tran_check) { + xScale = vec_get("time"); + } else if (dc_check) { + xScale = vec_get("v-sweep"); + } else { /* error */ + fprintf(cp_err, "Error: no such analysis type as %s.\n", meas->m_analysis); + return; + } - if (xScale == NULL) { - fprintf(cp_err, "Error: no such vector as time.\n"); - return; - } + if (xScale == NULL) { + fprintf(cp_err, "Error: no such vector as time.\n"); + return; + } - /* Allocate buffers for calculation. */ - x = TMALLOC(double, xScale->v_length); - y = TMALLOC(double, xScale->v_length); - width = TMALLOC(double, xScale->v_length + 1); + /* Allocate buffers for calculation. */ + x = TMALLOC(double, xScale->v_length); + y = TMALLOC(double, xScale->v_length); + width = TMALLOC(double, xScale->v_length + 1); - xy_size = 0 ; - toVal = -1 ; - /* create new set of values over interval [from, to] -- interpolate if necessary */ - for (i=0; i < d->v_length; i++) { - if (ac_check) { - if (d->v_compdata) - value = get_value(meas, d, i); //d->v_compdata[i].cx_real; - else { - value = d->v_realdata[i]; -// fprintf(cp_err, "Warning: 'meas ac' input vector is real!\n"); - } - xvalue = xScale->v_compdata[i].cx_real; - } - else { - value = d->v_realdata[i]; - xvalue = xScale->v_realdata[i]; - } - - if (xvalue < meas->m_from) - continue; - - if ((meas->m_to != 0.0e0) && (xvalue > meas->m_to) ){ - // interpolate ending value if necessary. - if (!(AlmostEqualUlps( xvalue, meas->m_to, 100))){ - value = measure_interpolate( xScale, d, i-1, i, meas->m_to, 'y', meas ); - xvalue = meas->m_to ; - } - x[xy_size] = xvalue ; - if (mFunctionType == AT_RMS) - y[xy_size++] = value * value ; - else - y[xy_size++] = value ; - toVal = xvalue ; - break; - } - - if (first == 0) { - if( meas->m_from != 0.0e0 && (i > 0) ){ - // interpolate starting value. - if (!(AlmostEqualUlps( xvalue, meas->m_from, 100))){ - value = measure_interpolate( xScale, d, i-1, i, meas->m_from, 'y' , meas); - xvalue = meas->m_from ; + xy_size = 0; + toVal = -1; + /* create new set of values over interval [from, to] -- interpolate if necessary */ + for (i = 0; i < d->v_length; i++) { + if (ac_check) { + if (d->v_compdata) { + value = get_value(meas, d, i); //d->v_compdata[i].cx_real; + } else { + value = d->v_realdata[i]; + // fprintf(cp_err, "Warning: 'meas ac' input vector is real!\n"); } - } - meas->m_measured_at = xvalue ; - first = 1; - } - x[xy_size] = xvalue ; - if (mFunctionType == AT_RMS) - y[xy_size++] = value * value ; - else - y[xy_size++] = value ; - } + xvalue = xScale->v_compdata[i].cx_real; + } else { + value = d->v_realdata[i]; + xvalue = xScale->v_realdata[i]; + } - // evaluate segment width - for ( i = 0; i < xy_size-1; i++ ) width[i] = x[i+1] - x[i] ; - width[i++] = 0; - width[i++] = 0; + if (xvalue < meas->m_from) + continue; - // Compute Integral (area under curve) - i = 0; - sum1 = sum2 = sum3 = 0.0 ; - while ( i < xy_size-1 ) { - // Simpson's 3/8 Rule - if ( AlmostEqualUlps( width[i], width[i+1], 100 ) && - AlmostEqualUlps( width[i], width[i+2], 100 ) ) { - sum1 += 3*width[i] * (y[i] + 3*(y[i+1] + y[i+2]) + y[i+3]) / 8.0; - i += 3; - } - // Simpson's 1/3 Rule - else if ( AlmostEqualUlps( width[i], width[i+1], 100 ) ) { - sum2 += width[i] * (y[i] + 4*y[i+1] + y[i+2]) / 3.0 ; - i += 2; - } - // Trapezoidal Rule - else if ( !AlmostEqualUlps( width[i], width[i+1], 100 ) ) { - sum3 += width[i] * (y[i] + y[i+1]) / 2; - i++; - } - } + if ((meas->m_to != 0.0e0) && (xvalue > meas->m_to)) { + // interpolate ending value if necessary. + if (!AlmostEqualUlps(xvalue, meas->m_to, 100)) { + value = measure_interpolate(xScale, d, i-1, i, meas->m_to, 'y', meas); + xvalue = meas->m_to; + } + x[xy_size] = xvalue; + if (mFunctionType == AT_RMS) + y[xy_size++] = value * value; + else + y[xy_size++] = value; + toVal = xvalue; + break; + } - /* Now set the measurement values if not set */ - if( toVal < 0.0 ){ - if (ac_check) { - if (d->v_compdata) - value = get_value(meas, d, i); //d->v_compdata[i].cx_real; - else { - value = d->v_realdata[i]; -// fprintf(cp_err, "Warning: 'meas ac' input vector is real!\n"); - } - xvalue = xScale->v_compdata[i].cx_real; - toVal = xScale->v_compdata[d->v_length-1].cx_real; - } - else { - toVal = xScale->v_realdata[d->v_length-1]; - } + if (first == 0) { + if (meas->m_from != 0.0e0 && (i > 0)) { + // interpolate starting value. + if (!AlmostEqualUlps(xvalue, meas->m_from, 100)) { + value = measure_interpolate(xScale, d, i-1, i, meas->m_from, 'y' , meas); + xvalue = meas->m_from; + } + } + meas->m_measured_at = xvalue; + first = 1; + } + x[xy_size] = xvalue; + if (mFunctionType == AT_RMS) + y[xy_size++] = value * value; + else + y[xy_size++] = value; + } + + // evaluate segment width + for (i = 0; i < xy_size-1; i++) + width[i] = x[i+1] - x[i]; + width[i++] = 0; + width[i++] = 0; + + // Compute Integral (area under curve) + i = 0; + sum1 = sum2 = sum3 = 0.0; + while (i < xy_size-1) { + // Simpson's 3/8 Rule + if (AlmostEqualUlps(width[i], width[i+1], 100) && + AlmostEqualUlps(width[i], width[i+2], 100)) { + sum1 += 3*width[i] * (y[i] + 3*(y[i+1] + y[i+2]) + y[i+3]) / 8.0; + i += 3; + } + // Simpson's 1/3 Rule + else if (AlmostEqualUlps(width[i], width[i+1], 100)) { + sum2 += width[i] * (y[i] + 4*y[i+1] + y[i+2]) / 3.0; + i += 2; + } + // Trapezoidal Rule + else if (!AlmostEqualUlps(width[i], width[i+1], 100)) { + sum3 += width[i] * (y[i] + y[i+1]) / 2; + i++; + } + } + + /* Now set the measurement values if not set */ + if (toVal < 0.0) { + if (ac_check) { + if (d->v_compdata) { + value = get_value(meas, d, i); //d->v_compdata[i].cx_real; + } else { + value = d->v_realdata[i]; + // fprintf(cp_err, "Warning: 'meas ac' input vector is real!\n"); + } + xvalue = xScale->v_compdata[i].cx_real; + toVal = xScale->v_compdata[d->v_length-1].cx_real; + } else { + toVal = xScale->v_realdata[d->v_length-1]; + } - } - meas->m_from = meas->m_measured_at ; - meas->m_to = toVal ; + } + meas->m_from = meas->m_measured_at; + meas->m_to = toVal; - if (mFunctionType == AT_RMS) { - meas->m_measured = (sum1 + sum2 + sum3)/ (toVal - meas->m_measured_at) ; - meas->m_measured = sqrt(meas->m_measured); + if (mFunctionType == AT_RMS) { + meas->m_measured = (sum1 + sum2 + sum3)/ (toVal - meas->m_measured_at); + meas->m_measured = sqrt(meas->m_measured); - } else { - meas->m_measured = ( sum1 + sum2 + sum3 ); - } - txfree(x); txfree(y); txfree(width); + } else { + meas->m_measured = (sum1 + sum2 + sum3); + } + + txfree(x); + txfree(y); + txfree(width); +} -} /* end measure_rms_integral() */ /* ----------------------------------------------------------------- * Function: Wrapper function to process a RMS measurement. * ----------------------------------------------------------------- */ #if 0 -static void measure_rms( - MEASUREPTR meas /* in : parsed measurement data request */ -) { - // RMS (root mean squared): - // Calculates the square root of the area under the 'out_var2' curve - // divided be the period of interest - measure_rms_integral(meas,AT_RMS) ; - return; +static void +measure_rms( + MEASUREPTR meas /* in : parsed measurement data request */ + ) +{ + // RMS (root mean squared): + // Calculates the square root of the area under the 'out_var2' curve + // divided be the period of interest + measure_rms_integral(meas, AT_RMS); + return; } #endif + /* ----------------------------------------------------------------- * Function: Wrapper function to process a integration measurement. * ----------------------------------------------------------------- */ #if 0 -static void measure_integ( - MEASUREPTR meas /* in : parsed measurement data request */ -) { - // INTEGRAL INTEG - measure_rms_integral(meas,AT_INTEG) ; - return; +static void +measure_integ( + MEASUREPTR meas /* in : parsed measurement data request */ + ) +{ + // INTEGRAL INTEG + measure_rms_integral(meas, AT_INTEG); + return; } #endif + /* still some more work to do.... */ #if 0 -static void measure_deriv(void) { +static void +measure_deriv(void) +{ // DERIVATIVE DERIV - return; + return; } #endif + // ERR Equations #if 0 -static void measure_ERR(void) { - return; +static void +measure_ERR(void) +{ + return; } -static void measure_ERR1(void) { - return; +static void +measure_ERR1(void) +{ + return; } -static void measure_ERR2(void) { - return; +static void +measure_ERR2(void) +{ + return; } -static void measure_ERR3(void) { - return; +static void +measure_ERR3(void) +{ + return; } #endif -void com_dotmeasure(wordlist *wl) { - NG_IGNORE(wl); +void +com_dotmeasure(wordlist *wl) +{ + NG_IGNORE(wl); -/* simulation info */ -// printf("*%s\n", plot_cur->pl_title); -// printf("\t %s, %s\n", plot_cur->pl_name, plot_cur->pl_date); // missing temp + /* simulation info */ + // printf("*%s\n", plot_cur->pl_title); + // printf("\t %s, %s\n", plot_cur->pl_name, plot_cur->pl_date); // missing temp - return; + return; } + /* ----------------------------------------------------------------- * Function: Given a measurement variable name, see if the analysis * has generated a measure vector for it. Returns TRUE if it exists * or varname is NULL, Return FALSE otherwise * ----------------------------------------------------------------- */ -static int measure_valid_vector( - char *varname /* in: requested variable name */ -) { +static int +measure_valid_vector( + char *varname /* in: requested variable name */ + ) +{ + struct dvec *d; /* measurement vector */ - struct dvec *d; /* measurement vector */ + if (varname == NULL) + return TRUE; - if(varname == NULL) - return TRUE; - d = vec_get(varname); - if (d == NULL) - return FALSE; + d = vec_get(varname); + if (d == NULL) + return FALSE; - return TRUE; + return TRUE; } + /* ----------------------------------------------------------------- * Function: Given a wordlist and measurement structure, parse the * standard parameters such as RISE, FALL, VAL, TD, FROM, TO, etc. * in a measurement statement. We also check the appropriate * variables found in the measurement statement. * ----------------------------------------------------------------- */ -static int measure_parse_stdParams ( - MEASUREPTR meas, /* in : measurement structure */ - wordlist *wl, /* in : word list to parse */ - wordlist *wlBreak, /* out: where we stopped parsing */ - char *errbuf /* in/out: buffer where we write error messages */ -) { +static int +measure_parse_stdParams( + MEASUREPTR meas, /* in : measurement structure */ + wordlist *wl, /* in : word list to parse */ + wordlist *wlBreak, /* out: where we stopped parsing */ + char *errbuf /* in/out: buffer where we write error messages */ + ) +{ + int pCnt; + char *p, *pName, *pValue; + double *engVal, engVal1; - int pCnt; - char *p, *pName, *pValue; - double *engVal, engVal1; + pCnt = 0; + while (wl != wlBreak) { + p = wl->wl_word; + pName = strtok(p, "="); + pValue = strtok(NULL, "="); - pCnt = 0; - while (wl != wlBreak) { - p = wl->wl_word; - pName = strtok(p, "="); - pValue = strtok(NULL, "="); + if (pValue == NULL) { + if (strcasecmp(pName, "LAST") == 0) { + meas->m_cross = MEASURE_LAST_TRANSITION; + meas->m_rise = -1; + meas->m_fall = -1; + pCnt ++; + wl = wl->wl_next; + continue; + } else { + sprintf(errbuf, "bad syntax of ??\n"); + return 0; + } + } - if (pValue == NULL) { - if( strcasecmp(pName,"LAST")==0) { - meas->m_cross = MEASURE_LAST_TRANSITION; + if (strcasecmp(pValue, "LAST") == 0) { + engVal1 = MEASURE_LAST_TRANSITION; + } else { + if ((engVal = ft_numparse(&pValue, FALSE)) == NULL) { + sprintf(errbuf, "bad syntax of ??\n"); + return 0; + } + engVal1 = *engVal; // What is this ?? + } + + if (strcasecmp(pName, "RISE") == 0) { + meas->m_rise = (int)floor(engVal1 + 0.5); + meas->m_fall = -1; + meas->m_cross = -1; + } else if (strcasecmp(pName, "FALL") == 0) { + meas->m_fall = (int)floor(engVal1 + 0.5); + meas->m_rise = -1; + meas->m_cross = -1; + } else if (strcasecmp(pName, "CROSS") == 0) { + meas->m_cross = (int)floor(engVal1 + 0.5); meas->m_rise = -1; meas->m_fall = -1; - pCnt ++; - wl = wl->wl_next; - continue ; - } else { - sprintf(errbuf,"bad syntax of ??\n"); + } else if (strcasecmp(pName, "VAL") == 0) { + meas->m_val = engVal1; + } else if (strcasecmp(pName, "TD") == 0) { + meas->m_td = engVal1; + } else if (strcasecmp(pName, "FROM") == 0) { + meas->m_from = engVal1; + } else if (strcasecmp(pName, "TO") == 0) { + meas->m_to = engVal1; + } else if (strcasecmp(pName, "AT") == 0) { + meas->m_at = engVal1; + } else { + sprintf(errbuf, "no such parameter as '%s'\n", pName); return 0; - } - } + } - if( strcasecmp(pValue,"LAST")==0) { - engVal1 = MEASURE_LAST_TRANSITION; - } else { - if ((engVal = ft_numparse(&pValue, FALSE)) == NULL) { - sprintf(errbuf,"bad syntax of ??\n"); + pCnt ++; + wl = wl->wl_next; + } + + if (pCnt == 0) { + sprintf(errbuf, "bad syntax of ??\n"); + return 0; + } + + // valid vector + if (measure_valid_vector(meas->m_vec) == 0) { + sprintf(errbuf, "no such vector as '%s'\n", meas->m_vec); + return 0; + } + + // valid vector2 + if (meas->m_vec2 != NULL) + if (measure_valid_vector(meas->m_vec2) == 0) { + sprintf(errbuf, "no such vector as '%s'\n", meas->m_vec2); return 0; - } - engVal1 = *engVal; // What is this ?? - } + } - if(strcasecmp(pName,"RISE")==0) { - meas->m_rise = (int)floor(engVal1 + 0.5); - meas->m_fall = -1; - meas->m_cross = -1; - } else if(strcasecmp(pName,"FALL")==0) { - meas->m_fall = (int)floor(engVal1 + 0.5); - meas->m_rise = -1; - meas->m_cross = -1; - } else if(strcasecmp(pName,"CROSS")==0) { - meas->m_cross = (int)floor(engVal1 + 0.5); - meas->m_rise = -1; - meas->m_fall = -1; - } else if(strcasecmp(pName,"VAL")==0) { - meas->m_val = engVal1; - } else if(strcasecmp(pName,"TD")==0) { - meas->m_td = engVal1; - } else if(strcasecmp(pName,"FROM")==0) { - meas->m_from = engVal1; - } else if(strcasecmp(pName,"TO")==0) { - meas->m_to = engVal1; - } else if(strcasecmp(pName,"AT")==0) { - meas->m_at = engVal1; - } else { - sprintf(errbuf,"no such parameter as '%s'\n",pName); - return 0; - } + /* dc: make m_from always less than m_to */ + if (cieq("dc", meas->m_analysis)) + if (meas->m_to < meas->m_from) { + double tmp_val = meas->m_to; + meas->m_to = meas->m_from; + meas->m_from = tmp_val; + } - pCnt ++; - wl = wl->wl_next; - } - - if (pCnt == 0) { - sprintf(errbuf,"bad syntax of ??\n"); - return 0; - } - - // valid vector - if (measure_valid_vector(meas->m_vec)==0) { - sprintf(errbuf,"no such vector as '%s'\n", meas->m_vec); - return 0; - } - - // valid vector2 - if (meas->m_vec2 != NULL) { - if (measure_valid_vector(meas->m_vec2)==0) { - sprintf(errbuf,"no such vector as '%s'\n", meas->m_vec2); - return 0; - } - } - /* dc: make m_from always less than m_to */ - if (cieq("dc", meas->m_analysis)) - if (meas->m_to < meas->m_from) { - double tmp_val = meas->m_to; - meas->m_to = meas->m_from; - meas->m_from = tmp_val; - } - - return 1; + return 1; } + /* ----------------------------------------------------------------- * Function: Given a wordlist and measurement structure, parse a * FIND measurement statement. Most of the work is done by calling * measure_parse_stdParams. * ----------------------------------------------------------------- */ -static int measure_parse_find ( - MEASUREPTR meas, /* in : measurement structure */ - wordlist *wl, /* in : word list to parse */ - wordlist *wlBreak, /* out: where we stopped parsing */ - char *errbuf /* in/out: buffer where we write error messages */ -) { +static int +measure_parse_find( + MEASUREPTR meas, /* in : measurement structure */ + wordlist *wl, /* in : word list to parse */ + wordlist *wlBreak, /* out: where we stopped parsing */ + char *errbuf /* in/out: buffer where we write error messages */ + ) +{ + int pCnt; + char *p, *pName, *pVal; + double *engVal, engVal1; - int pCnt; - char *p, *pName, *pVal; - double *engVal, engVal1; + meas->m_vec = NULL; + meas->m_vec2 = NULL; + meas->m_val = 1e99; + meas->m_cross = -1; + meas->m_fall = -1; + meas->m_rise = -1; + meas->m_td = 0; + meas->m_from = 0.0e0; + meas->m_to = 0.0e0; + meas->m_at = 1e99; - meas->m_vec = NULL; - meas->m_vec2 = NULL; - meas->m_val = 1e99; - meas->m_cross = -1; - meas->m_fall = -1; - meas->m_rise = -1; - meas->m_td = 0; - meas->m_from = 0.0e0; - meas->m_to = 0.0e0; - meas->m_at = 1e99; + /* for DC, set new outer limits for 'from' and 'to' + because 0.0e0 may be valid inside of range */ + if (cieq("dc", meas->m_analysis)) { + meas->m_to = 1.0e99; + meas->m_from = -1.0e99; + } - /* for DC, set new outer limits for 'from' and 'to' - because 0.0e0 may be valid inside of range */ - if (cieq("dc", meas->m_analysis)) { - meas->m_to = 1.0e99; - meas->m_from = -1.0e99; - } + pCnt = 0; + while (wl != wlBreak) { + p = wl->wl_word; - pCnt =0; - while(wl != wlBreak) { - p = wl->wl_word; + if (pCnt == 0) { + meas->m_vec = cp_unquote(wl->wl_word); + /* correct for vectors like vm, vp etc. */ + if (cieq("ac", meas->m_analysis) || cieq("sp", meas->m_analysis)) + correct_vec(meas); + } else if (pCnt == 1) { + pName = strtok(p, "="); + pVal = strtok(NULL, "="); - if (pCnt == 0 ) { - meas->m_vec= cp_unquote(wl->wl_word); - /* correct for vectors like vm, vp etc. */ - if (cieq("ac", meas->m_analysis) || cieq("sp", meas->m_analysis)) - correct_vec(meas); - } else if (pCnt == 1) { - pName = strtok(p, "="); - pVal = strtok(NULL, "="); - - if (pVal == NULL) { - sprintf(errbuf,"bad syntax of WHEN\n"); - return 0; - } - - if (strcasecmp(pName,"AT")==0) { - if ((engVal = ft_numparse(&pVal, FALSE)) == NULL) { - sprintf(errbuf,"bad syntax of WHEN\n"); - return 0; + if (pVal == NULL) { + sprintf(errbuf, "bad syntax of WHEN\n"); + return 0; } - engVal1 = *engVal; + if (strcasecmp(pName, "AT") == 0) { + if ((engVal = ft_numparse(&pVal, FALSE)) == NULL) { + sprintf(errbuf, "bad syntax of WHEN\n"); + return 0; + } - meas->m_at = engVal1; + engVal1 = *engVal; - } else { - sprintf(errbuf,"bad syntax of WHEN\n"); - return 0; - } - } else { - if (measure_parse_stdParams(meas, wl, NULL, errbuf) == 0) - return 0; - } + meas->m_at = engVal1; - wl = wl->wl_next; - pCnt ++; - } + } else { + sprintf(errbuf, "bad syntax of WHEN\n"); + return 0; + } + } else { + if (measure_parse_stdParams(meas, wl, NULL, errbuf) == 0) + return 0; + } - return 1; + wl = wl->wl_next; + pCnt ++; + } + + return 1; } + /* ----------------------------------------------------------------- * Function: Given a wordlist and measurement structure, parse a * WHEN measurement statement. Most of the work is done by calling * measure_parse_stdParams. * ----------------------------------------------------------------- */ -static int measure_parse_when ( - MEASUREPTR meas, /* in : measurement structure */ - wordlist *wl, /* in : word list to parse */ - char *errBuf /* in/out: buffer where we write error messages */ -) { - int pCnt, err = 0; - char *p, *pVar1, *pVar2; - meas->m_vec = NULL; - meas->m_vec2 = NULL; - meas->m_val = 1e99; - meas->m_cross = -1; - meas->m_fall = -1; - meas->m_rise = -1; - meas->m_td = 0; - meas->m_from = 0.0e0; - meas->m_to = 0.0e0; - meas->m_at = 1e99; +static int +measure_parse_when( + MEASUREPTR meas, /* in : measurement structure */ + wordlist *wl, /* in : word list to parse */ + char *errBuf /* in/out: buffer where we write error messages */ + ) +{ + int pCnt, err = 0; + char *p, *pVar1, *pVar2; + meas->m_vec = NULL; + meas->m_vec2 = NULL; + meas->m_val = 1e99; + meas->m_cross = -1; + meas->m_fall = -1; + meas->m_rise = -1; + meas->m_td = 0; + meas->m_from = 0.0e0; + meas->m_to = 0.0e0; + meas->m_at = 1e99; - /* for DC, set new outer limits for 'from' and 'to' - because 0.0e0 may be valid inside of range */ - if (cieq("dc", meas->m_analysis)) { - meas->m_to = 1.0e99; - meas->m_from = -1.0e99; - } + /* for DC, set new outer limits for 'from' and 'to' + because 0.0e0 may be valid inside of range */ + if (cieq("dc", meas->m_analysis)) { + meas->m_to = 1.0e99; + meas->m_from = -1.0e99; + } - pCnt =0; - while (wl) { - p= wl->wl_word; + pCnt = 0; + while (wl) { + p = wl->wl_word; - if (pCnt == 0) { - pVar1 = strtok(p, "="); - pVar2 = strtok(NULL, "="); + if (pCnt == 0) { + pVar1 = strtok(p, "="); + pVar2 = strtok(NULL, "="); - if (pVar2 == NULL) { - sprintf(errBuf,"bad syntax\n"); - return 0; - } + if (pVar2 == NULL) { + sprintf(errBuf, "bad syntax\n"); + return 0; + } - meas->m_vec = copy(pVar1); - /* correct for vectors like vm, vp etc. */ - if (cieq("ac", meas->m_analysis) || cieq("sp", meas->m_analysis)) - correct_vec(meas); - if (measure_valid_vector(pVar2)==1) { - meas->m_vec2 = copy(pVar2); + meas->m_vec = copy(pVar1); /* correct for vectors like vm, vp etc. */ - if (cieq("ac", meas->m_analysis) || cieq("sp", meas->m_analysis)) - correct_vec(meas); - } - else - meas->m_val = INPevaluate( &pVar2, &err, 1 ); - } else { - if (measure_parse_stdParams(meas, wl, NULL, errBuf) == 0) - return 0; - break; - } + if (cieq("ac", meas->m_analysis) || cieq("sp", meas->m_analysis)) + correct_vec(meas); + if (measure_valid_vector(pVar2) == 1) { + meas->m_vec2 = copy(pVar2); + /* correct for vectors like vm, vp etc. */ + if (cieq("ac", meas->m_analysis) || cieq("sp", meas->m_analysis)) + correct_vec(meas); + } else { + meas->m_val = INPevaluate(&pVar2, &err, 1); + } + } else { + if (measure_parse_stdParams(meas, wl, NULL, errBuf) == 0) + return 0; + break; + } - wl = wl->wl_next; - pCnt ++; - } - return 1; + wl = wl->wl_next; + pCnt ++; + } + return 1; } @@ -1372,71 +1402,73 @@ static int measure_parse_when ( * TRIGGER or TARGET clause of a measurement statement. Most of the * work is done by calling measure_parse_stdParams. * ----------------------------------------------------------------- */ -static int measure_parse_trigtarg ( - MEASUREPTR meas, /* in : measurement structure */ - wordlist *words, /* in : word list to parse */ - wordlist *wlTarg, /* out : where we stopped parsing target clause */ - char *trigTarg, /* in : type of clause */ - char *errbuf /* in/out: buffer where we write error messages */ -) { +static int +measure_parse_trigtarg( + MEASUREPTR meas, /* in : measurement structure */ + wordlist *words, /* in : word list to parse */ + wordlist *wlTarg, /* out : where we stopped parsing target clause */ + char *trigTarg, /* in : type of clause */ + char *errbuf /* in/out: buffer where we write error messages */ + ) +{ + int pcnt; + char *p; - int pcnt; - char *p; + meas->m_vec = NULL; + meas->m_vec2 = NULL; + meas->m_cross = -1; + meas->m_fall = -1; + meas->m_rise = -1; + meas->m_td = 0; + meas->m_from = 0.0e0; + meas->m_to = 0.0e0; + meas->m_at = 1e99; - meas->m_vec = NULL; - meas->m_vec2 = NULL; - meas->m_cross = -1; - meas->m_fall = -1; - meas->m_rise = -1; - meas->m_td = 0; - meas->m_from = 0.0e0; - meas->m_to = 0.0e0; - meas->m_at = 1e99; + /* for DC, set new outer limits for 'from' and 'to' + because 0.0e0 may be valid inside of range */ + if (cieq("dc", meas->m_analysis)) { + meas->m_to = 1.0e99; + meas->m_from = -1.0e99; + } - /* for DC, set new outer limits for 'from' and 'to' - because 0.0e0 may be valid inside of range */ - if (cieq("dc", meas->m_analysis)) { - meas->m_to = 1.0e99; - meas->m_from = -1.0e99; - } + pcnt = 0; - pcnt =0; + while (words != wlTarg) { + p = words->wl_word; - while (words != wlTarg) { - p = words->wl_word; + if ((pcnt == 0) && !ciprefix("at", p)) { + meas->m_vec = cp_unquote(words->wl_word); + /* correct for vectors like vm, vp etc. */ + if (cieq("ac", meas->m_analysis) || cieq("sp", meas->m_analysis)) + correct_vec(meas); + } else if (ciprefix("at", p)) { + if (measure_parse_stdParams(meas, words, wlTarg, errbuf) == 0) + return 0; + } else { + if (measure_parse_stdParams(meas, words, wlTarg, errbuf) == 0) + return 0; + break; + } - if ((pcnt == 0) && !ciprefix("at", p)) { - meas->m_vec= cp_unquote(words->wl_word); - /* correct for vectors like vm, vp etc. */ - if (cieq("ac", meas->m_analysis) || cieq("sp", meas->m_analysis)) - correct_vec(meas); - } else if (ciprefix("at", p)) { - if (measure_parse_stdParams(meas, words, wlTarg, errbuf) == 0) - return 0; - } else { - if (measure_parse_stdParams(meas, words, wlTarg, errbuf) == 0) - return 0; - break; - } + words = words->wl_next; + pcnt ++; + } - words = words->wl_next; - pcnt ++; - } + if (pcnt == 0) { + sprintf(errbuf, "bad syntax of '%s'\n", trigTarg); + return 0; + } - if (pcnt == 0) { - sprintf(errbuf,"bad syntax of '%s'\n", trigTarg); - return 0; - } + // valid vector + if (measure_valid_vector(meas->m_vec) == 0) { + sprintf(errbuf, "no such vector as '%s'\n", meas->m_vec); + return 0; + } - // valid vector - if (measure_valid_vector(meas->m_vec)==0) { - sprintf(errbuf,"no such vector as '%s'\n", meas->m_vec); - return 0; - } - - return 1; + return 1; } + /* ----------------------------------------------------------------- * Function: Given a wordlist, extract the measurement statement, * process it, and return a result. If out_line is furnished, we @@ -1444,440 +1476,442 @@ static int measure_parse_trigtarg ( * variable allows us to check for "autostop". This function is * called from measure.c. We use the functions in this file because * the parsing is much more complete and thorough. -* ----------------------------------------------------------------- */ + * ----------------------------------------------------------------- */ int get_measure2( - wordlist *wl, /* in: a word list for us to process */ - double *result, /* out : the result of the measurement */ - char *out_line, /* out: formatted result - may be NULL */ - bool autocheck /* in: TRUE if checking for "autostop"; FALSE otherwise */ -) { - wordlist *words, *wlTarg, *wlWhen; - char errbuf[100]; - char *mAnalysis = NULL; // analysis type - char *mName = NULL; // name given to the measured output - char *mFunction = ""; - int precision; // measurement precision - ANALYSIS_TYPE_T mFunctionType = AT_UNKNOWN; - int wl_cnt; - char *p; + wordlist *wl, /* in: a word list for us to process */ + double *result, /* out : the result of the measurement */ + char *out_line, /* out: formatted result - may be NULL */ + bool autocheck /* in: TRUE if checking for "autostop"; FALSE otherwise */ + ) +{ + wordlist *words, *wlTarg, *wlWhen; + char errbuf[100]; + char *mAnalysis = NULL; // analysis type + char *mName = NULL; // name given to the measured output + char *mFunction = ""; + int precision; // measurement precision + ANALYSIS_TYPE_T mFunctionType = AT_UNKNOWN; + int wl_cnt; + char *p; - *result = 0.0e0; /* default result */ + *result = 0.0e0; /* default result */ - if (!wl) { - printf("usage: measure .....\n"); - return MEASUREMENT_FAILURE; - } + if (!wl) { + printf("usage: measure .....\n"); + return MEASUREMENT_FAILURE; + } - if (!plot_cur || !plot_cur->pl_dvecs || !plot_cur->pl_scale) { - fprintf(cp_err, "Error: no vectors available\n"); - return MEASUREMENT_FAILURE; - } + if (!plot_cur || !plot_cur->pl_dvecs || !plot_cur->pl_scale) { + fprintf(cp_err, "Error: no vectors available\n"); + return MEASUREMENT_FAILURE; + } - if (!ciprefix("tran", plot_cur->pl_typename) && !ciprefix("ac", plot_cur->pl_typename) && - !ciprefix("dc", plot_cur->pl_typename) && !ciprefix("sp", plot_cur->pl_typename)) { - fprintf(cp_err, "Error: measure limited to tran, dc, sp, or ac analysis\n"); - return MEASUREMENT_FAILURE; - } + if (!ciprefix("tran", plot_cur->pl_typename) && + !ciprefix("ac", plot_cur->pl_typename) && + !ciprefix("dc", plot_cur->pl_typename) && + !ciprefix("sp", plot_cur->pl_typename)) + { + fprintf(cp_err, "Error: measure limited to tran, dc, sp, or ac analysis\n"); + return MEASUREMENT_FAILURE; + } - words =wl; - wlTarg = NULL; - wlWhen = NULL; + words = wl; + wlTarg = NULL; + wlWhen = NULL; - if (!words) { - fprintf(cp_err, "Error: no assignment found.\n"); - return MEASUREMENT_FAILURE; - } + if (!words) { + fprintf(cp_err, "Error: no assignment found.\n"); + return MEASUREMENT_FAILURE; + } - precision = measure_get_precision() ; - wl_cnt = 0; - while (words) { + precision = measure_get_precision(); + wl_cnt = 0; + while (words) { - switch(wl_cnt) - { - case 0: + switch (wl_cnt) + { + case 0: mAnalysis = cp_unquote(words->wl_word); break; - case 1: + case 1: mName = cp_unquote(words->wl_word); break; - case 2: - { + case 2: + { mFunctionType = measure_function_type(words->wl_word); - if ( mFunctionType == AT_UNKNOWN ){ - if(!(autocheck)){ - printf("\tmeasure '%s' failed\n", mName); - printf("Error: measure %s :\n", mName); - printf("\tno such function as '%s'\n", words->wl_word); - } - return MEASUREMENT_FAILURE; + if (mFunctionType == AT_UNKNOWN) { + if (!autocheck) { + printf("\tmeasure '%s' failed\n", mName); + printf("Error: measure %s :\n", mName); + printf("\tno such function as '%s'\n", words->wl_word); + } + return MEASUREMENT_FAILURE; } break; - } - default: - { + } + default: + { p = words->wl_word; - if (strcasecmp(p,"targ")==0) - wlTarg = words; + if (strcasecmp(p, "targ") == 0) + wlTarg = words; - if (strcasecmp(p,"when")==0) - wlWhen = words; + if (strcasecmp(p, "when") == 0) + wlWhen = words; - break; - } - } - wl_cnt ++; - words = words->wl_next; - } + break; + } + } + wl_cnt ++; + words = words->wl_next; + } - if (wl_cnt < 3) { - printf("\tmeasure '%s' failed\n", mName); - printf("Error: measure %s :\n", mName); - printf("\tinvalid num params\n"); - return MEASUREMENT_FAILURE; - } + if (wl_cnt < 3) { + printf("\tmeasure '%s' failed\n", mName); + printf("Error: measure %s :\n", mName); + printf("\tinvalid num params\n"); + return MEASUREMENT_FAILURE; + } //------------------------ - words =wl; + words = wl; - if (words) - words = words->wl_next; // skip - if (words) - words = words->wl_next; // skip results name - if (words) - words = words->wl_next; // Function + if (words) + words = words->wl_next; // skip + if (words) + words = words->wl_next; // skip results name + if (words) + words = words->wl_next; // Function // switch here - switch(mFunctionType) - { - case AT_DELAY: - case AT_TRIG: - { - // trig parameters - MEASUREPTR measTrig, measTarg; - measTrig = TMALLOC(struct measure, 1); - measTarg = TMALLOC(struct measure, 1); + switch (mFunctionType) + { + case AT_DELAY: + case AT_TRIG: + { + // trig parameters + MEASUREPTR measTrig, measTarg; + measTrig = TMALLOC(struct measure, 1); + measTarg = TMALLOC(struct measure, 1); - measTrig->m_analysis = measTarg->m_analysis = mAnalysis; + measTrig->m_analysis = measTarg->m_analysis = mAnalysis; - if (measure_parse_trigtarg(measTrig, words , wlTarg, "trig", errbuf)==0) { + if (measure_parse_trigtarg(measTrig, words , wlTarg, "trig", errbuf) == 0) { measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); return MEASUREMENT_FAILURE; - } + } - if ((measTrig->m_rise == -1) && (measTrig->m_fall == -1) && - (measTrig->m_cross == -1) && (measTrig->m_at == 1e99)) { - sprintf(errbuf,"at, rise, fall or cross must be given\n"); + if ((measTrig->m_rise == -1) && (measTrig->m_fall == -1) && + (measTrig->m_cross == -1) && (measTrig->m_at == 1e99)) { + sprintf(errbuf, "at, rise, fall or cross must be given\n"); measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); return MEASUREMENT_FAILURE; - } + } - while (words != wlTarg) + while (words != wlTarg) words = words->wl_next; // hack - if (words) + if (words) words = words->wl_next; // skip targ - if (measure_parse_trigtarg(measTarg, words , NULL, "targ", errbuf)==0) { + if (measure_parse_trigtarg(measTarg, words , NULL, "targ", errbuf) == 0) { measure_errMessage(mName, mFunction, "TARG", errbuf, autocheck); return MEASUREMENT_FAILURE; - } + } - if ((measTarg->m_rise == -1) && (measTarg->m_fall == -1) && - (measTarg->m_cross == -1)&& (measTarg->m_at == 1e99)) { - sprintf(errbuf,"at, rise, fall or cross must be given\n"); + if ((measTarg->m_rise == -1) && (measTarg->m_fall == -1) && + (measTarg->m_cross == -1)&& (measTarg->m_at == 1e99)) { + sprintf(errbuf, "at, rise, fall or cross must be given\n"); measure_errMessage(mName, mFunction, "TARG", errbuf, autocheck); return MEASUREMENT_FAILURE; - } + } - // measure trig - if (measTrig->m_at == 1e99) + // measure trig + if (measTrig->m_at == 1e99) com_measure_when(measTrig); - else + else measTrig->m_measured = measTrig->m_at; - if (isnan(measTrig->m_measured)) { - sprintf(errbuf,"out of interval\n"); - measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); - return MEASUREMENT_FAILURE; - } - // measure targ - com_measure_when(measTarg); + if (isnan(measTrig->m_measured)) { + sprintf(errbuf, "out of interval\n"); + measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); + return MEASUREMENT_FAILURE; + } + // measure targ + com_measure_when(measTarg); - if (isnan(measTarg->m_measured)) { - sprintf(errbuf,"out of interval\n"); + if (isnan(measTarg->m_measured)) { + sprintf(errbuf, "out of interval\n"); measure_errMessage(mName, mFunction, "TARG", errbuf, autocheck); return MEASUREMENT_FAILURE; - } + } - // print results - if( out_line ){ - sprintf(out_line,"%-20s= %e targ= %e trig= %e\n", mName, (measTarg->m_measured - measTrig->m_measured), measTarg->m_measured, measTrig->m_measured); - } else { + // print results + if (out_line) + sprintf(out_line, "%-20s= %e targ= %e trig= %e\n", mName, (measTarg->m_measured - measTrig->m_measured), measTarg->m_measured, measTrig->m_measured); + else printf("%-20s= %e targ= %e trig= %e\n", mName, (measTarg->m_measured - measTrig->m_measured), measTarg->m_measured, measTrig->m_measured); - } - *result = (measTarg->m_measured - measTrig->m_measured); - return MEASUREMENT_OK; - } - case AT_FIND: - { - MEASUREPTR meas, measFind; - meas = TMALLOC(struct measure, 1); - measFind = TMALLOC(struct measure, 1); + *result = (measTarg->m_measured - measTrig->m_measured); + return MEASUREMENT_OK; + } + case AT_FIND: + { + MEASUREPTR meas, measFind; + meas = TMALLOC(struct measure, 1); + measFind = TMALLOC(struct measure, 1); - meas->m_analysis = measFind->m_analysis = mAnalysis; + meas->m_analysis = measFind->m_analysis = mAnalysis; - if (measure_parse_find(meas, words, wlWhen, errbuf) == 0) { + if (measure_parse_find(meas, words, wlWhen, errbuf) == 0) { measure_errMessage(mName, mFunction, "FIND", errbuf, autocheck); return MEASUREMENT_FAILURE; - } + } - if (meas->m_at == 1e99 ) { + if (meas->m_at == 1e99) { // find .. when statment while (words != wlWhen) - words = words->wl_next; // hack + words = words->wl_next; // hack if (words) - words = words->wl_next; // skip targ + words = words->wl_next; // skip targ - if (measure_parse_when(measFind, words, errbuf) ==0) { - measure_errMessage(mName, mFunction, "WHEN", errbuf, autocheck); - return MEASUREMENT_FAILURE; + if (measure_parse_when(measFind, words, errbuf) == 0) { + measure_errMessage(mName, mFunction, "WHEN", errbuf, autocheck); + return MEASUREMENT_FAILURE; } com_measure_when(measFind); if (isnan(measFind->m_measured)) { - sprintf(errbuf,"out of interval\n"); - measure_errMessage(mName, mFunction, "AT", errbuf, autocheck); - return MEASUREMENT_FAILURE; + sprintf(errbuf, "out of interval\n"); + measure_errMessage(mName, mFunction, "AT", errbuf, autocheck); + return MEASUREMENT_FAILURE; } measure_at(meas, measFind->m_measured); meas->m_at = measFind->m_measured; - } else { + } else { measure_at(meas, meas->m_at); - } + } - if (isnan(meas->m_measured)) { - sprintf(errbuf,"out of interval\n"); + if (isnan(meas->m_measured)) { + sprintf(errbuf, "out of interval\n"); measure_errMessage(mName, mFunction, "AT", errbuf, autocheck); return MEASUREMENT_FAILURE; - } + } - // print results - if( out_line ){ - sprintf(out_line,"%-20s= %e\n", mName, meas->m_measured); - } else { + // print results + if (out_line) + sprintf(out_line, "%-20s= %e\n", mName, meas->m_measured); + else printf("%-20s= %e\n", mName, meas->m_measured); - } - *result = meas->m_measured; - return MEASUREMENT_OK; - } - case AT_WHEN: - { - MEASUREPTR meas; - meas = TMALLOC(struct measure, 1); - meas->m_analysis = mAnalysis; - if (measure_parse_when(meas, words, errbuf) ==0) { + + *result = meas->m_measured; + return MEASUREMENT_OK; + } + case AT_WHEN: + { + MEASUREPTR meas; + meas = TMALLOC(struct measure, 1); + meas->m_analysis = mAnalysis; + if (measure_parse_when(meas, words, errbuf) == 0) { measure_errMessage(mName, mFunction, "WHEN", errbuf, autocheck); return MEASUREMENT_FAILURE; - } + } - com_measure_when(meas); + com_measure_when(meas); - if (isnan(meas->m_measured)) { - sprintf(errbuf,"out of interval\n"); + if (isnan(meas->m_measured)) { + sprintf(errbuf, "out of interval\n"); measure_errMessage(mName, mFunction, "WHEN", errbuf, autocheck); return MEASUREMENT_FAILURE; - } + } - // print results - if( out_line ){ - sprintf(out_line,"%-20s= %.*e\n", mName, precision, meas->m_measured); - } else { + // print results + if (out_line) + sprintf(out_line, "%-20s= %.*e\n", mName, precision, meas->m_measured); + else printf("%-20s= %e\n", mName, meas->m_measured); - } - *result = meas->m_measured; - return MEASUREMENT_OK; - } - case AT_RMS: - case AT_INTEG: - { - // trig parameters - MEASUREPTR meas; - meas = TMALLOC(struct measure, 1); - meas->m_analysis = mAnalysis; - if (measure_parse_trigtarg(meas, words , NULL, "trig", errbuf)==0) { - measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); - return MEASUREMENT_FAILURE; - } - - // measure - measure_rms_integral(meas,mFunctionType); - - if (isnan(meas->m_measured)) { - sprintf(errbuf,"out of interval\n"); - measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); // ?? - return MEASUREMENT_FAILURE; - } - - if (meas->m_at == 1e99) - meas->m_at = 0.0e0; - - // print results - if( out_line ){ - sprintf(out_line,"%-20s= %.*e from= %.*e to= %.*e\n", mName, precision, meas->m_measured, precision, meas->m_from, precision, meas->m_to); - } else { - printf("%-20s= %.*e from= %.*e to= %.*e\n", mName, precision, meas->m_measured, precision, meas->m_from, precision, meas->m_to); - } - *result=meas->m_measured; - return MEASUREMENT_OK; - - } - case AT_AVG: - { + *result = meas->m_measured; + return MEASUREMENT_OK; + } + case AT_RMS: + case AT_INTEG: + { // trig parameters - MEASUREPTR meas; - meas = TMALLOC(struct measure, 1); - - meas->m_analysis = mAnalysis; - - if (measure_parse_trigtarg(meas, words , NULL, "trig", errbuf)==0) { + MEASUREPTR meas; + meas = TMALLOC(struct measure, 1); + meas->m_analysis = mAnalysis; + if (measure_parse_trigtarg(meas, words , NULL, "trig", errbuf) == 0) { measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); return MEASUREMENT_FAILURE; - } + } - // measure - measure_minMaxAvg(meas, mFunctionType); - if (isnan(meas->m_measured)) { - sprintf(errbuf,"out of interval\n"); + // measure + measure_rms_integral(meas, mFunctionType); + + if (isnan(meas->m_measured)) { + sprintf(errbuf, "out of interval\n"); measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); // ?? return MEASUREMENT_FAILURE; - } + } - if (meas->m_at == 1e99) + if (meas->m_at == 1e99) + meas->m_at = 0.0e0; + + // print results + if (out_line) + sprintf(out_line, "%-20s= %.*e from= %.*e to= %.*e\n", mName, precision, meas->m_measured, precision, meas->m_from, precision, meas->m_to); + else + printf("%-20s= %.*e from= %.*e to= %.*e\n", mName, precision, meas->m_measured, precision, meas->m_from, precision, meas->m_to); + + *result = meas->m_measured; + return MEASUREMENT_OK; + + } + case AT_AVG: + { + // trig parameters + MEASUREPTR meas; + meas = TMALLOC(struct measure, 1); + + meas->m_analysis = mAnalysis; + + if (measure_parse_trigtarg(meas, words , NULL, "trig", errbuf) == 0) { + measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); + return MEASUREMENT_FAILURE; + } + + // measure + measure_minMaxAvg(meas, mFunctionType); + if (isnan(meas->m_measured)) { + sprintf(errbuf, "out of interval\n"); + measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); // ?? + return MEASUREMENT_FAILURE; + } + + if (meas->m_at == 1e99) meas->m_at = meas->m_from; - // print results - if( out_line ){ - sprintf(out_line,"%-20s= %e from= %e to= %e\n", mName, meas->m_measured, meas->m_at, meas->m_measured_at); - } else { - printf("%-20s= %e from= %e to= %e\n", mName, meas->m_measured, meas->m_at, meas->m_measured_at); - } - *result=meas->m_measured; - return MEASUREMENT_OK; + // print results + if (out_line) + sprintf(out_line, "%-20s= %e from= %e to= %e\n", mName, meas->m_measured, meas->m_at, meas->m_measured_at); + else + printf("%-20s= %e from= %e to= %e\n", mName, meas->m_measured, meas->m_at, meas->m_measured_at); - } - case AT_MIN: - case AT_MAX: - case AT_MIN_AT: - case AT_MAX_AT: - { - // trig parameters - MEASUREPTR measTrig; - measTrig = TMALLOC(struct measure, 1); - measTrig->m_analysis = mAnalysis; - if (measure_parse_trigtarg(measTrig, words , NULL, "trig", errbuf)==0) { + *result = meas->m_measured; + return MEASUREMENT_OK; + + } + case AT_MIN: + case AT_MAX: + case AT_MIN_AT: + case AT_MAX_AT: + { + // trig parameters + MEASUREPTR measTrig; + measTrig = TMALLOC(struct measure, 1); + measTrig->m_analysis = mAnalysis; + if (measure_parse_trigtarg(measTrig, words , NULL, "trig", errbuf) == 0) { measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); return MEASUREMENT_FAILURE; - } + } - // measure - if ((mFunctionType == AT_MIN) || (mFunctionType == AT_MIN_AT)) + // measure + if ((mFunctionType == AT_MIN) || (mFunctionType == AT_MIN_AT)) measure_minMaxAvg(measTrig, AT_MIN); - else + else measure_minMaxAvg(measTrig, AT_MAX); - if (isnan(measTrig->m_measured)) { - sprintf(errbuf,"out of interval\n"); + if (isnan(measTrig->m_measured)) { + sprintf(errbuf, "out of interval\n"); measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); // ?? return MEASUREMENT_FAILURE; - } + } - if ((mFunctionType == AT_MIN) || (mFunctionType == AT_MAX)) { + if ((mFunctionType == AT_MIN) || (mFunctionType == AT_MAX)) { // print results - if( out_line ){ - sprintf(out_line,"%-20s= %e at= %e\n", mName, measTrig->m_measured, measTrig->m_measured_at); - } else { - printf("%-20s= %e at= %e\n", mName, measTrig->m_measured, measTrig->m_measured_at); - } - *result=measTrig->m_measured; - } else { + if (out_line) + sprintf(out_line, "%-20s= %e at= %e\n", mName, measTrig->m_measured, measTrig->m_measured_at); + else + printf("%-20s= %e at= %e\n", mName, measTrig->m_measured, measTrig->m_measured_at); + + *result = measTrig->m_measured; + } else { // print results - if( out_line ){ - sprintf(out_line,"%-20s= %e with= %e\n", mName, measTrig->m_measured_at, measTrig->m_measured); - } else { - printf("%-20s= %e with= %e\n", mName, measTrig->m_measured_at, measTrig->m_measured); - } - *result=measTrig->m_measured_at; - } - return MEASUREMENT_OK; - } - case AT_PP: - { - double minValue, maxValue; - MEASUREPTR measTrig; - measTrig = TMALLOC(struct measure, 1); - measTrig->m_analysis = mAnalysis; - if (measure_parse_trigtarg(measTrig, words , NULL, "trig", errbuf)==0) { + if (out_line) + sprintf(out_line, "%-20s= %e with= %e\n", mName, measTrig->m_measured_at, measTrig->m_measured); + else + printf("%-20s= %e with= %e\n", mName, measTrig->m_measured_at, measTrig->m_measured); + + *result = measTrig->m_measured_at; + } + return MEASUREMENT_OK; + } + case AT_PP: + { + double minValue, maxValue; + MEASUREPTR measTrig; + measTrig = TMALLOC(struct measure, 1); + measTrig->m_analysis = mAnalysis; + if (measure_parse_trigtarg(measTrig, words , NULL, "trig", errbuf) == 0) { measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); return MEASUREMENT_FAILURE; - } + } - // measure min - measure_minMaxAvg(measTrig, AT_MIN); - if (isnan(measTrig->m_measured)) { - sprintf(errbuf,"out of interval\n"); + // measure min + measure_minMaxAvg(measTrig, AT_MIN); + if (isnan(measTrig->m_measured)) { + sprintf(errbuf, "out of interval\n"); measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); // ?? return MEASUREMENT_FAILURE; - } - minValue = measTrig->m_measured; + } + minValue = measTrig->m_measured; - // measure max - measure_minMaxAvg(measTrig, AT_MAX); - if (isnan(measTrig->m_measured)) { - sprintf(errbuf,"out of interval\n"); + // measure max + measure_minMaxAvg(measTrig, AT_MAX); + if (isnan(measTrig->m_measured)) { + sprintf(errbuf, "out of interval\n"); measure_errMessage(mName, mFunction, "TRIG", errbuf, autocheck); // ?? return MEASUREMENT_FAILURE; - } - maxValue = measTrig->m_measured; + } + maxValue = measTrig->m_measured; - // print results - if( out_line ){ - sprintf(out_line,"%-20s= %e from= %e to= %e\n", mName, (maxValue - minValue), measTrig->m_from, measTrig->m_to); - } else { + // print results + if (out_line) + sprintf(out_line, "%-20s= %e from= %e to= %e\n", mName, (maxValue - minValue), measTrig->m_from, measTrig->m_to); + else printf("%-20s= %e from= %e to= %e\n", mName, (maxValue - minValue), measTrig->m_from, measTrig->m_to); - } - *result = (maxValue - minValue); - return MEASUREMENT_OK; - } - - case AT_DERIV: - case AT_ERR: - case AT_ERR1: - case AT_ERR2: - case AT_ERR3: - { - printf("\tmeasure '%s' failed\n", mName); - printf("Error: measure %s :\n", mName); - printf("\tfunction '%s' currently not supported\n", mFunction); - break; - } - default: - { - fprintf(stderr, "ERROR: enumeration value `AT_UNKNOWN' not handled in get_measure2\nAborting...\n" ); - controlled_exit(EXIT_FAILURE); - } - } - return MEASUREMENT_FAILURE; + *result = (maxValue - minValue); + return MEASUREMENT_OK; + } + + case AT_DERIV: + case AT_ERR: + case AT_ERR1: + case AT_ERR2: + case AT_ERR3: + { + printf("\tmeasure '%s' failed\n", mName); + printf("Error: measure %s :\n", mName); + printf("\tfunction '%s' currently not supported\n", mFunction); + break; + } + + default: + { + fprintf(stderr, "ERROR: enumeration value `AT_UNKNOWN' not handled in get_measure2\nAborting...\n"); + controlled_exit(EXIT_FAILURE); + } + } + + return MEASUREMENT_FAILURE; } - diff --git a/src/frontend/com_measure2.h b/src/frontend/com_measure2.h index 1bc2de2af..7f32fd351 100644 --- a/src/frontend/com_measure2.h +++ b/src/frontend/com_measure2.h @@ -3,9 +3,9 @@ #include "ngspice/config.h" -extern int measure_get_precision(void) ; -extern int get_measure2(wordlist *wl,double *result,char *out_line, bool auto_check) ; -extern int measure_extract_variables( char *line ) ; +extern int measure_get_precision(void); +extern int get_measure2(wordlist *wl, double *result, char *out_line, bool auto_check); +extern int measure_extract_variables(char *line); void com_dotmeasure(wordlist *wl); diff --git a/src/frontend/com_option.c b/src/frontend/com_option.c index 69fde79bf..5988581ee 100644 --- a/src/frontend/com_option.c +++ b/src/frontend/com_option.c @@ -14,39 +14,37 @@ void com_option(wordlist *wl) { - -struct variable *vars; + struct variable *vars; CKTcircuit *circuit = NULL; if (!ft_curckt) { - fprintf(cp_err, "Error: no circuit loaded\n"); - return; + fprintf(cp_err, "Error: no circuit loaded\n"); + return; } circuit = (ft_curckt->ci_ckt); - if (wl == NULL) { printf("******************************\n"); printf("* Current simulation options *\n"); printf("******************************\n\n"); printf("Temperatures:\n"); - printf("temp = %f\n",circuit->CKTtemp); - printf("tnom = %f\n",circuit->CKTnomTemp); + printf("temp = %f\n", circuit->CKTtemp); + printf("tnom = %f\n", circuit->CKTnomTemp); printf("\nIntegration method summary:\n"); switch (circuit->CKTintegrateMethod) - { - case TRAPEZOIDAL: - printf("Integration Method = TRAPEZOIDAL\n"); - break; - case GEAR: - printf("Integration Method = GEAR\n"); - break; - default: - printf("Unknown integration method\n"); - } + { + case TRAPEZOIDAL: + printf("Integration Method = TRAPEZOIDAL\n"); + break; + case GEAR: + printf("Integration Method = GEAR\n"); + break; + default: + printf("Unknown integration method\n"); + } printf("MaxOrder = %d\n", circuit->CKTmaxOrder); printf("\nTolerances (absolute):\n"); @@ -87,28 +85,29 @@ struct variable *vars; return; } + vars = cp_setparse(wl); /* This is sort of a hassle... */ while (vars) { void *s; switch (vars->va_type) { - case CP_BOOL: + case CP_BOOL: s = &vars->va_bool; break; - case CP_NUM: + case CP_NUM: s = &vars->va_num; break; - case CP_REAL: + case CP_REAL: s = &vars->va_real; break; - case CP_STRING: + case CP_STRING: s = vars->va_string; break; - case CP_LIST: + case CP_LIST: s = vars->va_vlist; break; - default: + default: s = NULL; } diff --git a/src/frontend/com_set.c b/src/frontend/com_set.c index f30836f35..ca52492a4 100644 --- a/src/frontend/com_set.c +++ b/src/frontend/com_set.c @@ -23,38 +23,37 @@ com_set(wordlist *wl) vars = cp_setparse(wl); /* This is sort of a hassle... */ - while (vars) { + while (vars) { void *s; switch (vars->va_type) { - case CP_BOOL: + case CP_BOOL: s = &vars->va_bool; break; - case CP_NUM: + case CP_NUM: s = &vars->va_num; break; - case CP_REAL: + case CP_REAL: s = &vars->va_real; break; - case CP_STRING: + case CP_STRING: s = vars->va_string; break; - case CP_LIST: + case CP_LIST: s = vars->va_vlist; break; - default: - s = NULL; + default: + s = NULL; } cp_vset(vars->va_name, vars->va_type, s); - oldvar = vars; + oldvar = vars; vars = vars->va_next; - /* va: avoid memory leak: free oldvar carefully */ + /* va: avoid memory leak: free oldvar carefully */ tfree(oldvar->va_name); - if (oldvar->va_type==CP_STRING) + if (oldvar->va_type == CP_STRING) tfree(oldvar->va_string); /* copied in cp_vset */ /* don't free oldvar->va_list! This structure is used furthermore! */ tfree(oldvar); } - + return; } - diff --git a/src/frontend/com_setscale.c b/src/frontend/com_setscale.c index cc4b3fe52..fb0d00297 100644 --- a/src/frontend/com_setscale.c +++ b/src/frontend/com_setscale.c @@ -20,19 +20,20 @@ com_setscale(wordlist *wl) char *s; if (plot_cur) { - if (wl) { - s = cp_unquote(wl->wl_word); - d = vec_get(s); - if(s) tfree(s);/*DG to avoid the cp_unquote memory leak */ - if (d == NULL) - fprintf(cp_err, "Error: no such vector as %s.\n", - wl->wl_word); - else - plot_cur->pl_scale = d; - } else if (plot_cur->pl_scale) { - pvec(plot_cur->pl_scale); - } + if (wl) { + s = cp_unquote(wl->wl_word); + d = vec_get(s); + if (s) + tfree(s);/*DG to avoid the cp_unquote memory leak */ + + if (d == NULL) + fprintf(cp_err, "Error: no such vector as %s.\n", wl->wl_word); + else + plot_cur->pl_scale = d; + } else if (plot_cur->pl_scale) { + pvec(plot_cur->pl_scale); + } } else { - fprintf(cp_err, "Error: no current plot.\n"); + fprintf(cp_err, "Error: no current plot.\n"); } } diff --git a/src/frontend/com_shell.c b/src/frontend/com_shell.c index 4198f82cc..98fc7d38f 100644 --- a/src/frontend/com_shell.c +++ b/src/frontend/com_shell.c @@ -10,6 +10,7 @@ #include "streams.h" #include "ngspice/cpextern.h" + /* Fork a shell. */ void @@ -21,44 +22,44 @@ com_shell(wordlist *wl) if (shell == NULL) shell = "/bin/csh"; - cp_ccon(FALSE); + cp_ccon(FALSE); #ifdef HAVE_VFORK_H - /* XXX Needs to switch process groups. Also, worry about suspend */ - /* Only bother for efficiency */ - pid = vfork(); - if (pid == 0) { - fixdescriptors(); - if (wl == NULL) { - execl(shell, shell, 0); - _exit(99); - } else { - com = wl_flatten(wl); - execl("/bin/sh", "sh", "-c", com, 0); - } + /* XXX Needs to switch process groups. Also, worry about suspend */ + /* Only bother for efficiency */ + pid = vfork(); + if (pid == 0) { + fixdescriptors(); + if (wl == NULL) { + execl(shell, shell, 0); + _exit(99); } else { - /* XXX Better have all these signals */ - svint = signal(SIGINT, SIG_DFL); - svquit = signal(SIGQUIT, SIG_DFL); - svtstp = signal(SIGTSTP, SIG_DFL); - /* XXX Sig on proc group */ - do { - r = wait(NULL); - } while ((r != pid) && pid != -1); - signal(SIGINT, (SIGNAL_FUNCTION) svint); - signal(SIGQUIT, (SIGNAL_FUNCTION) svquit); - signal(SIGTSTP, (SIGNAL_FUNCTION) svtstp); + com = wl_flatten(wl); + execl("/bin/sh", "sh", "-c", com, 0); } + } else { + /* XXX Better have all these signals */ + svint = signal(SIGINT, SIG_DFL); + svquit = signal(SIGQUIT, SIG_DFL); + svtstp = signal(SIGTSTP, SIG_DFL); + /* XXX Sig on proc group */ + do + r = wait(NULL); + while ((r != pid) && pid != -1); + signal(SIGINT, (SIGNAL_FUNCTION) svint); + signal(SIGQUIT, (SIGNAL_FUNCTION) svquit); + signal(SIGTSTP, (SIGNAL_FUNCTION) svtstp); + } #else /* Easier to forget about changing the io descriptors. */ if (wl) { com = wl_flatten(wl); system(com); tfree(com); - } else + } else { system(shell); + } #endif return; } - diff --git a/src/frontend/com_sysinfo.c b/src/frontend/com_sysinfo.c index 69785a4c8..84bc8d81b 100644 --- a/src/frontend/com_sysinfo.c +++ b/src/frontend/com_sysinfo.c @@ -1,14 +1,14 @@ /* Provide system information - + LINUX: /proc file system Windows: GlobalMemoryStatusEx, GetSystemInfo, GetVersionExA, RegQueryValueExA Authors: Holger Vogt, Hendrik Vogt - + */ - + #include "ngspice/config.h" -#include "ngspice/ngspice.h" +#include "ngspice/ngspice.h" #include "ngspice/cpdefs.h" #include "ngspice/fteext.h" #include "com_commands.h" @@ -21,7 +21,7 @@ #ifdef HAVE_WIN32 #define WIN32_LEAN_AND_MEAN - + #ifdef __MINGW32__ /* access to GlobalMemoryStatusEx in winbase.h:1558 */ #define WINVER 0x0500 #endif @@ -45,429 +45,436 @@ /* system info */ typedef struct TSI { - char* cpuModelName; - unsigned numPhysicalProcessors; - unsigned numLogicalProcessors; - char* osName; + char *cpuModelName; + unsigned numPhysicalProcessors; + unsigned numLogicalProcessors; + char *osName; } TesSystemInfo; /* memory info */ struct sys_memory { - unsigned long long size_m; /* Total memory size */ - unsigned long long free_m; /* Free memory */ - unsigned long long swap_t; /* Swap total */ - unsigned long long swap_f; /* Swap free */ + unsigned long long size_m; /* Total memory size */ + unsigned long long free_m; /* Free memory */ + unsigned long long swap_t; /* Swap total */ + unsigned long long swap_f; /* Swap free */ }; -static struct sys_memory mem_t_act; +static struct sys_memory mem_t_act; TesError tesCreateSystemInfo(TesSystemInfo *info); static int get_sysmem(struct sys_memory *memall); + /* Print to stream the given memory size in a human friendly format */ static void -fprintmem(FILE* stream, unsigned long long memory) { +fprintmem(FILE *stream, unsigned long long memory) +{ if (memory > 1048576) - fprintf(stream, "%8.6f MB", (double)memory /1048576.); + fprintf(stream, "%8.6f MB", (double)memory /1048576.); else if (memory > 1024) - fprintf(stream, "%5.3f kB", (double)memory / 1024.); + fprintf(stream, "%5.3f kB", (double)memory / 1024.); else - fprintf(stream, "%u bytes", (unsigned)memory); + fprintf(stream, "%u bytes", (unsigned)memory); } -static void tesFreeSystemInfo(TesSystemInfo *info) { - if(info != NULL) { - free(info->cpuModelName); - free(info->osName); - } +static void +tesFreeSystemInfo(TesSystemInfo *info) +{ + if (info != NULL) { + free(info->cpuModelName); + free(info->osName); + } } + /* print system info */ -void com_sysinfo(wordlist *wl) +void +com_sysinfo(wordlist *wl) { - int errorcode; - TesSystemInfo* info; + int errorcode; + TesSystemInfo *info; - NG_IGNORE(wl); + NG_IGNORE(wl); - info = TMALLOC(TesSystemInfo, 1); + info = TMALLOC(TesSystemInfo, 1); - errorcode = tesCreateSystemInfo(info); - if (errorcode) - fprintf(cp_err, "No system info available! \n"); - else { - fprintf(cp_out, "\nOS: %s\n", info->osName); - fprintf(cp_out, "CPU: %s\n", info->cpuModelName); - if (info->numPhysicalProcessors > 0) - fprintf(cp_out, "Physical processors: %u, ", info->numPhysicalProcessors); - fprintf(cp_out, "Logical processors: %u\n", - info->numLogicalProcessors); - } -#if defined(HAVE_WIN32) || defined(HAVE__PROC_MEMINFO) - - get_sysmem(&mem_t_act); - - /* get_sysmem returns bytes */ - fprintf(cp_out, "Total DRAM available = "); - fprintmem(cp_out, mem_t_act.size_m); - fprintf(cp_out, ".\n"); - - fprintf(cp_out, "DRAM currently available = "); - fprintmem(cp_out, mem_t_act.free_m); - fprintf(cp_out, ".\n\n"); + errorcode = tesCreateSystemInfo(info); + if (errorcode) { + fprintf(cp_err, "No system info available! \n"); + } else { + fprintf(cp_out, "\nOS: %s\n", info->osName); + fprintf(cp_out, "CPU: %s\n", info->cpuModelName); + if (info->numPhysicalProcessors > 0) + fprintf(cp_out, "Physical processors: %u, ", info->numPhysicalProcessors); + fprintf(cp_out, "Logical processors: %u\n", + info->numLogicalProcessors); + } +#if defined(HAVE_WIN32) || defined(HAVE__PROC_MEMINFO) + + get_sysmem(&mem_t_act); + + /* get_sysmem returns bytes */ + fprintf(cp_out, "Total DRAM available = "); + fprintmem(cp_out, mem_t_act.size_m); + fprintf(cp_out, ".\n"); + + fprintf(cp_out, "DRAM currently available = "); + fprintmem(cp_out, mem_t_act.free_m); + fprintf(cp_out, ".\n\n"); #endif - tesFreeSystemInfo(info); - tfree(info); + tesFreeSystemInfo(info); + tfree(info); } -#ifdef HAVE__PROC_MEMINFO +#ifdef HAVE__PROC_MEMINFO /* Get memory information */ -static int get_sysmem(struct sys_memory *memall) { - FILE *fp; - char buffer[2048]; - size_t bytes_read; - char *match; - unsigned long mem_got; +static int +get_sysmem(struct sys_memory *memall) +{ + FILE *fp; + char buffer[2048]; + size_t bytes_read; + char *match; + unsigned long mem_got; - if((fp = fopen("/proc/meminfo", "r")) == NULL) { - perror("fopen(\"/proc/meminfo\")"); - return 0; - } - - bytes_read = fread (buffer, 1, sizeof (buffer), fp); - fclose (fp); - if (bytes_read == 0 || bytes_read == sizeof (buffer)) - return 0; - buffer[bytes_read] = '\0'; + if ((fp = fopen("/proc/meminfo", "r")) == NULL) { + perror("fopen(\"/proc/meminfo\")"); + return 0; + } - /* Search for string "MemTotal" */ - match = strstr (buffer, "MemTotal"); - if (match == NULL) /* not found */ - return 0; - sscanf (match, "MemTotal: %ld", &mem_got); - memall->size_m = mem_got*1024; /* 1MB = 1024KB */ - /* Search for string "MemFree" */ - match = strstr (buffer, "MemFree"); - if (match == NULL) /* not found */ - return 0; - sscanf (match, "MemFree: %ld", &mem_got); - memall->free_m = mem_got*1024; /* 1MB = 1024KB */ - /* Search for string "SwapTotal" */ - match = strstr (buffer, "SwapTotal"); - if (match == NULL) /* not found */ - return 0; - sscanf (match, "SwapTotal: %ld", &mem_got); - memall->swap_t = mem_got*1024; /* 1MB = 1024KB */ - /* Search for string "SwapFree" */ - match = strstr (buffer, "SwapFree"); - if (match == NULL) /* not found */ - return 0; - sscanf (match, "SwapFree: %ld", &mem_got); - memall->swap_f = mem_got*1024; /* 1MB = 1024KB */ - return 1; + bytes_read = fread(buffer, 1, sizeof(buffer), fp); + fclose(fp); + if (bytes_read == 0 || bytes_read == sizeof(buffer)) + return 0; + buffer[bytes_read] = '\0'; + + /* Search for string "MemTotal" */ + match = strstr(buffer, "MemTotal"); + if (match == NULL) /* not found */ + return 0; + sscanf(match, "MemTotal: %ld", &mem_got); + memall->size_m = mem_got*1024; /* 1MB = 1024KB */ + /* Search for string "MemFree" */ + match = strstr(buffer, "MemFree"); + if (match == NULL) /* not found */ + return 0; + sscanf(match, "MemFree: %ld", &mem_got); + memall->free_m = mem_got*1024; /* 1MB = 1024KB */ + /* Search for string "SwapTotal" */ + match = strstr(buffer, "SwapTotal"); + if (match == NULL) /* not found */ + return 0; + sscanf(match, "SwapTotal: %ld", &mem_got); + memall->swap_t = mem_got*1024; /* 1MB = 1024KB */ + /* Search for string "SwapFree" */ + match = strstr(buffer, "SwapFree"); + if (match == NULL) /* not found */ + return 0; + sscanf(match, "SwapFree: %ld", &mem_got); + memall->swap_f = mem_got*1024; /* 1MB = 1024KB */ + return 1; } - /* Return length of first line in a string */ -static size_t getLineLength(const char *str) { - const char *p = str; +static size_t +getLineLength(const char *str) +{ + const char *p = str; - while(*p && (*p != '\n')) - p++; + while (*p && (*p != '\n')) + p++; - return (size_t) (p - str); + return (size_t) (p - str); } + /* Checks if number 'match' is found in a vector 'set' of size 'size' Returns 1 if yes, otherwise, 0 */ -static tInt searchInSet(const tInt *set, unsigned size, tInt match) { - unsigned index; - for(index = 0; index < size; index++) { - if(match == set[index]) { - return 1; - } - } - return 0; +static tInt +searchInSet(const tInt *set, unsigned size, tInt match) +{ + unsigned index; + for (index = 0; index < size; index++) + if (match == set[index]) + return 1; + return 0; } + /* Get system information */ -TesError tesCreateSystemInfo(TesSystemInfo *info) { - FILE *file; - TesError error = TES_SUCCESS; - - if(info == NULL) - return TES_INVALID_PARAMS; - info->cpuModelName = NULL; - info->osName = NULL; - info->numLogicalProcessors = info->numPhysicalProcessors = 0; - - /* get kernel version string */ - file = fopen("/proc/version", "rb"); - if(file != NULL) { - size_t size; - - /* read bytes and find end of file */ - for(size=0; ; size++) - if(EOF == fgetc(file)) - break; +TesError +tesCreateSystemInfo(TesSystemInfo *info) +{ + FILE *file; + TesError error = TES_SUCCESS; - info->osName = TMALLOC(char, size); - rewind(file); - fread(info->osName, sizeof(char), size, file); - fclose(file); - - info->osName[size-1] = '\0'; - } - else { - error = TES_FAIL; - } - - /* get cpu information */ - file = fopen("/proc/cpuinfo", "rb"); - if(file != NULL) { - size_t size; - char *inStr; - - /* read bytes and find end of file */ - for(size=0; ; size++) - if(EOF == fgetc(file)) - break; + if (info == NULL) + return TES_INVALID_PARAMS; + info->cpuModelName = NULL; + info->osName = NULL; + info->numLogicalProcessors = info->numPhysicalProcessors = 0; - /* get complete string */ - inStr = TMALLOC(char, size+1); - rewind(file); - fread(inStr, sizeof(char), size, file); - inStr[size] = '\0'; - - { - const char *matchStr = "model name"; - /* pointer to first occurrence of model name*/ - const char *modelStr = strstr(inStr, matchStr); - if(modelStr != NULL) { - /* search for ':' */ - const char *modelPtr = strchr(modelStr, ':'); - if(modelPtr != NULL) { - /*length of string from ':' till end of line */ - size_t numToEOL = getLineLength(modelPtr); - if(numToEOL > 2) { - /* skip ": "*/ - numToEOL-=2; - info->cpuModelName = TMALLOC(char, numToEOL+1); - memcpy(info->cpuModelName, modelPtr+2, numToEOL); - info->cpuModelName[numToEOL] = '\0'; - } - } - else { - error = TES_FAIL; - } - } - else { - error = TES_FAIL; - } - } - { - const char *matchStrProc = "processor"; - const char *matchStrPhys = "physical id"; - char *strPtr = inStr; - unsigned numProcs = 0; - tInt *physIDs; - - /* get number of logical processors */ - while((strPtr = strstr(strPtr, matchStrProc)) != NULL) { -// numProcs++; - strPtr += strlen(matchStrProc); - if (isblank(*strPtr)) numProcs++; - } - info->numLogicalProcessors = numProcs; - physIDs = TMALLOC(tInt, numProcs); - - /* get number of physical CPUs */ - numProcs = 0; - strPtr = inStr; - while((strPtr = strstr(strPtr, matchStrProc)) != NULL) { - - /* search for first occurrence of physical id */ - strPtr = strstr(strPtr, matchStrPhys); - if(strPtr != NULL) { - /* go to ';' */ - strPtr = strchr(strPtr, ':'); - if(strPtr != NULL) { - tInt buffer = 0; - /* skip ": " */ - strPtr += 2; - /* get number */ - sscanf(strPtr, "%d", &buffer); - /* If this physical id is unique, - we have another physically available CPU */ - if(searchInSet(physIDs, numProcs, buffer) == 0) { - physIDs[numProcs] = buffer; - numProcs++; - } - } - else { -// error = TES_FAIL; - break; - } - } - else { -// error = TES_FAIL; - break; - } - } - info->numPhysicalProcessors = numProcs; - free(physIDs); - } + /* get kernel version string */ + file = fopen("/proc/version", "rb"); + if (file != NULL) { + size_t size; - /* another test to get number of logical processors - if (info->numLogicalProcessors == 0) { - char* token; - char* cpustr = copy(inStr); - while ((cpustr) && !*cpustr) - if (cieq(gettok(&cpustr), "processor")) { - gettok(&cpustr); - token = gettok(&cpustr); + /* read bytes and find end of file */ + for (size = 0; ; size++) + if (EOF == fgetc(file)) + break; + + info->osName = TMALLOC(char, size); + rewind(file); + fread(info->osName, sizeof(char), size, file); + fclose(file); + + info->osName[size-1] = '\0'; + } else { + error = TES_FAIL; + } + + /* get cpu information */ + file = fopen("/proc/cpuinfo", "rb"); + if (file != NULL) { + size_t size; + char *inStr; + + /* read bytes and find end of file */ + for (size = 0; ; size++) + if (EOF == fgetc(file)) + break; + + /* get complete string */ + inStr = TMALLOC(char, size+1); + rewind(file); + fread(inStr, sizeof(char), size, file); + inStr[size] = '\0'; + + { + const char *matchStr = "model name"; + /* pointer to first occurrence of model name*/ + const char *modelStr = strstr(inStr, matchStr); + if (modelStr != NULL) { + /* search for ':' */ + const char *modelPtr = strchr(modelStr, ':'); + if (modelPtr != NULL) { + /*length of string from ':' till end of line */ + size_t numToEOL = getLineLength(modelPtr); + if (numToEOL > 2) { + /* skip ": "*/ + numToEOL -= 2; + info->cpuModelName = TMALLOC(char, numToEOL+1); + memcpy(info->cpuModelName, modelPtr+2, numToEOL); + info->cpuModelName[numToEOL] = '\0'; + } + } else { + error = TES_FAIL; + } + } else { + error = TES_FAIL; } - - info->numLogicalProcessors = atoi(token) + 1; - tfree(cpustr); - }*/ - - free(inStr); - fclose(file); - } - else { - error = TES_FAIL; - } + } + { + const char *matchStrProc = "processor"; + const char *matchStrPhys = "physical id"; + char *strPtr = inStr; + unsigned numProcs = 0; + tInt *physIDs; - return error; + /* get number of logical processors */ + while ((strPtr = strstr(strPtr, matchStrProc)) != NULL) { + // numProcs++; + strPtr += strlen(matchStrProc); + if (isblank(*strPtr)) numProcs++; + } + info->numLogicalProcessors = numProcs; + physIDs = TMALLOC(tInt, numProcs); + + /* get number of physical CPUs */ + numProcs = 0; + strPtr = inStr; + while ((strPtr = strstr(strPtr, matchStrProc)) != NULL) { + + /* search for first occurrence of physical id */ + strPtr = strstr(strPtr, matchStrPhys); + if (strPtr != NULL) { + /* go to ';' */ + strPtr = strchr(strPtr, ':'); + if (strPtr != NULL) { + tInt buffer = 0; + /* skip ": " */ + strPtr += 2; + /* get number */ + sscanf(strPtr, "%d", &buffer); + /* If this physical id is unique, + we have another physically available CPU */ + if (searchInSet(physIDs, numProcs, buffer) == 0) { + physIDs[numProcs] = buffer; + numProcs++; + } + } else { + // error = TES_FAIL; + break; + } + } else { + // error = TES_FAIL; + break; + } + } + info->numPhysicalProcessors = numProcs; + free(physIDs); + } + + /* another test to get number of logical processors + * if (info->numLogicalProcessors == 0) { + * char *token; + * char *cpustr = copy(inStr); + * while ((cpustr) && !*cpustr) + * if (cieq(gettok(&cpustr), "processor")) { + * gettok(&cpustr); + * token = gettok(&cpustr); + * } + * + * info->numLogicalProcessors = atoi(token) + 1; + * tfree(cpustr); + * } + */ + + free(inStr); + fclose(file); + } else { + error = TES_FAIL; + } + + return error; } #elif defined(HAVE_WIN32) /* get memory information */ -static int get_sysmem(struct sys_memory *memall) { -#if ( _WIN32_WINNT >= 0x0500) - MEMORYSTATUSEX ms; - ms.dwLength = sizeof(MEMORYSTATUSEX); - GlobalMemoryStatusEx( &ms); - memall->size_m = ms.ullTotalPhys; - memall->free_m = ms.ullAvailPhys; - memall->swap_t = ms.ullTotalPageFile; - memall->swap_f = ms.ullAvailPageFile; +static int +get_sysmem(struct sys_memory *memall) +{ +#if (_WIN32_WINNT >= 0x0500) + MEMORYSTATUSEX ms; + ms.dwLength = sizeof(MEMORYSTATUSEX); + GlobalMemoryStatusEx(&ms); + memall->size_m = ms.ullTotalPhys; + memall->free_m = ms.ullAvailPhys; + memall->swap_t = ms.ullTotalPageFile; + memall->swap_f = ms.ullAvailPageFile; #else - MEMORYSTATUS ms; - ms.dwLength = sizeof(MEMORYSTATUS); - GlobalMemoryStatus( &ms); - memall->size_m = ms.dwTotalPhys; - memall->free_m = ms.dwAvailPhys; - memall->swap_t = ms.dwTotalPageFile; - memall->swap_f = ms.dwAvailPageFile; -#endif /*_WIN32_WINNT 0x0500*/ - return 1; + MEMORYSTATUS ms; + ms.dwLength = sizeof(MEMORYSTATUS); + GlobalMemoryStatus(&ms); + memall->size_m = ms.dwTotalPhys; + memall->free_m = ms.dwAvailPhys; + memall->swap_t = ms.dwTotalPageFile; + memall->swap_f = ms.dwAvailPageFile; +#endif + return 1; } + /* get system information */ -TesError tesCreateSystemInfo(TesSystemInfo *info) { - OSVERSIONINFOA version; - char *versionStr = NULL, *procStr, *freeStr; - DWORD major, minor; - DWORD dwLen; - HKEY hkBaseCPU; - LONG lResult; +TesError +tesCreateSystemInfo(TesSystemInfo *info) +{ + OSVERSIONINFOA version; + char *versionStr = NULL, *procStr, *freeStr; + DWORD major, minor; + DWORD dwLen; + HKEY hkBaseCPU; + LONG lResult; SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); + info->numPhysicalProcessors = 0; + info->numLogicalProcessors = sysinfo.dwNumberOfProcessors; //atoi(getenv("NUMBER_OF_PROCESSORS")); + info->osName = NULL; - info->numPhysicalProcessors = 0; - info->numLogicalProcessors = sysinfo.dwNumberOfProcessors; //atoi(getenv("NUMBER_OF_PROCESSORS")); - info->osName = NULL; + version.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA); + if (GetVersionExA(&version) == 0) + return TES_FAIL; - version.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA); - if(GetVersionExA(&version) == 0) { - return TES_FAIL; - } - major = version.dwMajorVersion; - minor = version.dwMinorVersion; - switch(major) { - case 4: - if(minor == 0) { - versionStr = "Windows 95/NT4.0"; - } - else if(minor == 10) { - versionStr = "Windows 98"; - } - else if (minor == 90) { - versionStr = "Windows ME"; - } - break; - case 5: - if(minor == 0) { - versionStr = "Windows 2000"; - } - else if(minor == 1) { - versionStr = "Windows XP"; - } - else if(minor == 2) { - versionStr = "Windows Server 2003"; - } - break; - case 6: - if(minor == 0) { - versionStr = "Windows Vista"; - } - else if(minor == 1) { - versionStr = "Windows 7"; - } - break; - default: - break; - } + major = version.dwMajorVersion; + minor = version.dwMinorVersion; + switch (major) { + case 4: + if (minor == 0) + versionStr = "Windows 95/NT4.0"; + else if (minor == 10) + versionStr = "Windows 98"; + else if (minor == 90) + versionStr = "Windows ME"; + break; + case 5: + if (minor == 0) + versionStr = "Windows 2000"; + else if (minor == 1) + versionStr = "Windows XP"; + else if (minor == 2) + versionStr = "Windows Server 2003"; + break; + case 6: + if (minor == 0) + versionStr = "Windows Vista"; + else if (minor == 1) + versionStr = "Windows 7"; + break; + default: + break; + } - if(versionStr != NULL) { - size_t lengthCSD = strlen(version.szCSDVersion); - size_t lengthVer = strlen(versionStr); + if (versionStr != NULL) { + size_t lengthCSD = strlen(version.szCSDVersion); + size_t lengthVer = strlen(versionStr); - info->osName = TMALLOC(char, lengthVer + lengthCSD + 2); - memcpy(info->osName, versionStr, lengthVer); - memcpy(info->osName + lengthVer + 1, version.szCSDVersion, lengthCSD); - info->osName[lengthVer] = ' '; - info->osName[lengthVer + lengthCSD + 1] = '\0'; - } + info->osName = TMALLOC(char, lengthVer + lengthCSD + 2); + memcpy(info->osName, versionStr, lengthVer); + memcpy(info->osName + lengthVer + 1, version.szCSDVersion, lengthCSD); + info->osName[lengthVer] = ' '; + info->osName[lengthVer + lengthCSD + 1] = '\0'; + } lResult = RegOpenKeyExA(HKEY_LOCAL_MACHINE, - "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", - 0,KEY_READ,&hkBaseCPU); - if(lResult != ERROR_SUCCESS) { - info->cpuModelName = NULL; - return TES_FAIL; + "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", + 0, KEY_READ, &hkBaseCPU); + if (lResult != ERROR_SUCCESS) { + info->cpuModelName = NULL; + return TES_FAIL; } - RegQueryValueExA(hkBaseCPU,"ProcessorNameString",0,0,NULL,&dwLen); + RegQueryValueExA(hkBaseCPU, "ProcessorNameString", 0, 0, NULL, &dwLen); freeStr = procStr = TMALLOC(char, dwLen + 1); - RegQueryValueExA(hkBaseCPU,"ProcessorNameString",0,0,(LPBYTE)procStr,&dwLen); + RegQueryValueExA(hkBaseCPU, "ProcessorNameString", 0, 0, (LPBYTE)procStr, &dwLen); procStr[dwLen] = '\0'; - while (*procStr == ' ') procStr++; + while (*procStr == ' ') + procStr++; info->cpuModelName = copy(procStr); tfree(freeStr); - RegCloseKey(hkBaseCPU); + RegCloseKey(hkBaseCPU); - return TES_SUCCESS; + return TES_SUCCESS; } #else + /* no Windows OS, no proc info file system */ -TesError tesCreateSystemInfo(TesSystemInfo *info) { - return 1; +TesError +tesCreateSystemInfo(TesSystemInfo *info) +{ + return 1; } #endif - diff --git a/src/frontend/com_xgraph.c b/src/frontend/com_xgraph.c index 8bc3a087e..d52c97819 100644 --- a/src/frontend/com_xgraph.c +++ b/src/frontend/com_xgraph.c @@ -21,9 +21,10 @@ com_xgraph(wordlist *wl) fname = wl->wl_word; wl = wl->wl_next; } - if (!wl) { - return; - } + + if (!wl) + return; + if (cieq(fname, "temp") || cieq(fname, "tmp")) { fname = smktemp("xg"); tempf = TRUE; diff --git a/src/frontend/commands.c b/src/frontend/commands.c index e9fb37767..5c615b247 100644 --- a/src/frontend/commands.c +++ b/src/frontend/commands.c @@ -15,7 +15,7 @@ * uninterrupted or error-free. The end-user understands that the * program was developed for research purposes and is advised not to * rely exclusively on the program for any reason. - * + * * IN NO EVENT SHALL THE AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS @@ -97,7 +97,7 @@ #endif /* Information about spice commands (struct comm). */ - + // char *co_comname; /* The name of the command. */ // void (*co_func) (wordlist *wl); /* The function that handles the command. */ // bool co_spiceonly; /* These can't be used from nutmeg. */ @@ -121,7 +121,7 @@ struct comm spcp_coms[] = { { "define", com_define, FALSE, TRUE, { 010000, 040000, 040000, 040000 }, E_DEFHMASK, 0, LOTS, NULL, - "[[func (args)] stuff] : Define a user-definable function." } , + "[[func (args)] stuff] : Define a user-definable function." } , { "set", com_set, FALSE, TRUE, { 020000, 020000, 020000, 020000 }, E_DEFHMASK, 0, LOTS, arg_set, @@ -129,7 +129,7 @@ struct comm spcp_coms[] = { /* support for altering options in interactive mode, - using either command 'option' or 'options'*/ + using either command 'option' or 'options'*/ { "option", com_option, TRUE, TRUE, { 020000, 020000, 020000, 020000 }, E_DEFHMASK, 0, LOTS, arg_set, @@ -322,11 +322,11 @@ struct comm spcp_coms[] = { { "fft", com_fft, FALSE, TRUE, { 0, 0, 0, 0 }, E_DEFHMASK, 1, LOTS, NULL, - "vector ... : Create a frequency domain plot with FFT." } , + "vector ... : Create a frequency domain plot with FFT." } , { "psd", com_psd, FALSE, TRUE, { 0, 0, 0, 0 }, E_DEFHMASK, 2, LOTS, NULL, - "vector ... : Create a power spetral density plot with FFT." } , + "vector ... : Create a power spetral density plot with FFT." } , { "fourier", com_fourier, FALSE, TRUE, { 0, 040000, 040000, 040000 }, E_DEFHMASK, 1, LOTS, NULL, @@ -338,7 +338,7 @@ struct comm spcp_coms[] = { { "meas", com_meas, FALSE, TRUE, { 0, 0, 0, 0 }, E_DEFHMASK, 1, LOTS, NULL, - "various ... : User defined signal evaluation." } , + "various ... : User defined signal evaluation." } , { "show", com_show, TRUE, FALSE, { 040, 040, 040, 040 }, E_DEFHMASK, 0, LOTS, NULL, @@ -350,7 +350,7 @@ struct comm spcp_coms[] = { { "sysinfo", com_sysinfo, TRUE, FALSE, { 040, 040, 040, 040 }, E_DEFHMASK, 0, LOTS, NULL, - "Print out system info summary." } , + "Print out system info summary." } , { "alter", com_alter, TRUE, FALSE, { 040, 040, 040, 040 }, E_DEFHMASK, 0, LOTS, NULL, @@ -603,13 +603,13 @@ struct comm nutcp_coms[] = { "[option] [option = value] ... : Set a variable." } , #ifdef EXPERIMENTAL_CODE -/* PN support for altering options in interactive mode */ +/* PN support for altering options in interactive mode */ { "option", com_option, TRUE, TRUE, { 020000, 020000, 020000, 020000 }, E_DEFHMASK, 0, LOTS, arg_set, "[option] [option = value] ... : Set a simulator option." } , -#endif - +#endif + { "alias", com_alias, FALSE, FALSE, { 02, 04, 04, 04 }, E_ADVANCED, 0, LOTS, NULL, @@ -753,11 +753,11 @@ struct comm nutcp_coms[] = { { "fft", com_fft, FALSE, TRUE, { 0, 0, 0, 0 }, E_DEFHMASK, 1, LOTS, NULL, - "vector ... : Create a frequency domain plot with FFT." } , + "vector ... : Create a frequency domain plot with FFT." } , { "psd", com_psd, FALSE, TRUE, { 0, 0, 0, 0 }, E_DEFHMASK, 2, LOTS, NULL, - "vector ... : Create a power spetral density plot with FFT." } , + "vector ... : Create a power spetral density plot with FFT." } , { "fourier", com_fourier, FALSE, TRUE, { 0, 040000, 040000, 040000 }, E_DEFHMASK, 1, LOTS, NULL, @@ -959,7 +959,7 @@ struct comm nutcp_coms[] = { { 040000, 040000, 040000, 040000 }, E_DEFHMASK, 0, LOTS, NULL, " [ vec ... ] : Convert plot into one with linear scale." } , - { "devhelp",NULL, FALSE, FALSE, + { "devhelp", NULL, FALSE, FALSE, { 040, 040, 040, 040 }, E_DEFHMASK, 0, 5 , NULL, " devspecs : show device information." }, @@ -971,4 +971,4 @@ struct comm nutcp_coms[] = { { 0, 0, 0, 0 }, E_DEFHMASK, 0, LOTS, NULL, NULL } -} ; +}; diff --git a/src/frontend/control.c b/src/frontend/control.c index 3b181a659..f5eeb46c2 100644 --- a/src/frontend/control.c +++ b/src/frontend/control.c @@ -49,19 +49,20 @@ int stackp = 0; * input is ok though -- use ft_controlreset. */ /* Notes by CDHW: -* This routine leaked like a sieve because each getcommand() created a -* wordlist that was never freed because it might have been added into -* the control structure. I've tackled this by making sure that everything -* put into the cend[stackp] is a copy. This means that wlist can be -* destroyed safely -*/ + * This routine leaked like a sieve because each getcommand() created a + * wordlist that was never freed because it might have been added into + * the control structure. I've tackled this by making sure that everything + * put into the cend[stackp] is a copy. This means that wlist can be + * destroyed safely + */ /* no redirection after the following commands (we may need more to add here!) */ -static char *noredirect[] = { "stop", "define", NULL } ; +static char *noredirect[] = { "stop", "define", NULL }; static struct control * -findlabel(char *s, struct control *ct) { +findlabel(char *s, struct control *ct) +{ while (ct) { if ((ct->co_type == CO_LABEL) && eq(s, ct->co_text->wl_word)) break; @@ -103,11 +104,14 @@ pwlist_echo(wordlist *wlist, char *name) /*CDHW used to perform function of se return; } + /*CDHW Remove control structure and free the memory its hogging CDHW*/ -static void ctl_free(struct control *ctrl) +static void +ctl_free(struct control *ctrl) { - if (!ctrl) return; + if (!ctrl) + return; wl_free(ctrl->co_cond); ctrl->co_cond = NULL; tfree(ctrl->co_foreachvar); @@ -180,12 +184,11 @@ docommand(wordlist *wlist) for (i = 0; noredirect[i]; i++) if (eq(wlist->wl_word, noredirect[i])) break; - if (!noredirect[i]) { + if (!noredirect[i]) if ((wlist = cp_redirect(wlist)) == NULL) { cp_ioreset(); return; } - } /* Get rid of all the 8th bits now... */ cp_striplist(wlist); @@ -207,17 +210,17 @@ docommand(wordlist *wlist) if (!command->co_comname) { if (cp_dounixcom && cp_unixcom(wlist)) goto out; - fprintf(cp_err,"%s: no such command available in %s\n", + fprintf(cp_err, "%s: no such command available in %s\n", s, cp_program); goto out; /* If it hasn't been implemented */ } else if (!command->co_func) { - fprintf(cp_err,"%s: command is not implemented\n", s); + fprintf(cp_err, "%s: command is not implemented\n", s); goto out; /* If it's there but spiceonly, and this is nutmeg, error. */ } else if (ft_nutmeg && command->co_spiceonly) { - fprintf(cp_err,"%s: command available only in spice\n", s); + fprintf(cp_err, "%s: command available only in spice\n", s); goto out; } @@ -237,11 +240,11 @@ docommand(wordlist *wlist) } } -out: + out: wl_append(ee, wlist); wl_append(wlist, nextc); - if(!ee) + if (!ee) rwlist = wlist; wlist = nextc; @@ -279,7 +282,7 @@ doblock(struct control *bl, int *num) char *i; int nn; - nn = *num + 1 ; /*CDHW this is a guess... CDHW*/ + nn = *num + 1; /*CDHW this is a guess... CDHW*/ switch (bl->co_type) { case CO_WHILE: @@ -298,9 +301,9 @@ doblock(struct control *bl, int *num) break; case BROKEN: /* Break. */ - if (nn < 2) + if (nn < 2) { return (NORMAL_STR); - else { + } else { *num = nn - 1; return (BROKEN_STR); } @@ -334,9 +337,9 @@ doblock(struct control *bl, int *num) break; case BROKEN: /* Break. */ - if (nn < 2) + if (nn < 2) { return (NORMAL_STR); - else { + } else { *num = nn - 1; return (BROKEN_STR); } @@ -369,7 +372,7 @@ doblock(struct control *bl, int *num) bl->co_numtimes = -1: repeat forever bl->co_timestodo: remaining repeats*/ while ((bl->co_timestodo > 0) || - (bl->co_timestodo == -1)) { + (bl->co_timestodo == -1)) { if (!bl->co_children) cp_periodic(); /*CDHW*/ if (bl->co_timestodo != -1) bl->co_timestodo--; /* loop through all stements inside rpeat ... end */ @@ -384,9 +387,9 @@ doblock(struct control *bl, int *num) case BROKEN: /* Break. */ /* before leaving repeat loop set remaining timestodo to 0 */ bl->co_timestodo = 0; - if (nn < 2) + if (nn < 2) { return (NORMAL_STR); - else { + } else { *num = nn - 1; return (BROKEN_STR); } @@ -436,8 +439,7 @@ doblock(struct control *bl, int *num) cn = ch->co_next; i = doblock(ch, &nn); if (*i > 2) { - cn = findlabel(i, - bl->co_elseblock); + cn = findlabel(i, bl->co_elseblock); if (!cn) return (i); } else if (*i != NORMAL) { @@ -450,8 +452,8 @@ doblock(struct control *bl, int *num) case CO_FOREACH: for (wl = cp_variablesubst(cp_bquote(cp_doglob(wl_copy(bl->co_text)))); - wl; - wl = wl->wl_next) { + wl; + wl = wl->wl_next) { cp_vset(bl->co_foreachvar, CP_STRING, wl->wl_word); for (ch = bl->co_children; ch; ch = cn) { cn = ch->co_next; @@ -462,9 +464,9 @@ doblock(struct control *bl, int *num) break; case BROKEN: /* Break. */ - if (nn < 2) + if (nn < 2) { return (NORMAL_STR); - else { + } else { *num = nn - 1; return (BROKEN_STR); } @@ -535,8 +537,9 @@ doblock(struct control *bl, int *num) return (NORMAL_STR); } + /* Maxiumum number of cheverons used for the alternative prompt */ -#define MAX_CHEVRONS 16 +#define MAX_CHEVRONS 16 /* Get the alternate prompt. Number of chevrons indicates stack depth. @@ -546,7 +549,7 @@ char * get_alt_prompt(void) { int i = 0, j; - static char buf[MAX_CHEVRONS + 2]; /* includes terminating space & null */ + static char buf[MAX_CHEVRONS + 2]; /* includes terminating space & null */ struct control *c; /* if nothing on the command stack return NULL */ @@ -562,11 +565,11 @@ get_alt_prompt(void) /* Avoid overflow of buffer and indicate when we've limited the chevrons by starting with a '+' */ - if(i > MAX_CHEVRONS) { + if (i > MAX_CHEVRONS) { i = MAX_CHEVRONS; - buf[0]='+'; + buf[0] = '+'; } else { - buf[0]='>'; + buf[0] = '>'; } /* return one chevron per command stack depth */ @@ -607,6 +610,7 @@ getcommand(char *string) return (wlist); } + /* va: TODO: free control structure(s) before overwriting (memory leakage) */ int cp_evloop(char *string) @@ -631,15 +635,16 @@ cp_evloop(char *string) if (cend[stackp]->co_parent && !string) { cp_resetcontrol(); continue; - } else + } else { return (0); + } } if ((wlist->wl_word == NULL) || (*wlist->wl_word == '\0')) { /* User just typed return. */ wl_free(wlist); /* va, avoid memory leak */ - if (string) + if (string) { return (1); - else { + } else { cp_event--; continue; } @@ -708,10 +713,11 @@ cp_evloop(char *string) *dd = 0.0; } cend[stackp]->co_numtimes = (int) *dd; - } else + } else { fprintf(cp_err, "Error: bad repeat argument %s\n", t->wl_next->wl_word); /* CDHW */ + } wl_free(t); t = NULL; /* CDHW */ } @@ -733,9 +739,10 @@ cp_evloop(char *string) cend[stackp]->co_foreachvar = copy(wlist->wl_word); wlist = wlist->wl_next; - } else + } else { fprintf(stderr, "Error: missing foreach variable.\n"); + } wlist = cp_doglob(wlist); /*CDHW Possible leak around here? */ cend[stackp]->co_text = wl_copy(wlist); newblock; @@ -748,8 +755,9 @@ cp_evloop(char *string) if (wlist->wl_next->wl_next) fprintf(cp_err, "Warning: ignored extra junk after label.\n"); - } else + } else { fprintf(stderr, "Error: missing label.\n"); + } } else if (eq(wlist->wl_word, "goto")) { /* Incidentally, this won't work if the values 1 and 2 ever get @@ -761,8 +769,9 @@ cp_evloop(char *string) if (wlist->wl_next->wl_next) fprintf(cp_err, "Warning: ignored extra junk after goto.\n"); - } else + } else { fprintf(stderr, "Error: missing label.\n"); + } } else if (eq(wlist->wl_word, "continue")) { cend[stackp]->co_type = CO_CONTINUE; if (wlist->wl_next) { @@ -772,8 +781,9 @@ cp_evloop(char *string) fprintf(cp_err, "Warning: ignored extra junk after continue %d.\n", cend[stackp]->co_numtimes); - } else + } else { cend[stackp]->co_numtimes = 1; + } } else if (eq(wlist->wl_word, "break")) { cend[stackp]->co_type = CO_BREAK; if (wlist->wl_next) { @@ -783,8 +793,9 @@ cp_evloop(char *string) fprintf(cp_err, "Warning: ignored extra junk after break %d.\n", cend[stackp]->co_numtimes); - } else + } else { cend[stackp]->co_numtimes = 1; + } } else if (eq(wlist->wl_word, "end")) { /* Throw away this thing. */ if (!cend[stackp]->co_parent) { @@ -795,18 +806,18 @@ cp_evloop(char *string) x = cend[stackp]; cend[stackp] = cend[stackp]->co_parent; tfree(x); - x=NULL; + x = NULL; } else { x = cend[stackp]; cend[stackp] = cend[stackp]->co_parent; cend[stackp]->co_children = NULL; tfree(x); - x=NULL; + x = NULL; } } else if (eq(wlist->wl_word, "else")) { if (!cend[stackp]->co_parent || - (cend[stackp]->co_parent->co_type != - CO_IF)) { + (cend[stackp]->co_parent->co_type != + CO_IF)) { fprintf(stderr, "Error: misplaced else.\n"); cend[stackp]->co_type = CO_UNFILLED; } else { @@ -852,15 +863,16 @@ cp_evloop(char *string) } wl_free(wlist); wlist = NULL; - if (string) { + if (string) return (1); /* The return value is irrelevant. */ - } } + wl_free(wlist); wlist = NULL; return (0); /* va: which value? */ } + /* This blows away the control structures... */ void cp_free_control(void); /* needed by resetcontrol */ void cp_resetcontrol(void) @@ -883,9 +895,9 @@ cp_popcontrol(void) { if (cp_debug) fprintf(cp_err, "pop: stackp: %d -> %d\n", stackp, stackp - 1); - if (stackp < 1) + if (stackp < 1) { fprintf(cp_err, "cp_popcontrol: Internal Error: stack empty\n"); - else { + } else { /* va: free unused control structure */ ctl_free(control[stackp]); stackp--; @@ -924,13 +936,14 @@ cp_toplevel(void) /* va: This totally frees the control structures */ -void cp_free_control(void) +void +cp_free_control(void) { int i; - for (i=stackp; i>=0; i--) ctl_free(control[i]); + for (i = stackp; i >= 0; i--) + ctl_free(control[i]); control[0] = cend[0] = NULL; stackp = 0; } - diff --git a/src/frontend/cpitf.c b/src/frontend/cpitf.c index 5ee4d467c..0cd6095c9 100644 --- a/src/frontend/cpitf.c +++ b/src/frontend/cpitf.c @@ -268,7 +268,7 @@ ft_cpinit(void) found = TRUE; break; -#if defined (HAS_WINDOWS) || defined (__MINGW32__) || defined (_MSC_VER) +#if defined(HAS_WINDOWS) || defined(__MINGW32__) || defined(_MSC_VER) /* search in local directory where ngspice.exe resides */ #if defined TCL_MODULE } else if ((fp = fopen("./tclspinit", "r")) != NULL) { @@ -281,8 +281,9 @@ ft_cpinit(void) found = TRUE; break; #endif - } else if (ft_controldb) + } else if (ft_controldb) { fprintf(cp_err, "Note: can't open \"%s\".\n", buf); + } } if (!found) @@ -292,6 +293,7 @@ ft_cpinit(void) tcap_init(); } + /* Decide whether a condition is TRUE or not. */ bool @@ -332,6 +334,7 @@ cp_istrue(wordlist *wl) return (FALSE); } + /* This gets called before every command is executed... from fcns do_command() or do_block() in control.c */ @@ -345,12 +348,14 @@ cp_periodic(void) vec_gc(); /* remove vectors which do not have permanent flag set (vectors.c) */ } + void cp_doquit(void) { com_quit(NULL); } + /* This is how we deal with emulation of commands by scripts... If the script * is found, then set the variables argc and argv and call the script. Note * that this also allows us to type a filename to load a spice deck... diff --git a/src/frontend/define.c b/src/frontend/define.c index 0b40bd97d..c0119ee61 100644 --- a/src/frontend/define.c +++ b/src/frontend/define.c @@ -28,8 +28,8 @@ static void savetree(struct pnode *pn); static void prdefs(char *name); static void prtree(struct udfunc *ud); static void prtree1(struct pnode *pn, FILE *fp); -static struct pnode * trcopy(struct pnode *tree, char *args, struct pnode *nn); -static struct pnode * ntharg(int num, struct pnode *args); +static struct pnode *trcopy(struct pnode *tree, char *args, struct pnode *nn); +static struct pnode *ntharg(int num, struct pnode *args); static struct udfunc *udfuncs = NULL; @@ -174,7 +174,7 @@ savetree(struct pnode *pn) pn->pn_value->v_realdata = TMALLOC(double, d->v_length); bcopy(d->v_realdata, pn->pn_value->v_realdata, - sizeof (double) * (size_t) d->v_length); + sizeof(double) * (size_t) d->v_length); } else { pn->pn_value->v_compdata = TMALLOC(ngcomplex_t, d->v_length); bcopy(d->v_compdata, @@ -201,7 +201,7 @@ prdefs(char *name) char *s; if (name) { - s =strchr(name, '(' /* ) */); + s = strchr(name, '(' /* ) */); if (s) *s = '\0'; } @@ -289,9 +289,9 @@ ft_substdef(const char *name, struct pnode *args) for (udf = udfuncs; udf; udf = udf->ud_next) if (eq(name, udf->ud_name)) { - if (arity == udf->ud_arity) + if (arity == udf->ud_arity) { break; - else { + } else { found = TRUE; rarity = udf->ud_arity; } @@ -349,12 +349,16 @@ trcopy(struct pnode *tree, char *args, struct pnode *nn) while (*s++) /* Get past the last '\0'. */ ; } + if (*s) return (ntharg(i, nn)); else return (tree); + } else { + return (tree); + } } else if (tree->pn_func) { @@ -412,7 +416,7 @@ ntharg(int num, struct pnode *args) ptry = args; - if (num > 1) { + if (num > 1) while (--num > 0) { if (ptry && ptry->pn_op && (ptry->pn_op->op_num != PT_OP_COMMA)) { @@ -423,7 +427,6 @@ ntharg(int num, struct pnode *args) } ptry = ptry->pn_right; } - } if (ptry && ptry->pn_op && (ptry->pn_op->op_num == PT_OP_COMMA)) ptry = ptry->pn_left; diff --git a/src/frontend/device.c b/src/frontend/device.c index 4b1f3343d..d32ea7c1e 100644 --- a/src/frontend/device.c +++ b/src/frontend/device.c @@ -23,12 +23,14 @@ Modified: 2000 AlansFixes #include "gens.h" /* wl_forall */ + static wordlist *devexpand(char *name); static void all_show(wordlist *wl, int mode); static void all_show_old(wordlist *wl, int mode); static void com_alter_mod(wordlist *wl); static void if_set_binned_model(CKTcircuit *, char *, char *, struct dvec *); + /* * devhelp: lists available devices and information on parameters * devhelp : shows all available devices @@ -44,6 +46,7 @@ void com_devhelp(wordlist *wl) devhelp(wl); } + void devhelp(wordlist *wl) { int i, k = 0; @@ -60,12 +63,11 @@ void devhelp(wordlist *wl) if (!wlist) { out_init(); out_printf("\nDevices available in the simulator\n\n"); - for (k = 0; k < ft_sim->numDevices; k++) { + for (k = 0; k < ft_sim->numDevices; k++) if (ft_sim->devices[k]) out_printf("%-*s:\t%s\n", DEV_WIDTH, ft_sim->devices[k]->name, ft_sim->devices[k]->description); - } out_send("\n"); return; } @@ -107,10 +109,10 @@ void devhelp(wordlist *wl) } } -/* At this point, found is TRUE and we have found the device. - * Now we have to scan the model and instance parameters to print - * the string - */ + /* At this point, found is TRUE and we have found the device. + * Now we have to scan the model and instance parameters to print + * the string + */ found = FALSE; if (wlist && wlist->wl_word) { plist = ft_sim->devices[devindex]->modelParms; @@ -121,8 +123,8 @@ void devhelp(wordlist *wl) out_printf("Model Parameters\n"); if (csv) out_printf("id#, Name, Dir, Description\n"); - else - out_printf("%5s\t %-10s\t Dir\t Description\n", "id#", "Name"); + else + out_printf("%5s\t %-10s\t Dir\t Description\n", "id#", "Name"); printdesc(plist[i], csv); out_send("\n"); } @@ -137,8 +139,8 @@ void devhelp(wordlist *wl) out_printf("Instance Parameters\n"); if (csv) out_printf("id#, Name, Dir, Description\n"); - else - out_printf("%5s\t %-10s\t Dir\t Description\n", "id#", "Name"); + else + out_printf("%5s\t %-10s\t Dir\t Description\n", "id#", "Name"); printdesc(plist[i], csv); out_send("\n"); } @@ -151,7 +153,7 @@ void devhelp(wordlist *wl) } -/* No arguments - we want all the parameters*/ + /* No arguments - we want all the parameters*/ out_init(); out_printf("%s - %s\n\n", ft_sim->devices[devindex]->name, ft_sim->devices[devindex]->description); out_printf("Model Parameters\n"); @@ -178,12 +180,12 @@ void devhelp(wordlist *wl) } - /* * Pretty print parameter descriptions * This function prints description of device parameters */ -void printdesc(IFparm p, bool csv) +void +printdesc(IFparm p, bool csv) { char sep; int spacer1, spacer2; @@ -226,28 +228,28 @@ void printdesc(IFparm p, bool csv) * */ - static int count; - void com_showmod(wordlist *wl) { if (cp_getvar("altshow", CP_BOOL, NULL)) all_show(wl, 1); - else + else all_show_old(wl, 1); } + void com_show(wordlist *wl) { if (cp_getvar("altshow", CP_BOOL, NULL)) all_show(wl, 0); - else + else all_show_old(wl, 0); } + static void all_show(wordlist *wl, int mode) { @@ -270,7 +272,7 @@ all_show(wordlist *wl, int mode) } if (!cp_getvar("width", CP_NUM, &screen_width)) - screen_width = DEF_WIDTH; + screen_width = DEF_WIDTH; count = (screen_width - LEFT_WIDTH) / (DEV_WIDTH + 1); count = 1; @@ -287,40 +289,40 @@ all_show(wordlist *wl, int mode) for (w = wl; w && !nextgroup; w = next) { next = w->wl_next; - if ( eq(w->wl_word, "*") ) { - tfree(w->wl_word); - w->wl_word = strdup("all"); + if (eq(w->wl_word, "*")) { + tfree(w->wl_word); + w->wl_word = strdup("all"); } - + if (eq(w->wl_word, "++") || eq(w->wl_word, "all")) { if (params) { - param_flag = DGEN_ALLPARAMS; - if (prev) - prev->wl_next = w->wl_next; - else - params = next; + param_flag = DGEN_ALLPARAMS; + if (prev) + prev->wl_next = w->wl_next; + else + params = next; } else { - dev_flag = DGEN_ALLDEVS; - if (prev) - prev->wl_next = w->wl_next; - else - thisgroup = next; + dev_flag = DGEN_ALLDEVS; + if (prev) + prev->wl_next = w->wl_next; + else + thisgroup = next; } /* w must not be freed here */ w = NULL; } else if (eq(w->wl_word, "+")) { if (params) { - param_flag = DGEN_DEFPARAMS; - if (prev) - prev->wl_next = w->wl_next; - else - params = next; + param_flag = DGEN_DEFPARAMS; + if (prev) + prev->wl_next = w->wl_next; + else + params = next; } else { - dev_flag = DGEN_DEFDEVS; - if (prev) - prev->wl_next = w->wl_next; - else - thisgroup = next; + dev_flag = DGEN_DEFDEVS; + if (prev) + prev->wl_next = w->wl_next; + else + thisgroup = next; } /* w must not be freed here */ w = NULL; @@ -330,9 +332,9 @@ all_show(wordlist *wl, int mode) if (!params) { params = next; if (prev) - prev->wl_next = NULL; + prev->wl_next = NULL; else - thisgroup = NULL; + thisgroup = NULL; } else { if (prev) prev->wl_next = next; @@ -340,61 +342,60 @@ all_show(wordlist *wl, int mode) params = next; } } else if (eq(w->wl_word, ";") || eq(w->wl_word, ",")) { - nextgroup = next; - /* w must not be freed here */ - w = NULL; - if (prev) - prev->wl_next = NULL; - break; + nextgroup = next; + /* w must not be freed here */ + w = NULL; + if (prev) + prev->wl_next = NULL; + break; } prev = w; } instances = 0; for (dg = dgen_init(ft_curckt->ci_ckt, thisgroup, 1, dev_flag, mode); - dg; dgen_nth_next(&dg, count)) + dg; dgen_nth_next(&dg, count)) { instances = 1; if (dg->flags & DGEN_INSTANCE) { instances = 2; n += 1; - fprintf(cp_out,"%s:\n", dg->instance->GENname); - fprintf(cp_out," %-19s= %s\n", "model", dg->model->GENmodName); + fprintf(cp_out, "%s:\n", dg->instance->GENname); + fprintf(cp_out, " %-19s= %s\n", "model", dg->model->GENmodName); listdg = dg; - if (param_flag) { - param_forall(dg, param_flag); - } - else if (!params) { - param_forall(dg, DGEN_DEFPARAMS); - } - if (params) { - wl_forall(params, listparam, dg); - } - - } else if (ft_sim->devices[dg->dev_type_no]->numModelParms) { - fprintf(cp_out," %s models (%s)\n", - ft_sim->devices[dg->dev_type_no]->name, - ft_sim->devices[dg->dev_type_no]->description); - n += 1; - i = 0; - do { - fprintf(cp_out,"%*s", LEFT_WIDTH, "model"); - j = dgen_for_n(dg, count, printstr_m, NULL, i); - i += 1; - fprintf(cp_out,"\n"); - } while (j); - fprintf(cp_out,"\n"); - if (param_flag) param_forall(dg, param_flag); else if (!params) param_forall(dg, DGEN_DEFPARAMS); + if (params) wl_forall(params, listparam, dg); - fprintf(cp_out,"\n"); + + } else if (ft_sim->devices[dg->dev_type_no]->numModelParms) { + fprintf(cp_out, " %s models (%s)\n", + ft_sim->devices[dg->dev_type_no]->name, + ft_sim->devices[dg->dev_type_no]->description); + n += 1; + i = 0; + do { + fprintf(cp_out, "%*s", LEFT_WIDTH, "model"); + j = dgen_for_n(dg, count, printstr_m, NULL, i); + i += 1; + fprintf(cp_out, "\n"); + } while (j); + fprintf(cp_out, "\n"); + + if (param_flag) + param_forall(dg, param_flag); + else if (!params) + param_forall(dg, DGEN_DEFPARAMS); + + if (params) + wl_forall(params, listparam, dg); + fprintf(cp_out, "\n"); } } @@ -403,15 +404,16 @@ all_show(wordlist *wl, int mode) } while (wl); if (!n) { - if (instances == 0) - printf("No matching instances or models\n"); - else if (instances == 1) - printf("No matching models\n"); - else - printf("No matching elements\n"); + if (instances == 0) + printf("No matching instances or models\n"); + else if (instances == 1) + printf("No matching models\n"); + else + printf("No matching elements\n"); } } + static void all_show_old(wordlist *wl, int mode) { @@ -434,7 +436,7 @@ all_show_old(wordlist *wl, int mode) } if (!cp_getvar("width", CP_NUM, &screen_width)) - screen_width = DEF_WIDTH; + screen_width = DEF_WIDTH; count = (screen_width - LEFT_WIDTH) / (DEV_WIDTH + 1); n = 0; @@ -450,40 +452,40 @@ all_show_old(wordlist *wl, int mode) for (w = wl; w && !nextgroup; w = next) { next = w->wl_next; - if ( eq(w->wl_word, "*") ) { - tfree(w->wl_word); - w->wl_word = strdup("all"); + if (eq(w->wl_word, "*")) { + tfree(w->wl_word); + w->wl_word = strdup("all"); } - + if (eq(w->wl_word, "++") || eq(w->wl_word, "all")) { if (params) { - param_flag = DGEN_ALLPARAMS; - if (prev) - prev->wl_next = w->wl_next; - else - params = next; + param_flag = DGEN_ALLPARAMS; + if (prev) + prev->wl_next = w->wl_next; + else + params = next; } else { - dev_flag = DGEN_ALLDEVS; - if (prev) - prev->wl_next = w->wl_next; - else - thisgroup = next; + dev_flag = DGEN_ALLDEVS; + if (prev) + prev->wl_next = w->wl_next; + else + thisgroup = next; } /* w must not be freed here */ w = NULL; } else if (eq(w->wl_word, "+")) { if (params) { - param_flag = DGEN_DEFPARAMS; - if (prev) - prev->wl_next = w->wl_next; - else - params = next; + param_flag = DGEN_DEFPARAMS; + if (prev) + prev->wl_next = w->wl_next; + else + params = next; } else { - dev_flag = DGEN_DEFDEVS; - if (prev) - prev->wl_next = w->wl_next; - else - thisgroup = next; + dev_flag = DGEN_DEFDEVS; + if (prev) + prev->wl_next = w->wl_next; + else + thisgroup = next; } /* w must not be freed here */ w = NULL; @@ -493,9 +495,9 @@ all_show_old(wordlist *wl, int mode) if (!params) { params = next; if (prev) - prev->wl_next = NULL; + prev->wl_next = NULL; else - thisgroup = NULL; + thisgroup = NULL; } else { if (prev) prev->wl_next = next; @@ -503,44 +505,44 @@ all_show_old(wordlist *wl, int mode) params = next; } } else if (eq(w->wl_word, ";") || eq(w->wl_word, ",")) { - nextgroup = next; - /* w must not be freed here */ - w = NULL; - if (prev) - prev->wl_next = NULL; - break; + nextgroup = next; + /* w must not be freed here */ + w = NULL; + if (prev) + prev->wl_next = NULL; + break; } prev = w; } instances = 0; for (dg = dgen_init(ft_curckt->ci_ckt, thisgroup, 1, dev_flag, mode); - dg; dgen_nth_next(&dg, count)) + dg; dgen_nth_next(&dg, count)) { instances = 1; if (dg->flags & DGEN_INSTANCE) { instances = 2; - fprintf(cp_out," %s: %s\n", + fprintf(cp_out, " %s: %s\n", ft_sim->devices[dg->dev_type_no]->name, ft_sim->devices[dg->dev_type_no]->description); n += 1; i = 0; do { - fprintf(cp_out,"%*s", LEFT_WIDTH, "device"); - j = dgen_for_n(dg, count, printstr_n, NULL, i); - i += 1; - fprintf(cp_out,"\n"); + fprintf(cp_out, "%*s", LEFT_WIDTH, "device"); + j = dgen_for_n(dg, count, printstr_n, NULL, i); + i += 1; + fprintf(cp_out, "\n"); } while (j); if (ft_sim->devices[dg->dev_type_no]->numModelParms) { - i = 0; - do { - fprintf(cp_out,"%*s", LEFT_WIDTH, "model"); - j = dgen_for_n(dg, count, printstr_m, NULL, i); - i += 1; - fprintf(cp_out,"\n"); - } while (j); + i = 0; + do { + fprintf(cp_out, "%*s", LEFT_WIDTH, "model"); + j = dgen_for_n(dg, count, printstr_m, NULL, i); + i += 1; + fprintf(cp_out, "\n"); + } while (j); } listdg = dg; @@ -548,31 +550,33 @@ all_show_old(wordlist *wl, int mode) param_forall_old(dg, param_flag); else if (!params) param_forall_old(dg, DGEN_DEFPARAMS); + if (params) wl_forall(params, listparam, dg); - fprintf(cp_out,"\n"); + fprintf(cp_out, "\n"); } else if (ft_sim->devices[dg->dev_type_no]->numModelParms) { - fprintf(cp_out," %s models (%s)\n", + fprintf(cp_out, " %s models (%s)\n", ft_sim->devices[dg->dev_type_no]->name, ft_sim->devices[dg->dev_type_no]->description); n += 1; i = 0; do { - fprintf(cp_out,"%*s", LEFT_WIDTH, "model"); - j = dgen_for_n(dg, count, printstr_m, NULL, i); - i += 1; - fprintf(cp_out,"\n"); + fprintf(cp_out, "%*s", LEFT_WIDTH, "model"); + j = dgen_for_n(dg, count, printstr_m, NULL, i); + i += 1; + fprintf(cp_out, "\n"); } while (j); - fprintf(cp_out,"\n"); + fprintf(cp_out, "\n"); if (param_flag) param_forall_old(dg, param_flag); else if (!params) param_forall_old(dg, DGEN_DEFPARAMS); + if (params) wl_forall(params, listparam, dg); - fprintf(cp_out,"\n"); + fprintf(cp_out, "\n"); } } @@ -581,15 +585,16 @@ all_show_old(wordlist *wl, int mode) } while (wl); if (!n) { - if (instances == 0) - printf("No matching instances or models\n"); - else if (instances == 1) - printf("No matching models\n"); - else - printf("No matching elements\n"); + if (instances == 0) + printf("No matching instances or models\n"); + else if (instances == 1) + printf("No matching models\n"); + else + printf("No matching elements\n"); } } + int printstr_n(dgen *dg, IFparm *p, int i) { @@ -597,12 +602,13 @@ printstr_n(dgen *dg, IFparm *p, int i) NG_IGNORE(i); if (dg->instance) - fprintf(cp_out," %*.*s", DEV_WIDTH, DEV_WIDTH, dg->instance->GENname); + fprintf(cp_out, " %*.*s", DEV_WIDTH, DEV_WIDTH, dg->instance->GENname); else - fprintf(cp_out," %*s", DEV_WIDTH, "<\?\?\?\?\?\?\?>"); + fprintf(cp_out, " %*s", DEV_WIDTH, "<\?\?\?\?\?\?\?>"); return 0; } + int printstr_m(dgen *dg, IFparm *p, int i) { @@ -610,12 +616,13 @@ printstr_m(dgen *dg, IFparm *p, int i) NG_IGNORE(i); if (dg->model) - fprintf(cp_out," %*.*s", DEV_WIDTH, DEV_WIDTH, dg->model->GENmodName); + fprintf(cp_out, " %*.*s", DEV_WIDTH, DEV_WIDTH, dg->model->GENmodName); else - fprintf(cp_out," %*s", DEV_WIDTH, "<\?\?\?\?\?\?\?>"); + fprintf(cp_out, " %*s", DEV_WIDTH, "<\?\?\?\?\?\?\?>"); return 0; } + void param_forall(dgen *dg, int flags) { @@ -633,28 +640,26 @@ param_forall(dgen *dg, int flags) plist = ft_sim->devices[dg->dev_type_no]->modelParms; } - for (i = 0; i < xcount; i++) { - if (plist[i].dataType & IF_ASK) { - if ((((CKTcircuit *) (dg->ckt))->CKTrhsOld - || (plist[i].dataType & IF_SET)) - && (!(plist[i].dataType & (IF_REDUNDANT | IF_UNINTERESTING)) - || (flags == DGEN_ALLPARAMS - && !(plist[i].dataType & IF_REDUNDANT)))) + for (i = 0; i < xcount; i++) + if (plist[i].dataType & IF_ASK) + if ((((CKTcircuit *) (dg->ckt))->CKTrhsOld || + (plist[i].dataType & IF_SET)) && + (!(plist[i].dataType & (IF_REDUNDANT | IF_UNINTERESTING)) || + (flags == DGEN_ALLPARAMS && !(plist[i].dataType & IF_REDUNDANT)))) { j = 0; do { - fprintf(cp_out," %-19s=", plist[i].keyword); + fprintf(cp_out, " %-19s=", plist[i].keyword); - k = dgen_for_n(dg, count, printvals, (plist + i), j); - fprintf(cp_out,"\n"); - j += 1; + k = dgen_for_n(dg, count, printvals, (plist + i), j); + fprintf(cp_out, "\n"); + j += 1; } while (k); } - } - } } + void param_forall_old(dgen *dg, int flags) { @@ -672,30 +677,28 @@ param_forall_old(dgen *dg, int flags) plist = ft_sim->devices[dg->dev_type_no]->modelParms; } - for (i = 0; i < xcount; i++) { - if (plist[i].dataType & IF_ASK) { - if ((((CKTcircuit *) (dg->ckt))->CKTrhsOld - || (plist[i].dataType & IF_SET)) - && (!(plist[i].dataType & (IF_REDUNDANT | IF_UNINTERESTING)) - || (flags == DGEN_ALLPARAMS - && !(plist[i].dataType & IF_REDUNDANT)))) + for (i = 0; i < xcount; i++) + if (plist[i].dataType & IF_ASK) + if ((((CKTcircuit *) (dg->ckt))->CKTrhsOld || + (plist[i].dataType & IF_SET)) && + (!(plist[i].dataType & (IF_REDUNDANT | IF_UNINTERESTING)) || + (flags == DGEN_ALLPARAMS && !(plist[i].dataType & IF_REDUNDANT)))) { j = 0; do { - if (!j) - fprintf(cp_out,"%*.*s", LEFT_WIDTH, LEFT_WIDTH, - plist[i].keyword); - else - fprintf(cp_out,"%*.*s", LEFT_WIDTH, LEFT_WIDTH, " "); - k = dgen_for_n(dg, count, printvals_old, (plist + i), j); - fprintf(cp_out,"\n"); - j += 1; + if (!j) + fprintf(cp_out, "%*.*s", LEFT_WIDTH, LEFT_WIDTH, + plist[i].keyword); + else + fprintf(cp_out, "%*.*s", LEFT_WIDTH, LEFT_WIDTH, " "); + k = dgen_for_n(dg, count, printvals_old, (plist + i), j); + fprintf(cp_out, "\n"); + j += 1; } while (k); } - } - } } + void listparam(wordlist *p, dgen *dg) { @@ -713,24 +716,22 @@ listparam(wordlist *p, dgen *dg) plist = ft_sim->devices[dg->dev_type_no]->modelParms; } - for (i = 0; i < xcount; i++) { - if (eqc(p->wl_word, plist[i].keyword) && (plist[i].dataType & IF_ASK)) - { + for (i = 0; i < xcount; i++) + if (eqc(p->wl_word, plist[i].keyword) && (plist[i].dataType & IF_ASK)) { found = 1; break; } - } if (found) { - if ((((CKTcircuit *) (dg->ckt))->CKTrhsOld - || (plist[i].dataType & IF_SET))) + if ((((CKTcircuit *) (dg->ckt))->CKTrhsOld || + (plist[i].dataType & IF_SET))) { j = 0; do { if (!j) - fprintf(cp_out,"%*.*s", LEFT_WIDTH, LEFT_WIDTH, p->wl_word); + fprintf(cp_out, "%*.*s", LEFT_WIDTH, LEFT_WIDTH, p->wl_word); else - fprintf(cp_out,"%*.*s", LEFT_WIDTH, LEFT_WIDTH, " "); + fprintf(cp_out, "%*.*s", LEFT_WIDTH, LEFT_WIDTH, " "); k = dgen_for_n(dg, count, printvals_old, (plist + i), j); printf("\n"); j += 1; @@ -739,11 +740,11 @@ listparam(wordlist *p, dgen *dg) j = 0; do { if (!j) - fprintf(cp_out,"%*.*s", LEFT_WIDTH, LEFT_WIDTH, p->wl_word); + fprintf(cp_out, "%*.*s", LEFT_WIDTH, LEFT_WIDTH, p->wl_word); else - fprintf(cp_out,"%*s", LEFT_WIDTH, " "); + fprintf(cp_out, "%*s", LEFT_WIDTH, " "); k = dgen_for_n(dg, count, bogus1, 0, j); - fprintf(cp_out,"\n"); + fprintf(cp_out, "\n"); j += 1; } while (k > 0); } @@ -751,36 +752,41 @@ listparam(wordlist *p, dgen *dg) j = 0; do { if (!j) - fprintf(cp_out,"%*.*s", LEFT_WIDTH, LEFT_WIDTH, p->wl_word); + fprintf(cp_out, "%*.*s", LEFT_WIDTH, LEFT_WIDTH, p->wl_word); else - fprintf(cp_out,"%*s", LEFT_WIDTH, " "); + fprintf(cp_out, "%*s", LEFT_WIDTH, " "); k = dgen_for_n(dg, count, bogus2, 0, j); - fprintf(cp_out,"\n"); + fprintf(cp_out, "\n"); j += 1; } while (k > 0); } } -int bogus1(dgen *dg, IFparm *p, int i) + +int +bogus1(dgen *dg, IFparm *p, int i) { NG_IGNORE(dg); NG_IGNORE(p); NG_IGNORE(i); - fprintf(cp_out," %*s", DEV_WIDTH, "---------"); + fprintf(cp_out, " %*s", DEV_WIDTH, "---------"); return 0; } -int bogus2(dgen *dg, IFparm *p, int i) + +int +bogus2(dgen *dg, IFparm *p, int i) { NG_IGNORE(dg); NG_IGNORE(p); NG_IGNORE(i); - fprintf(cp_out," %*s", DEV_WIDTH, "?????????"); + fprintf(cp_out, " %*s", DEV_WIDTH, "?????????"); return 0; } + int printvals(dgen *dg, IFparm *p, int i) { @@ -788,11 +794,11 @@ printvals(dgen *dg, IFparm *p, int i) int n; if (dg->flags & DGEN_INSTANCE) - ft_sim->askInstanceQuest (ft_curckt->ci_ckt, dg->instance, - p->id, &val, &val); + ft_sim->askInstanceQuest + (ft_curckt->ci_ckt, dg->instance, p->id, &val, &val); else - ft_sim->askModelQuest (ft_curckt->ci_ckt, dg->model, - p->id, &val, &val); + ft_sim->askModelQuest + (ft_curckt->ci_ckt, dg->model, p->id, &val, &val); if (p->dataType & IF_VECTOR) n = val.v.numValue; @@ -804,70 +810,71 @@ printvals(dgen *dg, IFparm *p, int i) if (i >= n) { if (i == 0) - fprintf(cp_out," -"); + fprintf(cp_out, " -"); else - fprintf(cp_out," "); + fprintf(cp_out, " "); return 0; } if (p->dataType & IF_VECTOR) { /* va: ' ' is no flag for %s */ switch ((p->dataType & IF_VARTYPES) & ~IF_VECTOR) { - case IF_FLAG: - fprintf(cp_out," %d", val.v.vec.iVec[i]); - break; - case IF_INTEGER: - fprintf(cp_out," %d", val.v.vec.iVec[i]); - break; - case IF_REAL: - fprintf(cp_out," %.6g", val.v.vec.rVec[i]); - break; - case IF_COMPLEX: - if (!(i % 2)) - fprintf(cp_out," %.6g", val.v.vec.cVec[i / 2].real); - else - fprintf(cp_out," %.6g", val.v.vec.cVec[i / 2].imag); - break; - case IF_STRING: - fprintf(cp_out," %s", val.v.vec.sVec[i]); - break; - case IF_INSTANCE: - fprintf(cp_out," %s", val.v.vec.uVec[i]); - break; - default: - fprintf(cp_out," %s", " ******** "); + case IF_FLAG: + fprintf(cp_out, " %d", val.v.vec.iVec[i]); + break; + case IF_INTEGER: + fprintf(cp_out, " %d", val.v.vec.iVec[i]); + break; + case IF_REAL: + fprintf(cp_out, " %.6g", val.v.vec.rVec[i]); + break; + case IF_COMPLEX: + if (!(i % 2)) + fprintf(cp_out, " %.6g", val.v.vec.cVec[i / 2].real); + else + fprintf(cp_out, " %.6g", val.v.vec.cVec[i / 2].imag); + break; + case IF_STRING: + fprintf(cp_out, " %s", val.v.vec.sVec[i]); + break; + case IF_INSTANCE: + fprintf(cp_out, " %s", val.v.vec.uVec[i]); + break; + default: + fprintf(cp_out, " %s", " ******** "); } } else { switch ((p->dataType & IF_VARTYPES) & ~IF_VECTOR) { - case IF_FLAG: - fprintf(cp_out," %d", val.iValue); - break; - case IF_INTEGER: - fprintf(cp_out," %d", val.iValue); - break; - case IF_REAL: - fprintf(cp_out," %.6g", val.rValue); - break; - case IF_COMPLEX: - if (i % 2) - fprintf(cp_out," %.6g", val.cValue.real); - else - fprintf(cp_out," %.6g", val.cValue.imag); - break; - case IF_STRING: - fprintf(cp_out," %s", val.sValue); - break; - case IF_INSTANCE: - fprintf(cp_out," %s", val.uValue); - break; - default: - fprintf(cp_out," %s", " ******** "); + case IF_FLAG: + fprintf(cp_out, " %d", val.iValue); + break; + case IF_INTEGER: + fprintf(cp_out, " %d", val.iValue); + break; + case IF_REAL: + fprintf(cp_out, " %.6g", val.rValue); + break; + case IF_COMPLEX: + if (i % 2) + fprintf(cp_out, " %.6g", val.cValue.real); + else + fprintf(cp_out, " %.6g", val.cValue.imag); + break; + case IF_STRING: + fprintf(cp_out, " %s", val.sValue); + break; + case IF_INSTANCE: + fprintf(cp_out, " %s", val.uValue); + break; + default: + fprintf(cp_out, " %s", " ******** "); } } return n - 1; } + int printvals_old(dgen *dg, IFparm *p, int i) { @@ -875,11 +882,11 @@ printvals_old(dgen *dg, IFparm *p, int i) int n, error; if (dg->flags & DGEN_INSTANCE) - error = ft_sim->askInstanceQuest (ft_curckt->ci_ckt, dg->instance, - p->id, &val, &val); + error = ft_sim->askInstanceQuest + (ft_curckt->ci_ckt, dg->instance, p->id, &val, &val); else - error = ft_sim->askModelQuest (ft_curckt->ci_ckt, dg->model, - p->id, &val, &val); + error = ft_sim->askModelQuest + (ft_curckt->ci_ckt, dg->model, p->id, &val, &val); if (p->dataType & IF_VECTOR) n = val.v.numValue; @@ -891,67 +898,66 @@ printvals_old(dgen *dg, IFparm *p, int i) if (i >= n) { if (i == 0) - fprintf(cp_out," -"); + fprintf(cp_out, " -"); else - fprintf(cp_out," "); + fprintf(cp_out, " "); return 0; } - if(error) { - fprintf(cp_out," <>", error); - } else - if (p->dataType & IF_VECTOR) { + if (error) { + fprintf(cp_out, " <>", error); + } else if (p->dataType & IF_VECTOR) { /* va: ' ' is no flag for %s */ switch ((p->dataType & IF_VARTYPES) & ~IF_VECTOR) { - case IF_FLAG: - fprintf(cp_out," % *d", DEV_WIDTH, val.v.vec.iVec[i]); - break; - case IF_INTEGER: - fprintf(cp_out," % *d", DEV_WIDTH, val.v.vec.iVec[i]); - break; - case IF_REAL: - fprintf(cp_out," % *.6g", DEV_WIDTH, val.v.vec.rVec[i]); - break; - case IF_COMPLEX: - if (!(i % 2)) - fprintf(cp_out," % *.6g", DEV_WIDTH, val.v.vec.cVec[i / 2].real); - else - fprintf(cp_out," % *.6g", DEV_WIDTH, val.v.vec.cVec[i / 2].imag); - break; - case IF_STRING: - fprintf(cp_out," %*.*s", DEV_WIDTH, DEV_WIDTH, val.v.vec.sVec[i]); - break; - case IF_INSTANCE: - fprintf(cp_out," %*.*s", DEV_WIDTH, DEV_WIDTH, val.v.vec.uVec[i]); - break; - default: - fprintf(cp_out," %*.*s", DEV_WIDTH, DEV_WIDTH, " ******** "); + case IF_FLAG: + fprintf(cp_out, " % *d", DEV_WIDTH, val.v.vec.iVec[i]); + break; + case IF_INTEGER: + fprintf(cp_out, " % *d", DEV_WIDTH, val.v.vec.iVec[i]); + break; + case IF_REAL: + fprintf(cp_out, " % *.6g", DEV_WIDTH, val.v.vec.rVec[i]); + break; + case IF_COMPLEX: + if (!(i % 2)) + fprintf(cp_out, " % *.6g", DEV_WIDTH, val.v.vec.cVec[i / 2].real); + else + fprintf(cp_out, " % *.6g", DEV_WIDTH, val.v.vec.cVec[i / 2].imag); + break; + case IF_STRING: + fprintf(cp_out, " %*.*s", DEV_WIDTH, DEV_WIDTH, val.v.vec.sVec[i]); + break; + case IF_INSTANCE: + fprintf(cp_out, " %*.*s", DEV_WIDTH, DEV_WIDTH, val.v.vec.uVec[i]); + break; + default: + fprintf(cp_out, " %*.*s", DEV_WIDTH, DEV_WIDTH, " ******** "); } } else { switch ((p->dataType & IF_VARTYPES) & ~IF_VECTOR) { - case IF_FLAG: - fprintf(cp_out," % *d", DEV_WIDTH, val.iValue); - break; - case IF_INTEGER: - fprintf(cp_out," % *d", DEV_WIDTH, val.iValue); - break; - case IF_REAL: - fprintf(cp_out," % *.6g", DEV_WIDTH, val.rValue); - break; - case IF_COMPLEX: - if (i % 2) - fprintf(cp_out," % *.6g", DEV_WIDTH, val.cValue.real); - else - fprintf(cp_out," % *.6g", DEV_WIDTH, val.cValue.imag); - break; - case IF_STRING: - fprintf(cp_out," %*.*s", DEV_WIDTH, DEV_WIDTH, val.sValue); - break; - case IF_INSTANCE: - fprintf(cp_out," %*.*s", DEV_WIDTH, DEV_WIDTH, val.uValue); - break; - default: - fprintf(cp_out," %*.*s", DEV_WIDTH, DEV_WIDTH, " ******** "); + case IF_FLAG: + fprintf(cp_out, " % *d", DEV_WIDTH, val.iValue); + break; + case IF_INTEGER: + fprintf(cp_out, " % *d", DEV_WIDTH, val.iValue); + break; + case IF_REAL: + fprintf(cp_out, " % *.6g", DEV_WIDTH, val.rValue); + break; + case IF_COMPLEX: + if (i % 2) + fprintf(cp_out, " % *.6g", DEV_WIDTH, val.cValue.real); + else + fprintf(cp_out, " % *.6g", DEV_WIDTH, val.cValue.imag); + break; + case IF_STRING: + fprintf(cp_out, " %*.*s", DEV_WIDTH, DEV_WIDTH, val.sValue); + break; + case IF_INSTANCE: + fprintf(cp_out, " %*.*s", DEV_WIDTH, DEV_WIDTH, val.uValue); + break; + default: + fprintf(cp_out, " %*.*s", DEV_WIDTH, DEV_WIDTH, " ******** "); } } @@ -977,9 +983,9 @@ old_show(wordlist *wl) devs = wl; wl = wl_find(":", wl); - if (!wl) + if (!wl) { parms = NULL; - else { + } else { if (wl->wl_prev) wl->wl_prev->wl_next = NULL; parms = wl->wl_next; @@ -1009,24 +1015,21 @@ old_show(wordlist *wl) if (parms) { for (tw = parms; tw; tw = tw->wl_next) { nn = copy(devs->wl_word); - v = if_getparam (ft_curckt->ci_ckt, - &nn, tw->wl_word, 0, 0); + v = if_getparam(ft_curckt->ci_ckt, &nn, tw->wl_word, 0, 0); if (!v) - v = if_getparam (ft_curckt->ci_ckt, - &nn, tw->wl_word, 0, 1); + v = if_getparam(ft_curckt->ci_ckt, &nn, tw->wl_word, 0, 1); if (v) { out_printf("\t%s =", tw->wl_word); - for (ww = cp_varwl(v); ww; ww = - ww->wl_next) + for (ww = cp_varwl(v); ww; ww = ww->wl_next) out_printf(" %s", ww->wl_word); out_send("\n"); } } } else { nn = copy(devs->wl_word); - v = if_getparam (ft_curckt->ci_ckt, &nn, "all", 0, 0); + v = if_getparam(ft_curckt->ci_ckt, &nn, "all", 0, 0); if (!v) - v = if_getparam (ft_curckt->ci_ckt, &nn, "all", 0, 1); + v = if_getparam(ft_curckt->ci_ckt, &nn, "all", 0, 1); while (v) { out_printf("\t%s =", v->va_name); for (ww = cp_varwl(v); ww; ww = ww->wl_next) @@ -1037,9 +1040,11 @@ old_show(wordlist *wl) } devs = devs->wl_next; } + return; } + /* Alter a device parameter. The new syntax here is * alter @device[parameter] = expr * alter device = expr @@ -1059,61 +1064,65 @@ com_alter(wordlist *wl) fprintf(cp_err, " or alter dev = expression\n"); return; } + com_alter_common(wl, 0); } + void com_altermod(wordlist *wl) { wordlist *fileword; bool newfile = FALSE; + fileword = wl; - while (fileword){ - if (ciprefix("file",fileword->wl_word)) { + while (fileword) { + if (ciprefix("file", fileword->wl_word)) newfile = TRUE; - } fileword = fileword->wl_next; } + if (newfile) com_alter_mod(wl); else com_alter_common(wl, 1); } + static void if_set_binned_model(CKTcircuit *ckt, char *devname, char *param, struct dvec *val) { - char *width_length; - double w=0.0, l=0.0; - struct variable *v; + char *width_length; + double w = 0.0, l = 0.0; + struct variable *v; - v = if_getparam(ckt, &devname, "w", 0, 0); - if (!v) { - fprintf(cp_err, "Error: Can't access width instance parameter.\n"); - return; - } - w = v->va_V.vV_real; + v = if_getparam(ckt, &devname, "w", 0, 0); + if (!v) { + fprintf(cp_err, "Error: Can't access width instance parameter.\n"); + return; + } + w = v->va_V.vV_real; - v = if_getparam(ckt, &devname, "l", 0, 0); - if (!v) { - fprintf(cp_err, "Error: Can't access length instance parameter.\n"); - return; - } - l = v->va_V.vV_real; + v = if_getparam(ckt, &devname, "l", 0, 0); + if (!v) { + fprintf(cp_err, "Error: Can't access length instance parameter.\n"); + return; + } + l = v->va_V.vV_real; - if (param[0] == 'w') { - w = *val->v_realdata; /* overwrite the width with the alter param */ - } else { - l = *val->v_realdata; /* overwrite the length with the alter param */ - } - width_length = TMALLOC(char, 36); - (void) sprintf(width_length,"w=%15.7e l=%15.7e", w, l); + if (param[0] == 'w') + w = *val->v_realdata; /* overwrite the width with the alter param */ + else + l = *val->v_realdata; /* overwrite the length with the alter param */ - if_setparam_model(ft_curckt->ci_ckt, &devname, width_length); - FREE(width_length); + width_length = TMALLOC(char, 36); + (void) sprintf(width_length, "w=%15.7e l=%15.7e", w, l); + if_setparam_model(ft_curckt->ci_ckt, &devname, width_length); + FREE(width_length); } + static void com_alter_common(wordlist *wl, int do_model) { @@ -1122,11 +1131,11 @@ com_alter_common(wordlist *wl, int do_model) char *param; struct dvec *dv; struct pnode *names; - + /* DIE 2009_02_06 */ char *argument; char **arglist; - int i=0, step=0, n, wlen, maxelem=3; + int i = 0, step = 0, n, wlen, maxelem = 3; wordlist *wl2 = NULL, *wlin, *rhs; bool eqfound = FALSE, vecfound = FALSE; @@ -1135,81 +1144,81 @@ com_alter_common(wordlist *wl, int do_model) return; } - /* - wordlist 'wl' will be splitted into a wordlist wl2 with three elements, - containing - 1) '@dev[param]' string (i.e.: the substring before '=' char); - 2) '=' string; - 3) 'expression' string. + /* + wordlist 'wl' will be splitted into a wordlist wl2 with three elements, + containing + 1) '@dev[param]' string (i.e.: the substring before '=' char); + 2) '=' string; + 3) 'expression' string. - Spaces around the '=' sign have to be removed. This is provided - by inp_remove_excess_ws(). But take care if command is entered manually! - - If the 'altermod' argument is 'altermod m1 vth0=0.7', 'm1' has to be kept as the - element in wl2 before splitting inserts the three new elements. - If 'expression' is a vector (e.g. [ 1.0 1.2 1.4 ] ), its elements - in wl2 have to follow the splitting. wl_splice() will take care of this. + Spaces around the '=' sign have to be removed. This is provided + by inp_remove_excess_ws(). But take care if command is entered manually! + + If the 'altermod' argument is 'altermod m1 vth0=0.7', 'm1' has to be kept as the + element in wl2 before splitting inserts the three new elements. + If 'expression' is a vector (e.g. [ 1.0 1.2 1.4 ] ), its elements + in wl2 have to follow the splitting. wl_splice() will take care of this. */ wlin = wl; - while(wl){ - argument = wl->wl_word; - /* searching for '=' ... */ - i = 0; - while(argument[i]!='=' && argument[i]!='\0'){ - i++; - } - /* argument may be '=', then do nothing - or =token - or token= - or token1=token2 - ...and if found split argument into three chars and make a new wordlist */ - if(argument[i]!='\0'){ - /* We found '=' */ - eqfound = TRUE; - if (strlen(argument) == 1) { - wl = wl->wl_next; - step = -1; - wl2 = wlin; - } - else if (strlen(argument) > 1) { - arglist = TMALLOC(char*, 4); - arglist[3] = NULL; - arglist[0] = TMALLOC(char, i + 1); - arglist[2] = TMALLOC(char, strlen(&argument[i + 1]) + 1); - /* copy argument */ - strncpy(arglist[0], argument, (size_t) i); - arglist[0][i] = '\0'; - /* copy equal sign */ - arglist[1] = copy("="); - /* copy expression */ - strncpy(arglist[2],&argument[i+1],strlen(&argument[i+1])+1); + while (wl) { + argument = wl->wl_word; + /* searching for '=' ... */ + i = 0; + while (argument[i] != '=' && argument[i] != '\0') + i++; - /* create a new wordlist from array arglist */ - wl2 = wl_build(arglist); - /* combine wordlists into wl2, free wl */ - wl_splice(wl, wl2); - wl = NULL; - /* free arglist */ - for (n=0; n < 3; n++) tfree(arglist[n]); - tfree(arglist); - } - } else { - /* deal with 'altermod m1 vth0=0.7' by moving - forward beyond 'm1' */ - wl = wl->wl_next; - step++; + /* argument may be '=', then do nothing + or =token + or token= + or token1=token2 + ...and if found split argument into three chars and make a new wordlist */ + if (argument[i] != '\0') { + /* We found '=' */ + eqfound = TRUE; + if (strlen(argument) == 1) { + wl = wl->wl_next; + step = -1; + wl2 = wlin; + } else if (strlen(argument) > 1) { + arglist = TMALLOC(char*, 4); + arglist[3] = NULL; + arglist[0] = TMALLOC(char, i + 1); + arglist[2] = TMALLOC(char, strlen(&argument[i + 1]) + 1); + /* copy argument */ + strncpy(arglist[0], argument, (size_t) i); + arglist[0][i] = '\0'; + /* copy equal sign */ + arglist[1] = copy("="); + /* copy expression */ + strncpy(arglist[2], &argument[i+1], strlen(&argument[i+1])+1); + + /* create a new wordlist from array arglist */ + wl2 = wl_build(arglist); + /* combine wordlists into wl2, free wl */ + wl_splice(wl, wl2); + wl = NULL; + /* free arglist */ + for (n = 0; n < 3; n++) + tfree(arglist[n]); + tfree(arglist); } + } else { + /* deal with 'altermod m1 vth0=0.7' by moving + forward beyond 'm1' */ + wl = wl->wl_next; + step++; + } } - if(eqfound) { + if (eqfound) { /* step back in the wordlist, if we have moved forward, to catch 'm1' */ - for(n=step;n>0;n--) + for (n = step; n > 0; n--) wl2 = wl2->wl_prev; } else { - /* no equal sign found, probably a pre3f4 input format + /* no equal sign found, probably a pre3f4 input format 'alter device value' 'alter device parameter value' - are supported, + are supported, 'alter device parameter value parameter value [ parameter value ]' multiple param value pairs are not supported! */ @@ -1218,22 +1227,22 @@ com_alter_common(wordlist *wl, int do_model) /* Return the last element of wlin */ wlin = wl_nthelem(100, wlin); /* no more than 100 vector elements */ - if (eq(wlin->wl_word, "]"))/* we have a vector */ { - for (n=0;n<100;n++) {/* no more than 100 vector elements */ - wlin=wlin->wl_prev; - maxelem++; - if (eq(wlin->wl_word, "[")) { - vecfound = TRUE; - break; - } - if(wlin->wl_prev==NULL) { - fprintf(cp_err, "Error: '[' is missing.\n"); - fprintf(cp_err, "Cannot alter parameters.\n"); - return; - } - } - } - if(wlen > maxelem) { + if (eq(wlin->wl_word, "]")) /* we have a vector */ + for (n = 0; n < 100; n++) { /* no more than 100 vector elements */ + wlin = wlin->wl_prev; + maxelem++; + if (eq(wlin->wl_word, "[")) { + vecfound = TRUE; + break; + } + if (wlin->wl_prev == NULL) { + fprintf(cp_err, "Error: '[' is missing.\n"); + fprintf(cp_err, "Cannot alter parameters.\n"); + return; + } + } + + if (wlen > maxelem) { fprintf(cp_err, "Error: Only a single param - value pair supported.\n"); fprintf(cp_err, "Cannot alter parameters.\n"); return; @@ -1242,24 +1251,24 @@ com_alter_common(wordlist *wl, int do_model) wlin = wlin->wl_prev; rhs = wl_chop_rest(wlin); wlin = wl_append(wlin, wl_cons(copy("="), rhs)); - /* step back until 'alter' or 'altermod' is found, - then move one step forward */ - while (!ciprefix("alter",wlin->wl_word)) //while (!ciprefix(wlin->wl_word,"alter")) + /* step back until 'alter' or 'altermod' is found, + then move one step forward */ + while (!ciprefix("alter", wlin->wl_word)) //while (!ciprefix(wlin->wl_word, "alter")) wlin = wlin->wl_prev; wlin = wlin->wl_next; wl2 = wlin; } /* Everything is ready, parsing of the wordlist starts here. */ - words = wl2; + words = wl2; while (words) { p = words->wl_word; eqword = words; words = words->wl_next; - if (eq(p, "=")) { + if (eq(p, "=")) break; - } } + if (!words) { fprintf(cp_err, "Error: no assignment found.\n"); fprintf(cp_err, "Cannot alter parameters.\n"); @@ -1269,7 +1278,7 @@ com_alter_common(wordlist *wl, int do_model) /* device parameter = expr device = expr @dev[param] = expr - */ + */ dev = NULL; param = NULL; @@ -1277,17 +1286,16 @@ com_alter_common(wordlist *wl, int do_model) while (words != eqword) { p = words->wl_word; if (param) { - fprintf(cp_err, "Warning: excess parameter name \"%s\" ignored.\n", - p); + fprintf(cp_err, "Warning: excess parameter name \"%s\" ignored.\n", p); } else if (dev) { param = words->wl_word; } else if (*p == '@' || *p == '#') { dev = p + 1; - p =strchr(p, '['); + p = strchr(p, '['); if (p) { *p++ = 0; param = p; - p =strchr(p, ']'); + p = strchr(p, ']'); if (p) *p = 0; } @@ -1296,87 +1304,92 @@ com_alter_common(wordlist *wl, int do_model) } words = words->wl_next; } + if (!dev) { - fprintf(cp_err, "Error: no model or device name provided.\n" ); + fprintf(cp_err, "Error: no model or device name provided.\n"); fprintf(cp_err, "Cannot alter parameters.\n"); return; } words = eqword->wl_next; /* skip next line if words is a vector */ - if(!eq(words->wl_word, "[")) { + if (!eq(words->wl_word, "[")) names = ft_getpnames(words, FALSE); - } - else names = NULL; + else + names = NULL; + if (!names) { - /* Put this to try to resolve the case of - alter @vin[pulse] = [ 0 5 10n 10n 10n 50n 100n ] - */ - char *xsbuf; - int type = IF_REALVEC,i=0; - - double *list; - double tmp; - int error; - /* move beyond '[' to allow INPevaluate() */ - if(eq(words->wl_word, "[")) words = words->wl_next; - xsbuf = wl_flatten(words); - /* fprintf(cp_err, "Chain converted %s \n",xsbuf); */ - dv = TMALLOC(struct dvec, 1); - dv->v_name = copy("real vector"); - type &= IF_VARTYPES; - if (type == IF_REALVEC) { - list = TMALLOC(double, 1); - tmp = INPevaluate(&xsbuf,&error,1); - while (error == 0) - { - /*printf(" returning vector value %g\n",tmp); */ - i++; - list=TREALLOC(double, list, i); - *(list+i-1) = tmp; - tmp = INPevaluate(&xsbuf,&error,1); - } - dv->v_realdata=list; - } - dv->v_length=i; - - if (!dv) - return; - if (dv->v_length < 1) - { - fprintf(cp_err, "Error: cannot evaluate new parameter value.\n"); - return; - } - - /* Here I was, to change the inclusion in the circuit. - * will have to revise that dv is right for its insertion. + /* Put this to try to resolve the case of + alter @vin[pulse] = [ 0 5 10n 10n 10n 50n 100n ] */ - if_setparam(ft_curckt->ci_ckt, &dev, param, dv, do_model); + char *xsbuf; + int type = IF_REALVEC, i = 0; - return; + double *list; + double tmp; + int error; + /* move beyond '[' to allow INPevaluate() */ + if (eq(words->wl_word, "[")) + words = words->wl_next; + xsbuf = wl_flatten(words); + /* fprintf(cp_err, "Chain converted %s \n", xsbuf); */ + dv = TMALLOC(struct dvec, 1); + dv->v_name = copy("real vector"); + type &= IF_VARTYPES; + if (type == IF_REALVEC) { + list = TMALLOC(double, 1); + tmp = INPevaluate(&xsbuf, &error, 1); + while (error == 0) { + /*printf(" returning vector value %g\n", tmp); */ + i++; + list = TREALLOC(double, list, i); + *(list+i-1) = tmp; + tmp = INPevaluate(&xsbuf, &error, 1); + } + dv->v_realdata = list; + } + dv->v_length = i; + + if (!dv) + return; + + if (dv->v_length < 1) { + fprintf(cp_err, "Error: cannot evaluate new parameter value.\n"); + return; + } + + /* Here I was, to change the inclusion in the circuit. + * will have to revise that dv is right for its insertion. + */ + if_setparam(ft_curckt->ci_ckt, &dev, param, dv, do_model); + + return; } + dv = ft_evaluate(names); if (!dv) return; + if (dv->v_length < 1) { fprintf(cp_err, "Error: cannot evaluate new parameter value.\n"); return; } - /* If we want alter the geometry of a MOS device + /* If we want alter the geometry of a MOS device we have to ensure that we are in the valid model bin. */ - if ( (dev[0] == 'm') && ((param[0] == 'w') || (param[0] == 'l')) ) { + if ((dev[0] == 'm') && ((param[0] == 'w') || (param[0] == 'l'))) if_set_binned_model(ft_curckt->ci_ckt, dev, param, dv); - } if_setparam(ft_curckt->ci_ckt, &dev, param, dv, do_model); /* va: garbage collection for dv, if pnode names is no simple value */ - if (names->pn_value==NULL && dv!=NULL) vec_free(dv); + if (names->pn_value == NULL && dv != NULL) + vec_free(dv); free_pnode(names); /* free also dv, if pnode names is simple value */ return; } + /* Given a device name, possibly with wildcards, return the matches. */ static wordlist * @@ -1387,27 +1400,29 @@ devexpand(char *name) if (strchr(name, '*') || strchr(name, '[') || strchr(name, '?')) { devices = cp_cctowl(ft_curckt->ci_devices); for (wl = NULL; devices; devices = devices->wl_next) - if (cp_globmatch(name, devices->wl_word)) { + if (cp_globmatch(name, devices->wl_word)) wl = wl_cons(devices->wl_word, wl); - } } else if (cieq(name, "all")) { wl = cp_cctowl(ft_curckt->ci_devices); } else { wl = wl_cons(name, NULL); } + wl_sort(wl); return (wl); } + /* altermod mod_1 [mod_nn] file=modelparam.mod load model file and overwrite models mod_1 till mod_nn with all new parameters (limited to 16 models) */ -static void com_alter_mod(wordlist *wl) +static void +com_alter_mod(wordlist *wl) { #define MODLIM 16 /* max number of models */ FILE *modfile; - char *modellist[MODLIM]={NULL}, *modellines[MODLIM]={NULL}, *newmodelname, *newmodelline; - char *filename=NULL, *eqword, *input, *modelline=NULL, *inptoken; + char *modellist[MODLIM] = {NULL}, *modellines[MODLIM] = {NULL}, *newmodelname, *newmodelline; + char *filename = NULL, *eqword, *input, *modelline = NULL, *inptoken; int modno = 0, molineno = 0, i, j; wordlist *newcommand; struct line *modeldeck, *tmpdeck; @@ -1435,20 +1450,19 @@ static void com_alter_mod(wordlist *wl) eqword = strstr(input, "="); if (eqword) { eqword++; - while(*eqword == ' ') + while (*eqword == ' ') eqword++; - if(eqword=='\0') { + if (eqword == '\0') { fprintf(cp_err, "Error: no filename given\n"); controlled_exit(1); } filename = copy(eqword); - } - else { + } else { eqword = strstr(input, "file"); eqword += 4; - while(*eqword == ' ') + while (*eqword == ' ') eqword++; - if(eqword=='\0') { + if (eqword == '\0') { fprintf(cp_err, "Error: no filename given\n"); controlled_exit(1); } @@ -1465,7 +1479,7 @@ static void com_alter_mod(wordlist *wl) /* get all lines starting with *model */ for (tmpdeck = modeldeck; tmpdeck; tmpdeck = tmpdeck->li_next) if (ciprefix("*model", tmpdeck->li_line)) { - if (molineno == MODLIM){ + if (molineno == MODLIM) { fprintf(cp_err, "Error: more than %d models in deck, rest ignored\n", molineno); break; } @@ -1475,14 +1489,14 @@ static void com_alter_mod(wordlist *wl) /* Check if all models named in altermod command are to be found in input deck. Exit if not successfull */ for (i = 0; i < modno; i++) { - for (j=0; j < molineno; j++) { + for (j = 0; j < molineno; j++) { newmodelline = modellines[j]; /* get model name from model line */ inptoken = gettok(&newmodelline); /* *model */ tfree(inptoken); newmodelname = gettok(&newmodelline); /* modelname */ - if (cieq(newmodelname,modellist[i])) { - modelfound = TRUE; + if (cieq(newmodelname, modellist[i])) { + modelfound = TRUE; tfree(newmodelname); break; } @@ -1492,8 +1506,7 @@ static void com_alter_mod(wordlist *wl) modelfound = FALSE; ij[i] = j; /* model in altermod, found in model line */ continue; - } - else { + } else { fprintf(cp_err, "Error: could not find model %s in input deck\n", modellist[i]); controlled_exit(1); } diff --git a/src/frontend/diff.c b/src/frontend/diff.c index 7b9cd5759..adcbed8b3 100644 --- a/src/frontend/diff.c +++ b/src/frontend/diff.c @@ -24,46 +24,52 @@ nameeq(char *n1, char *n2) { char buf1[BSIZE_SP], buf2[BSIZE_SP]; char *tmp; - + if (eq(n1, n2)) return (TRUE); - - /* n1 or n2 is in the form i(...) or I(...) + /* n1 or n2 is in the form i(...) or I(...) * This happens in the saved rawfile */ - if(ciprefix("i(",n1)) { + if (ciprefix("i(", n1)) { tmp = n1; - while ( *tmp != '(' ) tmp++; + while (*tmp != '(') + tmp++; tmp++; - (void) strcpy(buf1, tmp); + (void) strcpy(buf1, tmp); tmp = buf1; - while ( *tmp != ')' ) tmp++; - *tmp ='\0'; + while (*tmp != ')') + tmp++; + *tmp = '\0'; (void) strcat(buf1, "#branch"); - } else if (isdigit(*n1)) - (void) sprintf(buf1, "v(%s)", n1); - else - (void) strcpy(buf1, n1); + } else if (isdigit(*n1)) { + (void) sprintf(buf1, "v(%s)", n1); + } else { + (void) strcpy(buf1, n1); + } - if(ciprefix("i(",n2)) { + if (ciprefix("i(", n2)) { tmp = n2; - while ( *tmp != '(' ) tmp++; + while (*tmp != '(') + tmp++; tmp++; - (void) strcpy(buf2, tmp); + (void) strcpy(buf2, tmp); tmp = buf2; - while ( *tmp != ')' ) tmp++; - *tmp ='\0'; + while (*tmp != ')') + tmp++; + *tmp = '\0'; (void) strcat(buf2, "#branch"); - } else if (isdigit(*n2)) - (void) sprintf(buf2, "v(%s)", n2); - else - (void) strcpy(buf2, n2); + } else if (isdigit(*n2)) { + (void) sprintf(buf2, "v(%s)", n2); + } else { + (void) strcpy(buf2, n2); + } return (cieq(buf1, buf2) ? TRUE : FALSE); } + void com_diff(wordlist *wl) { @@ -74,7 +80,7 @@ com_diff(wordlist *wl) ngcomplex_t c1, c2, c3; int i, j; wordlist *tw; - char numbuf[BSIZE_SP],numbuf2[BSIZE_SP] ,numbuf3[BSIZE_SP], numbuf4[BSIZE_SP]; /* For printnum */ + char numbuf[BSIZE_SP], numbuf2[BSIZE_SP], numbuf3[BSIZE_SP], numbuf4[BSIZE_SP]; /* For printnum */ if (!cp_getvar("diff_vntol", CP_REAL, &vntol)) vntol = 1.0e-6; @@ -85,12 +91,11 @@ com_diff(wordlist *wl) /* Let's try to be clever about defaults. This code is ugly. */ if (!wl || !wl->wl_next) { - if (plot_list && plot_list->pl_next && - !plot_list->pl_next->pl_next) { + if (plot_list && plot_list->pl_next && !plot_list->pl_next->pl_next) { p1 = plot_list; p2 = plot_list->pl_next; if (wl && !eq(wl->wl_word, p1->pl_typename) && - !eq(wl->wl_word, p2->pl_typename)) { + !eq(wl->wl_word, p2->pl_typename)) { fprintf(cp_err, "Error: no such plot \"%s\"\n", wl->wl_word); return; @@ -109,8 +114,7 @@ com_diff(wordlist *wl) if (eq(wl->wl_word, p1->pl_typename)) break; if (!p1) { - fprintf(cp_err, "Error: no such plot %s\n", - wl->wl_word); + fprintf(cp_err, "Error: no such plot %s\n", wl->wl_word); return; } wl = wl->wl_next; @@ -121,8 +125,7 @@ com_diff(wordlist *wl) if (eq(wl->wl_word, p2->pl_typename)) break; if (!p2) { - fprintf(cp_err, "Error: no such plot %s\n", - wl->wl_word); + fprintf(cp_err, "Error: no such plot %s\n", wl->wl_word); return; } wl = wl->wl_next; @@ -132,13 +135,13 @@ com_diff(wordlist *wl) * same type, etc. */ if (!eq(p1->pl_name, p2->pl_name)) - fprintf(cp_err, - "Warning: plots %s and %s seem to be of different types\n", - p1->pl_typename, p2->pl_typename); + fprintf(cp_err, + "Warning: plots %s and %s seem to be of different types\n", + p1->pl_typename, p2->pl_typename); if (!eq(p1->pl_title, p2->pl_title)) - fprintf(cp_err, - "Warning: plots %s and %s seem to be from different circuits\n", - p1->pl_typename, p2->pl_typename); + fprintf(cp_err, + "Warning: plots %s and %s seem to be from different circuits\n", + p1->pl_typename, p2->pl_typename); /* This may not be the best way to do this */ for (v1 = p1->pl_dvecs; v1; v1 = v1->v_next) @@ -146,32 +149,31 @@ com_diff(wordlist *wl) for (v2 = p2->pl_dvecs; v2; v2 = v2->v_next) v2->v_link2 = NULL; - for (v1 = p1->pl_dvecs; v1; v1 = v1->v_next) { + for (v1 = p1->pl_dvecs; v1; v1 = v1->v_next) for (v2 = p2->pl_dvecs; v2; v2 = v2->v_next) if (!v2->v_link2 && nameeq(v1->v_name, v2->v_name) && ((v1->v_flags & (VF_REAL | VF_COMPLEX)) == - (v2->v_flags & (VF_REAL | VF_COMPLEX))) && - (v1->v_type == v2->v_type)) { + (v2->v_flags & (VF_REAL | VF_COMPLEX))) && + (v1->v_type == v2->v_type)) + { v1->v_link2 = v2; v2->v_link2 = v1; break; } - } for (v1 = p1->pl_dvecs; v1; v1 = v1->v_next) if (!v1->v_link2) - fprintf(cp_err, - ">>> %s vector %s in %s not in %s, or of wrong type\n", + fprintf(cp_err, + ">>> %s vector %s in %s not in %s, or of wrong type\n", isreal(v1) ? "real" : "complex", - v1->v_name, p1->pl_typename, - p2->pl_typename); + v1->v_name, p1->pl_typename, p2->pl_typename); + for (v2 = p2->pl_dvecs; v2; v2 = v2->v_next) if (!v2->v_link2) - fprintf(cp_err, - ">>> %s vector %s in %s not in %s, or of wrong type\n", + fprintf(cp_err, + ">>> %s vector %s in %s not in %s, or of wrong type\n", isreal(v2) ? "real" : "complex", - v2->v_name, p2->pl_typename, - p1->pl_typename); + v2->v_name, p2->pl_typename, p1->pl_typename); /* Throw out the ones that aren't in the arg list */ if (wl && !eq(wl->wl_word, "all")) { /* Just in case */ @@ -192,7 +194,7 @@ com_diff(wordlist *wl) v2->v_link2 = NULL; } } - + /* Now we have all the vectors linked to their twins. Travel * down each one and print values that differ enough. */ @@ -207,35 +209,31 @@ com_diff(wordlist *wl) j = MAX(v1->v_length, v2->v_length); for (i = 0; i < j; i++) { if (v1->v_length <= i) { - fprintf(cp_out, - ">>> %s is %d long in %s and %d long in %s\n", + fprintf(cp_out, + ">>> %s is %d long in %s and %d long in %s\n", v1->v_name, v1->v_length, - p1->pl_typename, v2->v_length, - p2->pl_typename); + p1->pl_typename, v2->v_length, p2->pl_typename); break; } else if (v2->v_length <= i) { - fprintf(cp_out, - ">>> %s is %d long in %s and %d long in %s\n", + fprintf(cp_out, + ">>> %s is %d long in %s and %d long in %s\n", v2->v_name, v2->v_length, - p2->pl_typename, v1->v_length, - p1->pl_typename); + p2->pl_typename, v1->v_length, p1->pl_typename); break; } else { if (isreal(v1)) { d1 = v1->v_realdata[i]; d2 = v2->v_realdata[i]; if (MAX(fabs(d1), fabs(d2)) * reltol + - tol < fabs(d1 - d2)) { - printnum(numbuf, d1); + tol < fabs(d1 - d2)) { + printnum(numbuf, d1); fprintf(cp_out, - "%s.%s[%d] = %-15s ", - p1->pl_typename, v1->v_name, i, - numbuf); + "%s.%s[%d] = %-15s ", + p1->pl_typename, v1->v_name, i, numbuf); printnum(numbuf, d2); fprintf(cp_out, - "%s.%s[%d] = %s\n", - p2->pl_typename, v2->v_name, i, - numbuf); + "%s.%s[%d] = %s\n", + p2->pl_typename, v2->v_name, i, numbuf); } } else { c1 = v1->v_compdata[i]; @@ -246,22 +244,21 @@ com_diff(wordlist *wl) cm1 = cmag(c1); cm2 = cmag(c2); cmax = MAX(cm1, cm2); - if (cmax * reltol + - tol < cmag(c3)) { - - printnum(numbuf, realpart(c1)); + if (cmax * reltol + tol < cmag(c3)) { + + printnum(numbuf, realpart(c1)); printnum(numbuf2, imagpart(c1)); printnum(numbuf3, realpart(c2)); printnum(numbuf4, imagpart(c2)); - + fprintf(cp_out, - "%s.%s[%d] = %-10s, %-10s %s.%s[%d] = %-10s, %s\n", - p1->pl_typename, v1->v_name, i, - numbuf, - numbuf2, - p2->pl_typename, v2->v_name, i, - numbuf3, - numbuf4); + "%s.%s[%d] = %-10s, %-10s %s.%s[%d] = %-10s, %s\n", + p1->pl_typename, v1->v_name, i, + numbuf, + numbuf2, + p2->pl_typename, v2->v_name, i, + numbuf3, + numbuf4); } } } diff --git a/src/frontend/dimens.c b/src/frontend/dimens.c index ed61a4951..23e08a7ec 100644 --- a/src/frontend/dimens.c +++ b/src/frontend/dimens.c @@ -8,7 +8,7 @@ Author: 1992 David A. Gates, U. C. Berkeley CAD Group */ #include "ngspice/ngspice.h" -#include "ngspice/dvec.h" /* For MAXDIMS */ +#include "ngspice/dvec.h" /* For MAXDIMS */ #include "dimens.h" @@ -18,42 +18,45 @@ Author: 1992 David A. Gates, U. C. Berkeley CAD Group void dimstring(int *data, int length, char *retstring) { - int i; + int i; char buf[BSIZE_SP]; - + if (!data || length < 1) - retstring = ""; + retstring = ""; buf[0] = '\0'; - for (i=0; i < length; i++) { - sprintf(buf + strlen(buf), "%d%s", data[i], - (i < length - 1) ? "," : ""); - } + + for (i = 0; i < length; i++) + sprintf(buf + strlen(buf), "%d%s", data[i], (i < length - 1) ? "," : ""); + /* XXX Should I return a copy instead? */ /* qui ci devo fare una copia */ strcpy(retstring, buf); } + /* * Create a string of the form "[12][1][10]". */ void indexstring(int *data, int length, char *retstring) { - int i; + int i; char buf[BSIZE_SP]; if (!data || length < 1) - retstring = ""; + retstring = ""; buf[0] = '\0'; - for (i=0; i < length; i++) { - sprintf(buf + strlen(buf), "[%d]", data[i]); - } + + for (i = 0; i < length; i++) + sprintf(buf + strlen(buf), "[%d]", data[i]); + strcpy(retstring, buf); } + /* * Add one to anstrchr into an array with sizes in dims. * Return 1 when all counters overflow at once. @@ -64,21 +67,23 @@ incindex(int *counts, int numcounts, int *dims, int numdims) int i, start; if (!counts || numcounts < 1 || !dims || numdims < 1) - return 0; + return 0; start = numcounts - 1; - for (i = start; i >= 0; i--) { - if (++counts[i] < dims[i]) - break; /* This counter is not maxed out. */ - else - counts[i] = 0; - } + + for (i = start; i >= 0; i--) + if (++counts[i] < dims[i]) + break; /* This counter is not maxed out. */ + else + counts[i] = 0; + if (i == 0) - return(1); + return (1); else - return(0); + return (0); } + /* * Count number of empty dimensions in an array. */ @@ -87,13 +92,14 @@ emptydims(int *data, int length) { int i, numempty = 0; - for (i=0; i < length; i++) { - if (data[i] == 0) - numempty++; - } - return(numempty); + for (i = 0; i < length; i++) + if (data[i] == 0) + numempty++; + + return (numempty); } + /* * Read a string of one of the following forms into a dimensions array: * [12][1][10] @@ -106,7 +112,7 @@ emptydims(int *data, int length) * the beginning [ and end ] are ignored if they exist. The only valid * characters in the string are brackets, commas, spaces, and digits. * If any dimension is blank, its entry in the array is set to 0. - * + * * Return 0 on success, 1 on failure. */ int @@ -119,86 +125,90 @@ atodims(char *p, int *data, int *outlength) char sep = '\0'; if (!data || !outlength) - return 1; + return 1; if (!p) { - *outlength = 0; - return 0; + *outlength = 0; + return 0; } while (*p && isspace(*p)) - p++; + p++; if (*p == '[') { - p++; - while (*p && isspace(*p)) - p++; - needbracket = 1; + p++; + while (*p && isspace(*p)) + p++; + needbracket = 1; } while (*p && state != 3) { - switch (state) { - case 0: /* p just at or before a number */ - if (length >= MAXDIMS) { - if (length == MAXDIMS) - printf("Error: maximum of %d dimensions allowed.\n", - MAXDIMS); - length += 1; - } else if (!isdigit(*p)) { - data[length++] = 0; /* This position was empty. */ - } else { - data[length++] = atoi(p); - while (isdigit(*p)) - p++; - } - state = 1; - break; + switch (state) { + case 0: /* p just at or before a number */ + if (length >= MAXDIMS) { + if (length == MAXDIMS) + printf("Error: maximum of %d dimensions allowed.\n", + MAXDIMS); + length += 1; + } else if (!isdigit(*p)) { + data[length++] = 0; /* This position was empty. */ + } else { + data[length++] = atoi(p); + while (isdigit(*p)) + p++; + } + state = 1; + break; - case 1: /* p after a number, looking for ',' or ']' */ - if (sep == '\0') { - sep = *p; - } - if (*p == ']' && *p == sep) { - p++; - state = 2; - } else if (*p == ',' && *p == sep) { - p++; - state = 0; - } else /* Funny character following a # */ - break; - break; + case 1: /* p after a number, looking for ',' or ']' */ + if (sep == '\0') + sep = *p; - case 2: /* p after a ']', either at the end or looking for '[' */ - if (*p == '[') { - p++; - state = 0; - } else { - state = 3; - } - break; - } + if (*p == ']' && *p == sep) { + p++; + state = 2; + } else if (*p == ',' && *p == sep) { + p++; + state = 0; + } else { /* Funny character following a # */ + break; + } + break; - while (*p && isspace(*p)) - p++; + case 2: /* p after a ']', either at the end or looking for '[' */ + if (*p == '[') { + p++; + state = 0; + } else { + state = 3; + } + break; + } + + while (*p && isspace(*p)) + p++; } *outlength = length; - if (length > MAXDIMS) { - return(1); - } + + if (length > MAXDIMS) + return (1); + if (state == 3) { /* We finished with a closing bracket */ - err = !needbracket; + err = !needbracket; } else if (*p) { /* We finished by hitting a bad character after a # */ - err = 1; - } else { /* We finished by exhausting the string */ - err = needbracket; + err = 1; + } else { /* We finished by exhausting the string */ + err = needbracket; } - if (err) { - *outlength = 0; - } - return(err); + + if (err) + *outlength = 0; + + return (err); } + /* * Skip to the first character that cannot be part of a dimension string. */ @@ -206,11 +216,10 @@ char * skipdims(char *p) { if (!p) - return NULL; + return NULL; - while(*p && (*p == '[' || *p == ']' || *p == ',' - || isspace(*p) || isdigit(*p))) - p++; + while (*p && (*p == '[' || *p == ']' || *p == ',' || isspace(*p) || isdigit(*p))) + p++; - return(p); + return (p); } diff --git a/src/frontend/dimens.h b/src/frontend/dimens.h index 269d0bae3..029992910 100644 --- a/src/frontend/dimens.h +++ b/src/frontend/dimens.h @@ -11,8 +11,6 @@ void indexstring(int *data, int length, char *retstring); int incindex(int *counts, int numcounts, int *dims, int numdims); int emptydims(int *data, int length); int atodims(char *p, int *data, int *outlength); -char * skipdims(char *p); - - +char *skipdims(char *p); #endif diff --git a/src/frontend/display.c b/src/frontend/display.c index 15fd86c74..4d8fac37b 100644 --- a/src/frontend/display.c +++ b/src/frontend/display.c @@ -139,14 +139,14 @@ FindDev(char *name) { size_t i; - for (i=0; i < NUMELEMS(device); i++) + for (i = 0; i < NUMELEMS(device); i++) if (strcmp(name, device[i].name) == 0) - return(device + i); + return (device + i); sprintf(ErrorMessage, "Can't find device %s.", name); internalerror(ErrorMessage); - return(device + 0); + return (device + 0); } @@ -190,15 +190,15 @@ DevInit(void) #if !defined(HAS_WINDOWS) && !defined(TCL_MODULE) && (defined(_MSC_VER) || defined(__MINGW32__)) /* console application under MS Windows */ fprintf - ( cp_err, - "Warning: no graphics interface!\n" - " You may use command 'gnuplot'\n" - " if GnuPlot is installed.\n" ); + (cp_err, + "Warning: no graphics interface!\n" + " You may use command 'gnuplot'\n" + " if GnuPlot is installed.\n"); #elif !defined(X_DISPLAY_MISSING) externalerror - ( "no graphics interface;\n" - " please check if X-server is running,\n" - " or ngspice is compiled properly (see INSTALL)" ); + ("no graphics interface;\n" + " please check if X-server is running,\n" + " or ngspice is compiled properly (see INSTALL)"); #endif dispdev = FindDev("error"); @@ -218,61 +218,71 @@ NewViewport(GRAPH *pgraph) } -void DevClose(void) +void +DevClose(void) { dispdev->Close(); } -void DevClear(void) +void +DevClear(void) { dispdev->Clear(); } -void DevDrawLine(int x1, int y1, int x2, int y2) +void +DevDrawLine(int x1, int y1, int x2, int y2) { dispdev->DrawLine (x1, y1, x2, y2); } -void DevDrawArc(int x0, int y0, int radius, double theta, double delta_theta) +void +DevDrawArc(int x0, int y0, int radius, double theta, double delta_theta) { dispdev->DrawArc (x0, y0, radius, theta, delta_theta); } -void DevDrawText(char *text, int x, int y) +void +DevDrawText(char *text, int x, int y) { dispdev->DrawText (text, x, y); } -void DefineColor(int colorid, double red, double green, double blue) +void +DefineColor(int colorid, double red, double green, double blue) { dispdev->DefineColor (colorid, red, green, blue); } -void DefineLinestyle(int linestyleid, int mask) +void +DefineLinestyle(int linestyleid, int mask) { dispdev->DefineLinestyle (linestyleid, mask); } -void SetLinestyle(int linestyleid) +void +SetLinestyle(int linestyleid) { dispdev->SetLinestyle (linestyleid); } -void SetColor(int colorid) +void +SetColor(int colorid) { dispdev->SetColor (colorid); } -void DevUpdate(void) +void +DevUpdate(void) { if (dispdev) dispdev->Update(); @@ -322,13 +332,15 @@ gen_DatatoScreen(GRAPH *graph, double x, double y, int *screenx, int *screeny) } -void DatatoScreen(GRAPH *graph, double x, double y, int *screenx, int *screeny) +void +DatatoScreen(GRAPH *graph, double x, double y, int *screenx, int *screeny) { dispdev->DatatoScreen (graph, x, y, screenx, screeny); } -void Input(REQUEST *request, RESPONSE *response) +void +Input(REQUEST *request, RESPONSE *response) { dispdev->Input (request, response); } @@ -349,28 +361,31 @@ gen_Input(REQUEST *request, RESPONSE *response) break; } - return(0); + return (0); } /* no operation, do nothing */ -static int nop(void) +static int +nop(void) { - return(1); /* so NewViewport will fail */ + return (1); /* so NewViewport will fail */ } -static int nodev(void) +static int +nodev(void) { sprintf(ErrorMessage, "This operation is not defined for display type %s.", dispdev->name); internalerror(ErrorMessage); - return(1); + return (1); } -void SaveText(GRAPH *graph, char *text, int x, int y) +void +SaveText(GRAPH *graph, char *text, int x, int y) { struct _keyed *keyed = TMALLOC(struct _keyed, 1); @@ -393,7 +408,8 @@ void SaveText(GRAPH *graph, char *text, int x, int y) /* if given name of a hardcopy device, finds it and switches devices if given NULL, switches back */ -int DevSwitch(char *devname) +int +DevSwitch(char *devname) { static DISPDEVICE *lastdev = NULL; @@ -426,5 +442,5 @@ int DevSwitch(char *devname) } - return(0); + return (0); } diff --git a/src/frontend/dotcards.c b/src/frontend/dotcards.c index 9acace659..c859890cd 100644 --- a/src/frontend/dotcards.c +++ b/src/frontend/dotcards.c @@ -30,7 +30,7 @@ Modified: 2000 AlansFixes static void fixdotplot(wordlist *wl); static void fixdotprint(wordlist *wl); -static char * fixem(char *string); +static char *fixem(char *string); void ft_savemeasure(void); @@ -39,14 +39,14 @@ setcplot(char *name) { struct plot *pl; - for (pl = plot_list; pl; pl = pl->pl_next) { - if (ciprefix(name, pl->pl_typename)) { + for (pl = plot_list; pl; pl = pl->pl_next) + if (ciprefix(name, pl->pl_typename)) return pl; - } - } + return NULL; } + /* All lines with .width, .plot, .print, .save, .op, .meas, .tf have been assembled into a wordlist (wl_first) in inp.c:inp_spsource(), and then stored to ci_commands in inp.c:inp_dodeck(). @@ -62,119 +62,120 @@ ft_dotsaves(void) if (!ft_curckt) /* Shouldn't happen. */ return; - for (iline = ft_curckt->ci_commands; iline; iline = iline->wl_next) { + for (iline = ft_curckt->ci_commands; iline; iline = iline->wl_next) if (ciprefix(".save", iline->wl_word)) { s = iline->wl_word; (void) gettok(&s); wl = wl_append(wl, gettoks(s)); } - } com_save(wl); return; } + /* Go through the dot lines given and make up a big "save" command with * all the node names mentioned. Note that if a node is requested for * one analysis, it is saved for all of them. */ static char *plot_opts[ ] = { - "linear", - "xlog", - "ylog", - "loglog" - }; + "linear", + "xlog", + "ylog", + "loglog" +}; + int ft_savedotargs(void) { - wordlist *w, *wl = NULL, *iline, **prev_wl, *w_next; - char *name; - char *s; - int some = 0; - static wordlist all = { "all", NULL, NULL }; - int isaplot; - int i; - int status; + wordlist *w, *wl = NULL, *iline, **prev_wl, *w_next; + char *name; + char *s; + int some = 0; + static wordlist all = { "all", NULL, NULL }; + int isaplot; + int i; + int status; - if (!ft_curckt) /* Shouldn't happen. */ - return 0; + if (!ft_curckt) /* Shouldn't happen. */ + return 0; - for (iline = ft_curckt->ci_commands; iline; iline = iline->wl_next) { - s = iline->wl_word; - if (ciprefix(".plot", s)) - isaplot = 1; - else - isaplot = 0; + for (iline = ft_curckt->ci_commands; iline; iline = iline->wl_next) { + s = iline->wl_word; + if (ciprefix(".plot", s)) + isaplot = 1; + else + isaplot = 0; - if (isaplot || ciprefix(".print", s)) { - (void) gettok(&s); - name = gettok(&s); + if (isaplot || ciprefix(".print", s)) { + (void) gettok(&s); + name = gettok(&s); - if ((w = gettoks(s)) == NULL) { - fprintf(cp_err, "Warning: no nodes given: %s\n", iline->wl_word); - } else { - if (isaplot) { - prev_wl = &w; - for (wl = w; wl; wl = w_next) { - w_next = wl->wl_next; - for (i = 0; (size_t) i < NUMELEMS(plot_opts); i++) { - if (!strcmp(wl->wl_word, plot_opts[i])) { - /* skip it */ - *prev_wl = w_next; - tfree(wl); - break; - } - } - if (i == NUMELEMS(plot_opts)) - prev_wl = &wl->wl_next; - } + if ((w = gettoks(s)) == NULL) { + fprintf(cp_err, "Warning: no nodes given: %s\n", iline->wl_word); + } else { + if (isaplot) { + prev_wl = &w; + for (wl = w; wl; wl = w_next) { + w_next = wl->wl_next; + for (i = 0; (size_t) i < NUMELEMS(plot_opts); i++) { + if (!strcmp(wl->wl_word, plot_opts[i])) { + /* skip it */ + *prev_wl = w_next; + tfree(wl); + break; + } + } + if (i == NUMELEMS(plot_opts)) + prev_wl = &wl->wl_next; + } + } + some = 1; + com_save2(w, name); } + } else if (ciprefix(".four", s)) { + (void) gettok(&s); + (void) gettok(&s); + if ((w = gettoks(s)) == NULL) { + fprintf(cp_err, "Warning: no nodes given: %s\n", iline->wl_word); + } else { + some = 1; + com_save2(w, "TRAN"); /* A hack */ + } + } else if (ciprefix(".meas", s)) { + status = measure_extract_variables(s); + if (!(status)) { + some = 1; + } + } else if (ciprefix(".op", s)) { some = 1; - com_save2(w, name); - } - } else if (ciprefix(".four", s)) { - (void) gettok(&s); - (void) gettok(&s); - if ((w = gettoks(s)) == NULL) - fprintf(cp_err, "Warning: no nodes given: %s\n", iline->wl_word); - else { + com_save2(&all, "OP"); + } else if (ciprefix(".tf", s)) { some = 1; - com_save2(w, "TRAN"); /* A hack */ - } - } else if (ciprefix(".meas", s)) { - status = measure_extract_variables( s ) ; - if(!(status)){ - some = 1; - } - } else if (ciprefix(".op", s)) { - some = 1; - com_save2(&all, "OP"); - } else if (ciprefix(".tf", s)) { - some = 1; - com_save2(&all, "TF"); - } - } - return some; + com_save2(&all, "TF"); + } + } + return some; } void ft_savemeasure(void) { - char *s; - wordlist *iline; + char *s; + wordlist *iline; - if (!ft_curckt) /* Shouldn't happen. */ - return ; + if (!ft_curckt) /* Shouldn't happen. */ + return; - for (iline = ft_curckt->ci_commands; iline; iline = iline->wl_next) { - s = iline->wl_word; - if (ciprefix(".measure", s)) { - (void) measure_extract_variables( s ) ; - } - } - return ; + for (iline = ft_curckt->ci_commands; iline; iline = iline->wl_next) { + s = iline->wl_word; + if (ciprefix(".measure", s)) { + (void) measure_extract_variables(s); + } + } + return; } /* Execute the .whatever lines found in the deck, after we are done running. @@ -189,7 +190,7 @@ ft_cktcoms(bool terse) wordlist *coms, *command, all; char *plottype, *s; struct dvec *v; - static wordlist twl = { "col", NULL, NULL } ; + static wordlist twl = { "col", NULL, NULL }; struct plot *pl; int i, found; char numbuf[BSIZE_SP]; /* For printnum*/ @@ -198,7 +199,7 @@ ft_cktcoms(bool terse) all.wl_word = "all"; if (!ft_curckt) - return 1; + return 1; plot_cur = setcplot("op"); if (!ft_curckt->ci_commands && !plot_cur) @@ -208,64 +209,62 @@ ft_cktcoms(bool terse) /* Listing */ if (ft_listprint) { - if (terse) - fprintf(cp_err, ".options: no listing, rawfile was generated.\n"); - else - inp_list(cp_out, ft_curckt->ci_deck, ft_curckt->ci_options, - LS_DECK); + if (terse) + fprintf(cp_err, ".options: no listing, rawfile was generated.\n"); + else + inp_list(cp_out, ft_curckt->ci_deck, ft_curckt->ci_options, LS_DECK); } /* If there was a .op line, then we have to do the .op output. */ plot_cur = setcplot("op"); if (plot_cur != NULL) { - assert(plot_cur->pl_dvecs != NULL); - if (plot_cur->pl_dvecs->v_realdata!=NULL) { - if (terse) { - fprintf(cp_out, "OP information in rawfile.\n"); - } else { - fprintf(cp_out, "\t%-30s%15s\n", "Node", "Voltage"); - fprintf(cp_out, "\t%-30s%15s\n", "----", "-------"); - fprintf(cp_out, "\t----\t-------\n"); - for (v = plot_cur->pl_dvecs; v; v = v->v_next) { - if (!isreal(v)) { - fprintf(cp_err, - "Internal error: op vector %s not real\n", - v->v_name); - continue; - } - if ((v->v_type == SV_VOLTAGE) && (*(v->v_name)!='@')) { - printnum(numbuf, v->v_realdata[0]); - fprintf(cp_out, "\t%-30s%15s\n", v->v_name, numbuf); - } - } - fprintf(cp_out, "\n\tSource\tCurrent\n"); - fprintf(cp_out, "\t------\t-------\n\n"); - for (v = plot_cur->pl_dvecs; v; v = v->v_next) - if (v->v_type == SV_CURRENT) { - printnum(numbuf, v->v_realdata[0]); - fprintf(cp_out, "\t%-30s%15s\n", v->v_name, numbuf); - } - fprintf(cp_out, "\n"); + assert(plot_cur->pl_dvecs != NULL); + if (plot_cur->pl_dvecs->v_realdata != NULL) { + if (terse) { + fprintf(cp_out, "OP information in rawfile.\n"); + } else { + fprintf(cp_out, "\t%-30s%15s\n", "Node", "Voltage"); + fprintf(cp_out, "\t%-30s%15s\n", "----", "-------"); + fprintf(cp_out, "\t----\t-------\n"); + for (v = plot_cur->pl_dvecs; v; v = v->v_next) { + if (!isreal(v)) { + fprintf(cp_err, + "Internal error: op vector %s not real\n", + v->v_name); + continue; + } + if ((v->v_type == SV_VOLTAGE) && (*(v->v_name) != '@')) { + printnum(numbuf, v->v_realdata[0]); + fprintf(cp_out, "\t%-30s%15s\n", v->v_name, numbuf); + } + } + fprintf(cp_out, "\n\tSource\tCurrent\n"); + fprintf(cp_out, "\t------\t-------\n\n"); + for (v = plot_cur->pl_dvecs; v; v = v->v_next) + if (v->v_type == SV_CURRENT) { + printnum(numbuf, v->v_realdata[0]); + fprintf(cp_out, "\t%-30s%15s\n", v->v_name, numbuf); + } + fprintf(cp_out, "\n"); - if (!ft_nomod) - com_showmod(&all); - com_show(&all); - } - } + if (!ft_nomod) + com_showmod(&all); + com_show(&all); + } + } } - for (pl = plot_list; pl; pl = pl->pl_next) { + for (pl = plot_list; pl; pl = pl->pl_next) if (ciprefix("tf", pl->pl_typename)) { - if (terse) { - fprintf(cp_out, "TF information in rawfile.\n"); - break; - } + if (terse) { + fprintf(cp_out, "TF information in rawfile.\n"); + break; + } plot_cur = pl; - fprintf(cp_out, "Transfer function information:\n"); - com_print(&all); - fprintf(cp_out, "\n"); - } - } + fprintf(cp_out, "Transfer function information:\n"); + com_print(&all); + fprintf(cp_out, "\n"); + } /* Now all the '.' lines */ while (coms) { @@ -273,11 +272,11 @@ ft_cktcoms(bool terse) if (!command) goto bad; if (eq(command->wl_word, ".width")) { - do { + do command = command->wl_next; - } while (command && !ciprefix("out", command->wl_word)); + while (command && !ciprefix("out", command->wl_word)); if (command) { - s =strchr(command->wl_word, '='); + s = strchr(command->wl_word, '='); if (!s || !s[1]) { fprintf(cp_err, "Error: bad line %s\n", coms->wl_word); coms = coms->wl_next; @@ -288,8 +287,8 @@ ft_cktcoms(bool terse) } } else if (eq(command->wl_word, ".print")) { if (terse) { - fprintf(cp_out, - ".print line ignored since rawfile was produced.\n"); + fprintf(cp_out, + ".print line ignored since rawfile was produced.\n"); } else { command = command->wl_next; if (!command) { @@ -301,23 +300,22 @@ ft_cktcoms(bool terse) command = command->wl_next; fixdotprint(command); twl.wl_next = command; - found = 0; - for (pl = plot_list; pl; pl = pl->pl_next) { - if (ciprefix(plottype, pl->pl_typename)) { - plot_cur = pl; - com_print(&twl); - fprintf(cp_out, "\n"); - found = 1; - } - } + found = 0; + for (pl = plot_list; pl; pl = pl->pl_next) + if (ciprefix(plottype, pl->pl_typename)) { + plot_cur = pl; + com_print(&twl); + fprintf(cp_out, "\n"); + found = 1; + } if (!found) fprintf(cp_err, "Error: .print: no %s analysis found.\n", - plottype); + plottype); } } else if (eq(command->wl_word, ".plot")) { if (terse) { - fprintf(cp_out, - ".plot line ignored since rawfile was produced.\n"); + fprintf(cp_out, + ".plot line ignored since rawfile was produced.\n"); } else { command = command->wl_next; if (!command) { @@ -329,23 +327,22 @@ ft_cktcoms(bool terse) plottype = command->wl_word; command = command->wl_next; fixdotplot(command); - found = 0; - for (pl = plot_list; pl; pl = pl->pl_next) { - if (ciprefix(plottype, pl->pl_typename)) { - plot_cur = pl; - com_asciiplot(command); - fprintf(cp_out, "\n"); - found = 1; - } - } + found = 0; + for (pl = plot_list; pl; pl = pl->pl_next) + if (ciprefix(plottype, pl->pl_typename)) { + plot_cur = pl; + com_asciiplot(command); + fprintf(cp_out, "\n"); + found = 1; + } if (!found) fprintf(cp_err, "Error: .plot: no %s analysis found.\n", - plottype); + plottype); } } else if (ciprefix(".four", command->wl_word)) { if (terse) { - fprintf(cp_out, - ".fourier line ignored since rawfile was produced.\n"); + fprintf(cp_out, + ".fourier line ignored since rawfile was produced.\n"); } else { int err; @@ -355,25 +352,25 @@ ft_cktcoms(bool terse) fprintf(cp_out, "\n\n"); else fprintf(cp_err, "No transient data available for " - "fourier analysis"); + "fourier analysis"); } - } else if (!eq(command->wl_word, ".save") - && !eq(command->wl_word, ".op") -// && !eq(command->wl_word, ".measure") - && !ciprefix(".meas", command->wl_word) - && !eq(command->wl_word, ".tf")) + } else if (!eq(command->wl_word, ".save") && + !eq(command->wl_word, ".op") && + // !eq(command->wl_word, ".measure") && + !ciprefix(".meas", command->wl_word) && + !eq(command->wl_word, ".tf")) { goto bad; } coms = coms->wl_next; } - nocmds: +nocmds: /* Now the node table - if (ft_nodesprint) - ; + if (ft_nodesprint) + ; */ - + /* The options */ if (ft_optsprint) { fprintf(cp_out, "Options:\n\n"); @@ -383,20 +380,22 @@ ft_cktcoms(bool terse) /* And finally the accounting info. */ if (ft_acctprint) { - static wordlist ww = { "everything", NULL, NULL } ; + static wordlist ww = { "everything", NULL, NULL }; com_rusage(&ww); - } else if ((!ft_noacctprint) && (!ft_acctprint)) + } else if ((!ft_noacctprint) && (!ft_acctprint)) { com_rusage(NULL); + } /* absolutely no accounting if noacct is given */ - + putc('\n', cp_out); return 0; - bad: +bad: fprintf(cp_err, "Internal Error: ft_cktcoms: bad commands\n"); return 1; } + /* These routines make sure that the arguments to .plot and .print in * spice2 decks are acceptable to spice3. The things we look for are: * trailing (a,b) in .plot -> xlimit a b @@ -425,7 +424,7 @@ fixdotplot(wordlist *wl) if (*s != ',') { fprintf(cp_err, "Error: bad limits \"%s\"\n", wl->wl_word); - return; + return; } d1 = *d; s++; @@ -433,7 +432,7 @@ fixdotplot(wordlist *wl) if ((*s != /*(*/ ')') || s[1]) { fprintf(cp_err, "Error: bad limits \"%s\"\n", wl->wl_word); - return; + return; } d2 = *d; tfree(wl->wl_word); @@ -448,6 +447,7 @@ fixdotplot(wordlist *wl) return; } + static void fixdotprint(wordlist *wl) { @@ -458,6 +458,7 @@ fixdotprint(wordlist *wl) return; } + static char * fixem(char *string) { @@ -465,53 +466,92 @@ fixem(char *string) char *ss = string; /* Get rid of ss ? */ if (ciprefix("v(", string) &&strchr(string, ',')) { - for (s = string; *s && (*s != ','); s++) ; *s++ = '\0'; - for (t = s; *t && (*t != ')'); t++) ; *t = '\0'; - if (eq(s, "0")) (void) sprintf(buf, "v(%s)", string + 2); + for (s = string; *s && (*s != ','); s++) + ; + *s++ = '\0'; + for (t = s; *t && (*t != ')'); t++) + ; + *t = '\0'; + if (eq(s, "0")) + (void) sprintf(buf, "v(%s)", string + 2); else if (eq(string + 2, "0")) - (void) sprintf(buf, "-v(%s)", s); - else (void) sprintf(buf, "v(%s)-v(%s)", string + 2, s); + (void) sprintf(buf, "-v(%s)", s); + else + (void) sprintf(buf, "v(%s)-v(%s)", string + 2, s); } else if (ciprefix("vm(", string) &&strchr(string, ',')) { - for (s = string; *s && (*s != ','); s++) ; *s++ = '\0'; - for (t = s; *t && (*t != ')'); t++) ; *t = '\0'; - if (eq(s, "0")) (void) sprintf(buf, "mag(v(%s))", string + 3); + for (s = string; *s && (*s != ','); s++) + ; + *s++ = '\0'; + for (t = s; *t && (*t != ')'); t++) + ; + *t = '\0'; + if (eq(s, "0")) + (void) sprintf(buf, "mag(v(%s))", string + 3); else if (eq(string + 3, "0")) - (void) sprintf(buf, "mag(-v(%s))", s); - else (void) sprintf(buf, "mag(v(%s)-v(%s))", string + 3, s); + (void) sprintf(buf, "mag(-v(%s))", s); + else + (void) sprintf(buf, "mag(v(%s)-v(%s))", string + 3, s); } else if (ciprefix("vp(", string) &&strchr(string, ',')) { - for (s = string; *s && (*s != ','); s++) ; *s++ = '\0'; - for (t = s; *t && (*t != ')'); t++) ; *t = '\0'; - if (eq(s, "0")) (void) sprintf(buf, "ph(v(%s))", string + 3); + for (s = string; *s && (*s != ','); s++) + ; + *s++ = '\0'; + for (t = s; *t && (*t != ')'); t++) + ; + *t = '\0'; + if (eq(s, "0")) + (void) sprintf(buf, "ph(v(%s))", string + 3); else if (eq(string + 3, "0")) - (void) sprintf(buf, "ph(-v(%s))", s); - else (void) sprintf(buf, "ph(v(%s)-v(%s))", string + 3, s); + (void) sprintf(buf, "ph(-v(%s))", s); + else + (void) sprintf(buf, "ph(v(%s)-v(%s))", string + 3, s); } else if (ciprefix("vi(", string) &&strchr(string, ',')) { - for (s = string; *s && (*s != ','); s++) ; *s++ = '\0'; - for (t = s; *t && (*t != ')'); t++) ; *t = '\0'; - if (eq(s, "0")) (void) sprintf(buf, "imag(v(%s))", string + 3); + for (s = string; *s && (*s != ','); s++) + ; + *s++ = '\0'; + for (t = s; *t && (*t != ')'); t++) + ; + *t = '\0'; + if (eq(s, "0")) + (void) sprintf(buf, "imag(v(%s))", string + 3); else if (eq(string + 3, "0")) - (void) sprintf(buf, "imag(-v(%s))", s); - else (void) sprintf(buf, "imag(v(%s)-v(%s))", string + 3, s); + (void) sprintf(buf, "imag(-v(%s))", s); + else + (void) sprintf(buf, "imag(v(%s)-v(%s))", string + 3, s); } else if (ciprefix("vr(", string) &&strchr(string, ',')) { - for (s = string; *s && (*s != ','); s++) ; *s++ = '\0'; - for (t = s; *t && (*t != ')'); t++) ; *t = '\0'; - if (eq(s, "0")) (void) sprintf(buf, "real(v(%s))", string + 3); + for (s = string; *s && (*s != ','); s++) + ; + *s++ = '\0'; + for (t = s; *t && (*t != ')'); t++) + ; + *t = '\0'; + if (eq(s, "0")) + (void) sprintf(buf, "real(v(%s))", string + 3); else if (eq(string + 3, "0")) - (void) sprintf(buf, "real(-v(%s))", s); - else (void) sprintf(buf, "real(v(%s)-v(%s))", string + 3, s); + (void) sprintf(buf, "real(-v(%s))", s); + else + (void) sprintf(buf, "real(v(%s)-v(%s))", string + 3, s); } else if (ciprefix("vdb(", string) &&strchr(string, ',')) { - for (s = string; *s && (*s != ','); s++) ; *s++ = '\0'; - for (t = s; *t && (*t != ')'); t++) ; *t = '\0'; - if (eq(s, "0")) (void) sprintf(buf, "db(v(%s))", string + 4); + for (s = string; *s && (*s != ','); s++) + ; + *s++ = '\0'; + for (t = s; *t && (*t != ')'); t++) + ; + *t = '\0'; + if (eq(s, "0")) + (void) sprintf(buf, "db(v(%s))", string + 4); else if (eq(string + 4, "0")) - (void) sprintf(buf, "db(-v(%s))", s); - else (void) sprintf(buf, "db(v(%s)-v(%s))", string + 4, s); + (void) sprintf(buf, "db(-v(%s))", s); + else + (void) sprintf(buf, "db(v(%s)-v(%s))", string + 4, s); } else if (ciprefix("i(", string)) { - for (s = string; *s && (*s != ')'); s++) ; *s = '\0'; + for (s = string; *s && (*s != ')'); s++) + ; + *s = '\0'; string += 2; (void) sprintf(buf, "%s#branch", string); + } else { + return (string); } - else return (string); tfree(ss); string = copy(buf); @@ -523,53 +563,54 @@ fixem(char *string) wordlist * gettoks(char *s) { - char *t; - char *l, *r, *c; /* left, right, center/comma */ - wordlist *wl, *list, **prevp; + char *t; + char *l, *r, *c; /* left, right, center/comma */ + wordlist *wl, *list, **prevp; list = NULL; prevp = &list; - if (strstr( s, "(" )) s = stripWhiteSpacesInsideParens(s); + if (strstr(s, "(")) s = stripWhiteSpacesInsideParens(s); while ((t = gettok(&s)) != NULL) { - if (*t == '(') - continue; - l =strrchr(t, '('/*)*/); - if (!l) { - wl = wl_cons(copy(t), NULL); - *prevp = wl; - prevp = &wl->wl_next; - continue; - } + if (*t == '(') + continue; + l = strrchr(t, '('/*)*/); + if (!l) { + wl = wl_cons(copy(t), NULL); + *prevp = wl; + prevp = &wl->wl_next; + continue; + } - r =strchr(t, /*(*/')'); + r = strchr(t, /*(*/')'); - c =strchr(t, ','); - if (!c) - c = r; + c = strchr(t, ','); + if (!c) + c = r; - if (c) - *c = 0; + if (c) + *c = 0; - wl = wl_cons(NULL, NULL); - *prevp = wl; - prevp = &wl->wl_next; + wl = wl_cons(NULL, NULL); + *prevp = wl; + prevp = &wl->wl_next; - if (*(l - 1) == 'i' || *(l - 1) == 'I') { - char buf[513]; - sprintf(buf, "%s#branch", l + 1); - wl->wl_word = copy(buf); - c = r = NULL; - } else - wl->wl_word = copy(l + 1); + if (*(l - 1) == 'i' || *(l - 1) == 'I') { + char buf[513]; + sprintf(buf, "%s#branch", l + 1); + wl->wl_word = copy(buf); + c = r = NULL; + } else { + wl->wl_word = copy(l + 1); + } - if (c != r) { - *r = 0; - wl = wl_cons(copy(c + 1), NULL); - *prevp = wl; - prevp = &wl->wl_next; - } + if (c != r) { + *r = 0; + wl = wl_cons(copy(c + 1), NULL); + *prevp = wl; + prevp = &wl->wl_next; + } } return list; } diff --git a/src/frontend/error.c b/src/frontend/error.c index 07cc3ec11..ca090c874 100644 --- a/src/frontend/error.c +++ b/src/frontend/error.c @@ -18,7 +18,7 @@ char ErrorMessage[1024]; #ifdef HAS_WINDOWS -void winmessage(char* new_msg); +void winmessage(char *new_msg); #endif diff --git a/src/frontend/evaluate.c b/src/frontend/evaluate.c index ff83e3d96..fec9bf004 100644 --- a/src/frontend/evaluate.c +++ b/src/frontend/evaluate.c @@ -19,11 +19,11 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group #include "ngspice/sim.h" /* To get SV_VOLTAGE definition */ -/* static declarations */ + static RETSIGTYPE sig_matherr(void); -static struct dvec * apply_func(struct func *func, struct pnode *arg); +static struct dvec *apply_func(struct func *func, struct pnode *arg); static struct dvec *ft_ternary(struct pnode *node); -static char * mkcname(char what, char *v1, char *v2); +static char *mkcname(char what, char *v1, char *v2); /* We are careful here to catch SIGILL and recognise them as math errors. @@ -43,8 +43,8 @@ sig_matherr(void) /* Note that ft_evaluate will return NULL on invalid expressions. */ /* va: NOTE: ft_evaluate returns a new vector for expressions (func, op, ...) - and an existing vector (node->pn_value) when node->pn_value != NULL. - For garbage collection caller must vec_free() expression-vector. */ + and an existing vector (node->pn_value) when node->pn_value != NULL. + For garbage collection caller must vec_free() expression-vector. */ struct dvec * ft_evaluate(struct pnode *node) { @@ -60,7 +60,7 @@ ft_evaluate(struct pnode *node) if (node->pn_op->op_arity == 1) d = node->pn_op->op_func.unary (node->pn_left); else if (node->pn_op->op_arity == 2) { - if(node->pn_op->op_num == PT_OP_TERNARY) + if (node->pn_op->op_num == PT_OP_TERNARY) d = ft_ternary(node); else d = node->pn_op->op_func.binary (node->pn_left, node->pn_right); @@ -70,12 +70,11 @@ ft_evaluate(struct pnode *node) d = NULL; } - if (d==NULL) { + if (d == NULL) return NULL; - } if (node->pn_name && !ft_evdb && d && !d->v_link2) { - if (d->v_name) + if (d->v_name) tfree(d->v_name); /* patch by Stefan Jones */ d->v_name = copy(node->pn_name); } @@ -83,8 +82,9 @@ ft_evaluate(struct pnode *node) if (!d->v_length) { fprintf(cp_err, "Error: no such vector %s\n", d->v_name); return (NULL); - } else + } else { return (d); + } } @@ -95,7 +95,7 @@ ft_ternary(struct pnode *node) struct pnode *arg; int c; - if(!node->pn_right->pn_op || node->pn_right->pn_op->op_func.binary != op_comma) + if (!node->pn_right->pn_op || node->pn_right->pn_op->op_func.binary != op_comma) { fprintf(cp_err, "Error: ft_ternary(), daemons ...\n"); return NULL; @@ -103,27 +103,27 @@ ft_ternary(struct pnode *node) cond = ft_evaluate(node->pn_left); - if(cond->v_link2) { + if (cond->v_link2) { fprintf(cp_err, "Error: ft_ternary(), whats that ?\n"); return NULL; } - if(cond->v_numdims != 1) { + if (cond->v_numdims != 1) { fprintf(cp_err, "Error: ft_ternary(), condition must be scalar, but numdims=%d\n", - cond->v_numdims); + cond->v_numdims); return NULL; } - if(cond->v_length != 1) { + if (cond->v_length != 1) { fprintf(cp_err, "Error: ft_ternary(), condition must be scalar, but length=%d\n", - cond->v_length); + cond->v_length); return NULL; } c = isreal(cond) ? (cond->v_realdata[0] != 0.0) : ((realpart(cond->v_compdata[0]) != 0.0) || - (imagpart(cond->v_compdata[0]) != 0.0) ); + (imagpart(cond->v_compdata[0]) != 0.0)); arg = c ? node->pn_right->pn_left @@ -148,9 +148,9 @@ ft_ternary(struct pnode *node) static void * doop_funcall( - void* (*func) (void *data1, void *data2, - short int datatype1, short int datatype2, - int length), + void * (*func) (void *data1, void *data2, + short int datatype1, short int datatype2, + int length), void *data1, void *data2, short int datatype1, short int datatype2, int length) @@ -167,7 +167,7 @@ doop_funcall( (void) signal(SIGILL, (SIGNAL_FUNCTION) sig_matherr); - data = func (data1, data2, datatype1, datatype2, length); + data = func(data1, data2, datatype1, datatype2, length); /* Back to normal */ (void) signal(SIGILL, SIG_DFL); @@ -178,14 +178,14 @@ doop_funcall( static struct dvec * doop(char what, - void*(*func) (void *data1, void *data2, - short int datatype1, short int datatype2, - int length), + void * (*func) (void *data1, void *data2, + short int datatype1, short int datatype2, + int length), struct pnode *arg1, struct pnode *arg2) { struct dvec *v1, *v2, *res; - ngcomplex_t *c1 = NULL, *c2 = NULL , lc; + ngcomplex_t *c1 = NULL, *c2 = NULL, lc; double *d1 = NULL, *d2 = NULL, ld; int length = 0, i; void *data; @@ -217,32 +217,31 @@ doop(char what, if ((v1->v_numdims > 1) && (v2->v_numdims > 1)) { if (v1->v_numdims != v2->v_numdims) { fprintf(cp_err, - "Warning: operands %s and %s have incompatible shapes.\n", - v1->v_name, v2->v_name); - return (NULL); - } - for (i = 1; i < v1->v_numdims; i++) { - if ((v1->v_dims[i] != v2->v_dims[i])) { - fprintf(cp_err, "Warning: operands %s and %s have incompatible shapes.\n", v1->v_name, v2->v_name); + return (NULL); + } + for (i = 1; i < v1->v_numdims; i++) + if ((v1->v_dims[i] != v2->v_dims[i])) { + fprintf(cp_err, + "Warning: operands %s and %s have incompatible shapes.\n", + v1->v_name, v2->v_name); return (NULL); } - } } /* This is a bad way to do this. */ switch (what) { - case '=': - case '>': - case '<': - case 'G': - case 'L': - case 'N': - case '&': - case '|': - case '~': - relflag = TRUE; + case '=': + case '>': + case '<': + case 'G': + case 'L': + case 'N': + case '&': + case '|': + case '~': + relflag = TRUE; } /* Type checking is done later */ @@ -258,7 +257,7 @@ doop(char what, d1[i] = v1->v_realdata[i]; if (i > 0) ld = v1->v_realdata[i - 1]; - for ( ; i < length; i++) + for (; i < length; i++) d1[i] = ld; } else { realpart(lc) = 0.0; @@ -268,14 +267,16 @@ doop(char what, c1[i] = v1->v_compdata[i]; if (i > 0) lc = v1->v_compdata[i - 1]; - for ( ; i < length; i++) + for (; i < length; i++) c1[i] = lc; } - } else + } else { if (isreal(v1)) d1 = v1->v_realdata; else c1 = v1->v_compdata; + } + if (v2->v_length < length) { free2 = TRUE; if (isreal(v2)) { @@ -285,7 +286,7 @@ doop(char what, d2[i] = v2->v_realdata[i]; if (i > 0) ld = v2->v_realdata[i - 1]; - for ( ; i < length; i++) + for (; i < length; i++) d2[i] = ld; } else { realpart(lc) = 0.0; @@ -295,29 +296,30 @@ doop(char what, c2[i] = v2->v_compdata[i]; if (i > 0) lc = v2->v_compdata[i - 1]; - for ( ; i < length; i++) + for (; i < length; i++) c2[i] = lc; } - } else + } else { if (isreal(v2)) d2 = v2->v_realdata; else c2 = v2->v_compdata; + } /* Now pass the vectors to the appropriate function. */ data = doop_funcall - ( func, - isreal(v1) ? (void *) d1 : (void *) c1, - isreal(v2) ? (void *) d2 : (void *) c2, - isreal(v1) ? VF_REAL : VF_COMPLEX, - isreal(v2) ? VF_REAL : VF_COMPLEX, - length); + (func, + isreal(v1) ? (void *) d1 : (void *) c1, + isreal(v2) ? (void *) d2 : (void *) c2, + isreal(v1) ? VF_REAL : VF_COMPLEX, + isreal(v2) ? VF_REAL : VF_COMPLEX, + length); if (!data) return (NULL); /* Make up the new vector. */ res = alloc(struct dvec); - ZERO(res,struct dvec); + ZERO(res, struct dvec); if (relflag || (isreal(v1) && isreal(v2) && (func != cx_comma))) { res->v_flags = (v1->v_flags | v2->v_flags | VF_REAL) & ~ VF_COMPLEX; @@ -336,8 +338,9 @@ doop(char what, fprintf(cp_err, "Warning: scales of %s and %s are different.\n", v1->v_name, v2->v_name); res->v_scale = NULL; - } else + } else { res->v_scale = v1->v_scale; + } /* Copy a few useful things */ res->v_defcolor = v1->v_defcolor; @@ -361,105 +364,107 @@ doop(char what, */ switch (what) { - case '*': /* Multiplication of two vectors */ - switch(v1->v_type) - { - case SV_VOLTAGE: - switch(v2->v_type) - { - case SV_VOLTAGE: - res->v_type = SV_VOLTAGE; - break; - case SV_CURRENT: - res->v_type = SV_POWER; - break; - default: - break; - } - break; + case '*': /* Multiplication of two vectors */ + switch (v1->v_type) + { + case SV_VOLTAGE: + switch (v2->v_type) + { + case SV_VOLTAGE: + res->v_type = SV_VOLTAGE; + break; + case SV_CURRENT: + res->v_type = SV_POWER; + break; + default: + break; + } + break; - case SV_CURRENT: - switch(v2->v_type) - { - case SV_VOLTAGE: - res->v_type = SV_POWER; - break; - case SV_CURRENT: - res->v_type = SV_CURRENT; - break; - default: - break; - } - break; + case SV_CURRENT: + switch (v2->v_type) + { + case SV_VOLTAGE: + res->v_type = SV_POWER; + break; + case SV_CURRENT: + res->v_type = SV_CURRENT; + break; + default: + break; + } + break; - default: - break; - } - break; - case '/': /* division of two vectors */ - switch(v1->v_type) - { - case SV_VOLTAGE: - switch(v2->v_type) - { - case SV_VOLTAGE: - res->v_type = SV_NOTYPE; - break; - case SV_CURRENT: - res->v_type = SV_IMPEDANCE; - break; - default: - break; - } - break; + default: + break; + } + break; + case '/': /* division of two vectors */ + switch (v1->v_type) + { + case SV_VOLTAGE: + switch (v2->v_type) + { + case SV_VOLTAGE: + res->v_type = SV_NOTYPE; + break; + case SV_CURRENT: + res->v_type = SV_IMPEDANCE; + break; + default: + break; + } + break; - case SV_CURRENT: - switch(v2->v_type) - { - case SV_VOLTAGE: - res->v_type = SV_ADMITTANCE; - break; - case SV_CURRENT: - res->v_type = SV_NOTYPE; - break; - default: - break; - } - break; + case SV_CURRENT: + switch (v2->v_type) + { + case SV_VOLTAGE: + res->v_type = SV_ADMITTANCE; + break; + case SV_CURRENT: + res->v_type = SV_NOTYPE; + break; + default: + break; + } + break; - default: - break; - } + default: + break; + } - default: - break; + default: + break; } + vec_new(res); /* Free the temporary data areas we used, if we allocated any. */ if (free1) { - if (isreal(v1)) { + if (isreal(v1)) tfree(d1); - } else { + else tfree(c1); - } } + if (free2) { - if (isreal(v2)) { + if (isreal(v2)) tfree(d2); - } else { + else tfree(c2); - } } /* va: garbage collection */ - if (arg1->pn_value==NULL && v1!=NULL) vec_free(v1); - if (arg2->pn_value==NULL && v2!=NULL) vec_free(v2); + if (arg1->pn_value == NULL && v1 != NULL) + vec_free(v1); + if (arg2->pn_value == NULL && v2 != NULL) + vec_free(v2); + return (res); } - /* The binary operations. */ struct dvec * op_plus(struct pnode *arg1, struct pnode *arg2) @@ -551,6 +556,7 @@ op_or(struct pnode *arg1, struct pnode *arg2) return (doop('|', cx_or, arg1, arg2)); } + /* This is an odd operation. The first argument is the name of a vector, and * the second is a range in the scale, so that v(1)[[10, 20]] gives all the * values of v(1) for which the TIME value is between 10 and 20. If there is @@ -562,7 +568,7 @@ op_or(struct pnode *arg1, struct pnode *arg2) struct dvec * op_range(struct pnode *arg1, struct pnode *arg2) { - struct dvec *v, *ind, *res, *scale; /* , *nscale; */ + struct dvec *v, *ind, *res, *scale; double up, low, td; int len, i, j; bool rev = FALSE; @@ -571,9 +577,11 @@ op_range(struct pnode *arg1, struct pnode *arg2) ind = ft_evaluate(arg2); if (!v || !ind) return (NULL); + scale = v->v_scale; if (!scale) scale = v->v_plot->pl_scale; + if (!scale) { fprintf(cp_err, "Error: no scale for vector %s\n", v->v_name); return (NULL); @@ -583,27 +591,30 @@ op_range(struct pnode *arg1, struct pnode *arg2) fprintf(cp_err, "Error: strange range specification\n"); return (NULL); } + if (isreal(ind)) { up = low = *ind->v_realdata; } else { up = imagpart(ind->v_compdata[0]); low = realpart(ind->v_compdata[0]); } + if (up < low) { td = up; up = low; low = td; rev = TRUE; } + for (i = len = 0; i < scale->v_length; i++) { td = isreal(scale) ? scale->v_realdata[i] : - realpart(scale->v_compdata[i]); + realpart(scale->v_compdata[i]); if ((td <= up) && (td >= low)) len++; } res = alloc(struct dvec); - ZERO(res,struct dvec); + ZERO(res, struct dvec); res->v_name = mkcname('R', v->v_name, ind->v_name); res->v_type = v->v_type; res->v_flags = v->v_flags; @@ -614,9 +625,9 @@ op_range(struct pnode *arg1, struct pnode *arg2) res->v_length = len; res->v_scale = /* nscale; */ scale; /* Dave says get rid of this - res->v_numdims = v->v_numdims; - for (i = 0; i < v->v_numdims; i++) - res->v_dims[i] = v->v_dims[i]; + res->v_numdims = v->v_numdims; + for (i = 0; i < v->v_numdims; i++) + res->v_dims[i] = v->v_dims[i]; */ res->v_numdims = 1; res->v_dims[0] = len; @@ -629,22 +640,25 @@ op_range(struct pnode *arg1, struct pnode *arg2) /* Toss in the data */ j = 0; - for (i = (rev ? v->v_length - 1 : 0); i != (rev ? -1 : v->v_length); - rev ? i-- : i++) { + for (i = (rev ? v->v_length - 1 : 0); + i != (rev ? -1 : v->v_length); + rev ? i-- : i++) + { td = isreal(scale) ? scale->v_realdata[i] : - realpart(scale->v_compdata[i]); + realpart(scale->v_compdata[i]); if ((td <= up) && (td >= low)) { if (isreal(res)) { res->v_realdata[j] = v->v_realdata[i]; } else { realpart(res->v_compdata[j]) = - realpart(v->v_compdata[i]); + realpart(v->v_compdata[i]); imagpart(res->v_compdata[j]) = - imagpart(v->v_compdata[i]); + imagpart(v->v_compdata[i]); } j++; } } + if (j != len) fprintf(cp_err, "Error: something funny..\n"); @@ -656,11 +670,15 @@ op_range(struct pnode *arg1, struct pnode *arg2) vec_new(res); /* va: garbage collection */ - if (arg1->pn_value==NULL && v!=NULL) vec_free(v); - if (arg2->pn_value==NULL && ind!=NULL) vec_free(ind); + if (arg1->pn_value == NULL && v != NULL) + vec_free(v); + if (arg2->pn_value == NULL && ind != NULL) + vec_free(ind); + return (res); } + /* This is another operation we do specially -- if the argument is a vector of * dimension n, n > 0, the result will be either a vector of dimension n - 1, * or a vector of dimension n with only a certain range of vectors present. @@ -685,8 +703,8 @@ op_ind(struct pnode *arg1, struct pnode *arg2) j *= v->v_dims[i]; if (v->v_length != j) { fprintf(cp_err, - "op_ind: Internal Error: len %d should be %d\n", - v->v_length, j); + "op_ind: Internal Error: len %d should be %d\n", + v->v_length, j); return (NULL); } } else { @@ -753,7 +771,7 @@ op_ind(struct pnode *arg1, struct pnode *arg2) /* Make up the new vector. */ res = alloc(struct dvec); - ZERO(res,struct dvec); + ZERO(res, struct dvec); res->v_name = mkcname('[', v->v_name, ind->v_name); res->v_type = v->v_type; res->v_flags = v->v_flags; @@ -764,12 +782,12 @@ op_ind(struct pnode *arg1, struct pnode *arg2) res->v_length = length; res->v_numdims = newdim; if (up != down) { - for (i = 0; i < newdim; i++) - res->v_dims[i] = v->v_dims[i]; + for (i = 0; i < newdim; i++) + res->v_dims[i] = v->v_dims[i]; res->v_dims[0] = up - down + 1; } else { - for (i = 0; i < newdim; i++) - res->v_dims[i] = v->v_dims[i + 1]; + for (i = 0; i < newdim; i++) + res->v_dims[i] = v->v_dims[i + 1]; } if (isreal(res)) @@ -784,10 +802,10 @@ op_ind(struct pnode *arg1, struct pnode *arg2) else k = j; for (i = 0; i < blocksize; i++) - if (isreal(res)) + if (isreal(res)) { res->v_realdata[k * blocksize + i] = v->v_realdata[(down + j) * blocksize + i]; - else { + } else { realpart(res->v_compdata[k * blocksize + i]) = realpart(v->v_compdata[(down + j) * blocksize + i]); imagpart(res->v_compdata[k * blocksize + i]) = @@ -809,11 +827,15 @@ op_ind(struct pnode *arg1, struct pnode *arg2) vec_new(res); /* va: garbage collection */ - if (arg1->pn_value==NULL && v!=NULL) vec_free(v); - if (arg2->pn_value==NULL && ind!=NULL) vec_free(ind); + if (arg1->pn_value == NULL && v != NULL) + vec_free(v); + if (arg2->pn_value == NULL && ind != NULL) + vec_free(ind); + return (res); } + /* Apply a function to an argument. Complex functions are called as follows: * cx_something(data, type, length, &newlength, &newtype), * and returns a char * that is cast to complex or double. @@ -839,20 +861,22 @@ apply_func_funcall(struct func *func, struct dvec *v, int *newlength, short int if (eq(func->fu_name, "interpolate") || eq(func->fu_name, "deriv") || eq(func->fu_name, "group_delay")) /* Ack */ { - void *(*f)(void *data, short int type, int length, - int *newlength, short int *newtype, struct plot *, struct plot *, int) = (void *(*)(void *, short int, int, int *, short int *, struct plot *, struct plot *, int)) func->fu_func; - data = f ( - isreal(v) ? (void *) v->v_realdata : (void *) v->v_compdata, - (short) (isreal(v) ? VF_REAL : VF_COMPLEX), - v->v_length, - newlength, newtype, - v->v_plot, plot_cur, v->v_dims[0]); + void * (*f) (void *data, short int type, int length, + int *newlength, short int *newtype, + struct plot *, struct plot *, int) = + (void * (*) (void *, short int, int, int *, short int *, struct plot *, struct plot *, int)) func->fu_func; + data = f + (isreal(v) ? (void *) v->v_realdata : (void *) v->v_compdata, + (short) (isreal(v) ? VF_REAL : VF_COMPLEX), + v->v_length, + newlength, newtype, + v->v_plot, plot_cur, v->v_dims[0]); } else { - data = func->fu_func ( - isreal(v) ? (void *) v->v_realdata : (void *) v->v_compdata, - (short) (isreal(v) ? VF_REAL : VF_COMPLEX), - v->v_length, - newlength, newtype); + data = func->fu_func + (isreal(v) ? (void *) v->v_realdata : (void *) v->v_compdata, + (short) (isreal(v) ? VF_REAL : VF_COMPLEX), + v->v_length, + newlength, newtype); } /* Back to normal */ @@ -903,53 +927,58 @@ apply_func(struct func *func, struct pnode *arg) return (NULL); t = alloc(struct dvec); - ZERO(t,struct dvec); + ZERO(t, struct dvec); t->v_flags = (v->v_flags & ~VF_COMPLEX & ~VF_REAL & - ~VF_PERMANENT & ~VF_MINGIVEN & ~VF_MAXGIVEN); + ~VF_PERMANENT & ~VF_MINGIVEN & ~VF_MAXGIVEN); t->v_flags |= type; #ifdef FTEDEBUG if (ft_evdb) fprintf(cp_err, - "apply_func: func %s to %s len %d, type %d\n", + "apply_func: func %s to %s len %d, type %d\n", func->fu_name, v->v_name, len, type); #endif - if (isreal(t)) - t->v_realdata = (double *) data; - else - t->v_compdata = (ngcomplex_t *) data; - if (eq(func->fu_name, "minus")) - t->v_name = mkcname('a', func->fu_name, v->v_name); - else if (eq(func->fu_name, "not")) - t->v_name = mkcname('c', func->fu_name, v->v_name); - else - t->v_name = mkcname('b', v->v_name, NULL); - t->v_type = v->v_type; /* This is strange too. */ - t->v_length = len; - t->v_scale = v->v_scale; + if (isreal(t)) + t->v_realdata = (double *) data; + else + t->v_compdata = (ngcomplex_t *) data; - /* Copy a few useful things */ - t->v_defcolor = v->v_defcolor; - t->v_gridtype = v->v_gridtype; - t->v_plottype = v->v_plottype; - t->v_numdims = v->v_numdims; - for (i = 0; i < t->v_numdims; i++) - t->v_dims[i] = v->v_dims[i]; + if (eq(func->fu_name, "minus")) + t->v_name = mkcname('a', func->fu_name, v->v_name); + else if (eq(func->fu_name, "not")) + t->v_name = mkcname('c', func->fu_name, v->v_name); + else + t->v_name = mkcname('b', v->v_name, NULL); - vec_new(t); + t->v_type = v->v_type; /* This is strange too. */ + t->v_length = len; + t->v_scale = v->v_scale; - if (end) - end->v_link2 = t; - else - newv = t; - end = t; + /* Copy a few useful things */ + t->v_defcolor = v->v_defcolor; + t->v_gridtype = v->v_gridtype; + t->v_plottype = v->v_plottype; + t->v_numdims = v->v_numdims; + for (i = 0; i < t->v_numdims; i++) + t->v_dims[i] = v->v_dims[i]; + + vec_new(t); + + if (end) + end->v_link2 = t; + else + newv = t; + end = t; } /* va: garbage collection */ - if (arg->pn_value==NULL && v!=NULL) vec_free(v); + if (arg->pn_value == NULL && v != NULL) + vec_free(v); + return (newv); } + /* The unary minus operation. */ struct dvec * @@ -964,6 +993,7 @@ op_not(struct pnode *arg) return (apply_func(&func_not, arg)); } + /* Create a reasonable name for the result of a function application, etc. * The what values 'a' and 'b' mean "make a function name" and "make a * unary minus", respectively. @@ -975,18 +1005,17 @@ mkcname(char what, char *v1, char *v2) char buf[BSIZE_SP], *s; if (what == 'a') - (void) sprintf(buf, "%s(%s)", v1, v2); + (void) sprintf(buf, "%s(%s)", v1, v2); else if (what == 'b') - (void) sprintf(buf, "-(%s)", v1); + (void) sprintf(buf, "-(%s)", v1); else if (what == 'c') - (void) sprintf(buf, "~(%s)", v1); + (void) sprintf(buf, "~(%s)", v1); else if (what == '[') - (void) sprintf(buf, "%s[%s]", v1, v2); + (void) sprintf(buf, "%s[%s]", v1, v2); else if (what == 'R') - (void) sprintf(buf, "%s[[%s]]", v1, v2); + (void) sprintf(buf, "%s[[%s]]", v1, v2); else - (void) sprintf(buf, "(%s)%c(%s)", v1, what, v2); + (void) sprintf(buf, "(%s)%c(%s)", v1, what, v2); s = copy(buf); return (s); } - diff --git a/src/frontend/evaluate.h b/src/frontend/evaluate.h index 24d3a3405..37d00b172 100644 --- a/src/frontend/evaluate.h +++ b/src/frontend/evaluate.h @@ -9,25 +9,24 @@ #include "ngspice/dvec.h" #include "ngspice/pnode.h" -struct dvec * op_plus(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_minus(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_comma(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_times(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_mod(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_divide(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_power(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_eq(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_gt(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_lt(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_ge(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_le(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_ne(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_and(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_or(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_range(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_ind(struct pnode *arg1, struct pnode *arg2); -struct dvec * op_uminus(struct pnode *arg); -struct dvec * op_not(struct pnode *arg); - +struct dvec *op_plus(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_minus(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_comma(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_times(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_mod(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_divide(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_power(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_eq(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_gt(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_lt(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_ge(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_le(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_ne(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_and(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_or(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_range(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_ind(struct pnode *arg1, struct pnode *arg2); +struct dvec *op_uminus(struct pnode *arg); +struct dvec *op_not(struct pnode *arg); #endif diff --git a/src/frontend/fourier.c b/src/frontend/fourier.c index e37159c7e..f68b9f8b7 100644 --- a/src/frontend/fourier.c +++ b/src/frontend/fourier.c @@ -21,19 +21,18 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group #include "variable.h" -/* static declarations */ -static char * pn(double num); -static int CKTfour(int ndata, int numFreq, double *thd, double *Time, double *Value, - double FundFreq, double *Freq, double *Mag, double *Phase, double *nMag, - double *nPhase); +static char *pn(double num); +static int CKTfour(int ndata, int numFreq, double *thd, double *Time, double *Value, + double FundFreq, double *Freq, double *Mag, double *Phase, double *nMag, + double *nPhase); #define DEF_FOURGRIDSIZE 200 -/* CKTfour(ndata,numFreq,thd,Time,Value,FundFreq,Freq,Mag,Phase,nMag,nPhase) - * len 10 ? inp inp inp out out out out out +/* CKTfour(ndata, numFreq, thd, Time, Value, FundFreq, Freq, Mag, Phase, nMag, nPhase) + * len 10 ? inp inp inp out out out out out */ /* FIXME: This function leaks memory due to non local exit bypassing @@ -53,7 +52,7 @@ fourier(wordlist *wl, struct plot *current_plot) int shift; if (!current_plot) - return 1; + return 1; sprintf(xbuf, "%1.1e", 0.0); shift = (int) strlen(xbuf) - 7; @@ -95,14 +94,13 @@ fourier(wordlist *wl, struct plot *current_plot) names = names->pn_next; while (vec) { if (vec->v_length != time->v_length) { - fprintf(cp_err, - "Error: lengths don't match: %d, %d\n", + fprintf(cp_err, + "Error: lengths don't match: %d, %d\n", vec->v_length, time->v_length); continue; } if (!isreal(vec)) { - fprintf(cp_err, "Error: %s isn't real!\n", - vec->v_name); + fprintf(cp_err, "Error: %s isn't real!\n", vec->v_name); continue; } @@ -115,8 +113,7 @@ fourier(wordlist *wl, struct plot *current_plot) /* Now get the last fund freq... */ d = 1 / fundfreq; /* The wavelength... */ if (dp[1] - dp[0] < d) { - fprintf(cp_err, - "Error: wavelength longer than time span\n"); + fprintf(cp_err, "Error: wavelength longer than time span\n"); return 1; } else if (dp[1] - dp[0] > d) { dp[0] = dp[1] - d; @@ -125,14 +122,13 @@ fourier(wordlist *wl, struct plot *current_plot) d = (dp[1] - dp[0]) / fourgridsize; for (i = 0; i < fourgridsize; i++) grid[i] = dp[0] + i * d; - + /* Now interpolate the stuff... */ if (!ft_interpolate(vec->v_realdata, stuff, - time->v_realdata, vec->v_length, - grid, fourgridsize, - polydegree)) { - fprintf(cp_err, - "Error: can't interpolate\n"); + time->v_realdata, vec->v_length, + grid, fourgridsize, + polydegree)) { + fprintf(cp_err, "Error: can't interpolate\n"); return 1; } timescale = grid; @@ -143,25 +139,24 @@ fourier(wordlist *wl, struct plot *current_plot) } err = CKTfour(fourgridsize, nfreqs, &thd, timescale, - stuff, fundfreq, freq, mag, phase, nmag, - nphase); + stuff, fundfreq, freq, mag, phase, nmag, + nphase); if (err != OK) { ft_sperror(err, "fourier"); return 1; } - fprintf(cp_out, "Fourier analysis for %s:\n", - vec->v_name); - fprintf(cp_out, -" No. Harmonics: %d, THD: %g %%, Gridsize: %d, Interpolation Degree: %d\n\n", - nfreqs, thd, fourgridsize, - polydegree); + fprintf(cp_out, "Fourier analysis for %s:\n", vec->v_name); + fprintf(cp_out, + " No. Harmonics: %d, THD: %g %%, Gridsize: %d, Interpolation Degree: %d\n\n", + nfreqs, thd, fourgridsize, + polydegree); /* Each field will have width cp_numdgt + 6 (or 7 * with HP-UX) + 1 if there is a - sign. */ fw = ((cp_numdgt > 0) ? cp_numdgt : 6) + 5 + shift; fprintf(cp_out, "Harmonic %-*s %-*s %-*s %-*s %-*s\n", - fw, "Frequency", fw, "Magnitude", + fw, "Frequency", fw, "Magnitude", fw, "Phase", fw, "Norm. Mag", fw, "Norm. Phase"); fprintf(cp_out, "-------- %-*s %-*s %-*s %-*s %-*s\n", @@ -170,23 +165,25 @@ fourier(wordlist *wl, struct plot *current_plot) fw, "-----------"); for (i = 0; i < nfreqs; i++) fprintf(cp_out, - " %-4d %-*s %-*s %-*s %-*s %-*s\n", - i, - fw, pn(freq[i]), - fw, pn(mag[i]), - fw, pn(phase[i]), - fw, pn(nmag[i]), - fw, pn(nphase[i])); + " %-4d %-*s %-*s %-*s %-*s %-*s\n", + i, + fw, pn(freq[i]), + fw, pn(mag[i]), + fw, pn(phase[i]), + fw, pn(nmag[i]), + fw, pn(nphase[i])); fputs("\n", cp_out); vec = vec->v_link2; } } + free_pnode(first_name); tfree(freq); tfree(mag); tfree(phase); tfree(nmag); tfree(nphase); + return 0; } @@ -198,7 +195,6 @@ com_fourier(wordlist *wl) } - static char * pn(double num) { @@ -212,6 +208,7 @@ pn(double num) sprintf(buf, "%.*g", i - 1, num); else sprintf(buf, "%.*g", i, num); + return (copy(buf)); } @@ -224,25 +221,25 @@ pn(double num) * vectors of time and data values to have the fourier analysis * performed on them. */ static int -CKTfour(int ndata, /* number of entries in the Time and +CKTfour(int ndata, /* number of entries in the Time and Value arrays */ - int numFreq, /* number of harmonics to calculate */ - double *thd, /* total harmonic distortion (percent) + int numFreq, /* number of harmonics to calculate */ + double *thd, /* total harmonic distortion (percent) to be returned */ - double *Time, /* times at which the voltage/current + double *Time, /* times at which the voltage/current values were measured*/ - double *Value, /* voltage or current vector whose + double *Value, /* voltage or current vector whose transform is desired */ - double FundFreq, /* the fundamental frequency of the + double FundFreq, /* the fundamental frequency of the analysis */ - double *Freq, /* the frequency value of the various + double *Freq, /* the frequency value of the various harmonics */ - double *Mag, /* the Magnitude of the fourier + double *Mag, /* the Magnitude of the fourier transform */ - double *Phase, /* the Phase of the fourier transform */ - double *nMag, /* the normalized magnitude of the + double *Phase, /* the Phase of the fourier transform */ + double *nMag, /* the normalized magnitude of the transform: nMag(fund)=1*/ - double *nPhase) /* the normalized phase of the + double *nPhase) /* the normalized phase of the transform: Nphase(fund)=0 */ { /* Note: we can consider these as a set of arrays. The sizes are: @@ -265,30 +262,31 @@ CKTfour(int ndata, /* number of entries in the Time and /* clear output/computation arrays */ - for(i=0;i1) *thd += nMag[i]*nMag[i]; + Mag[i] = sqrt(tmp*tmp + Phase[i]*Phase[i]); + Phase[i] = atan2(Phase[i], tmp) * 180.0/M_PI; + nMag[i] = Mag[i] / Mag[1]; + nPhase[i] = Phase[i] - Phase[1]; + if (i > 1) + *thd += nMag[i] * nMag[i]; } *thd = 100*sqrt(*thd); - return(OK); + return (OK); } diff --git a/src/frontend/ftesopt.c b/src/frontend/ftesopt.c index 5c1a93ea4..db0567f38 100644 --- a/src/frontend/ftesopt.c +++ b/src/frontend/ftesopt.c @@ -45,9 +45,10 @@ ft_getstat(struct circ *ft_curckt, char *name) vv->va_type = FTEOPTtbl[i].dataType; vv->va_name = copy(FTEOPTtbl[i].description); vv->va_next = NULL; - return(vv); - } else + return (vv); + } else { return (NULL); + } } return (NULL); } else { @@ -88,7 +89,8 @@ getFTEstat(struct circ *ft_curckt, int id) break; default: tfree(v); - return(NULL); + return (NULL); } - return(v); + + return (v); } diff --git a/src/frontend/gens.c b/src/frontend/gens.c index 6867485f7..d5afdc12b 100644 --- a/src/frontend/gens.c +++ b/src/frontend/gens.c @@ -10,306 +10,304 @@ #include "gens.h" -/* static declarations */ static void dgen_next(dgen **dgx); - void wl_forall(wordlist *wl, void (*fn)(wordlist*, dgen*), dgen *data) { - while (wl) { - fn (wl, data); - wl = wl->wl_next; - } + while (wl) { + fn (wl, data); + wl = wl->wl_next; + } } + dgen * dgen_init(GENcircuit *ckt, wordlist *wl, int nomix, int flag, int model) { - dgen *dg, *dg_save; - wordlist **prevp; + dgen *dg, *dg_save; + wordlist **prevp; - NG_IGNORE(nomix); + NG_IGNORE(nomix); - dg = NEW(dgen); - dg->ckt = ckt; - dg->instance = NULL; - dg->model = NULL; - dg->dev_type_no = -1; - dg->dev_list = wl; - dg->flags = 0; - dg_save = dg; /* va: save, to avoid memory leak */ + dg = NEW(dgen); + dg->ckt = ckt; + dg->instance = NULL; + dg->model = NULL; + dg->dev_type_no = -1; + dg->dev_list = wl; + dg->flags = 0; + dg_save = dg; /* va: save, to avoid memory leak */ - prevp = &wl; + prevp = &wl; - if (model) - dg->flags = (DGEN_ALL & ~ DGEN_INSTANCE) | DGEN_INIT; - else - dg->flags = DGEN_ALL | DGEN_INIT; + if (model) + dg->flags = (DGEN_ALL & ~ DGEN_INSTANCE) | DGEN_INIT; + else + dg->flags = DGEN_ALL | DGEN_INIT; - if (wl) - dg->flags |= flag; - else - dg->flags |= DGEN_DEFDEVS | flag; + if (wl) + dg->flags |= flag; + else + dg->flags |= DGEN_DEFDEVS | flag; - dgen_next(&dg); - /* va: it might be too much tests, but safer is better... */ - if (dg!=dg_save && dg==NULL && dg_save!=NULL) tfree(dg_save); + dgen_next(&dg); + /* va: it might be too much tests, but safer is better... */ + if (dg != dg_save && dg == NULL && dg_save != NULL) + tfree(dg_save); - return dg; + return dg; } + int dgen_for_n(dgen *dg, int n, int (*fn) (dgen*, IFparm*, int), IFparm *data, int subindex) { - dgen dgx, *dgxp; - int dnum, i, j, k; + dgen dgx, *dgxp; + int dnum, i, j, k; - dgxp = &dgx; - bcopy(dg, dgxp, sizeof(dgx)); /* va: compatible pointer types */ + dgxp = &dgx; + bcopy(dg, dgxp, sizeof(dgx)); /* va: compatible pointer types */ - dnum = dgxp->dev_type_no; + dnum = dgxp->dev_type_no; - k = 0; - for (i = 0; dgxp && dgxp->dev_type_no == dnum && i < n; i++) { - /*printf("Loop at %d\n", i);*/ - j = fn (dgxp, data, subindex); - if (j > k) - k = j; - dgen_next(&dgxp); - } + k = 0; + for (i = 0; dgxp && dgxp->dev_type_no == dnum && i < n; i++) { + /*printf("Loop at %d\n", i);*/ + j = fn (dgxp, data, subindex); + if (j > k) + k = j; + dgen_next(&dgxp); + } - return k - subindex; + return k - subindex; } + void dgen_nth_next(dgen **p_dg, int n) { - int i, dnum; - dgen * dg_save=*p_dg; /* va: save, to avoid memory leak */ + int i, dnum; + dgen *dg_save = *p_dg; /* va: save, to avoid memory leak */ - dnum = (*p_dg)->dev_type_no; + dnum = (*p_dg)->dev_type_no; - for (i = 0; *p_dg && (*p_dg)->dev_type_no == dnum && i < n; i++) { - dgen_next(p_dg); - /* va: it might be too much tests, but safer is better... */ - if (*p_dg!=dg_save && *p_dg==NULL && dg_save!=NULL) tfree(dg_save); - } + for (i = 0; *p_dg && (*p_dg)->dev_type_no == dnum && i < n; i++) { + dgen_next(p_dg); + /* va: it might be too much tests, but safer is better... */ + if (*p_dg != dg_save && *p_dg == NULL && dg_save != NULL) + tfree(dg_save); + } } + static void dgen_next(dgen **dgx) { - int done; - dgen *dg; - char *p; - int need; - wordlist *w; - char type, *subckt, *device, *model; - char *Top_Level = "\001"; - int subckt_len; - int head_match; - char *word, *dev_name, *mod_name; + int done; + dgen *dg; + char *p; + int need; + wordlist *w; + char type, *subckt, *device, *model; + char *Top_Level = "\001"; + int subckt_len; + int head_match; + char *word, *dev_name, *mod_name; - dg = *dgx; - if (!dg) - return; + dg = *dgx; + if (!dg) + return; - /* Prime the "model only" or "device type only" iteration, - * required because the filtering (below) may request additional - * detail. - */ - if (!(dg->flags & DGEN_INSTANCE)) { - if (!(dg->flags & DGEN_MODEL)) - dg->model = NULL; - dg->instance = NULL; - } + /* Prime the "model only" or "device type only" iteration, + * required because the filtering (below) may request additional + * detail. + */ + if (!(dg->flags & DGEN_INSTANCE)) { + if (!(dg->flags & DGEN_MODEL)) + dg->model = NULL; + dg->instance = NULL; + } - need = dg->flags; - done = 0; + need = dg->flags; + done = 0; - while (!done) { + while (!done) { - if (dg->instance) { - /* next instance */ - dg->instance = dg->instance->GENnextInstance; - } else if (dg->model) { - dg->model = dg->model->GENnextModel; - if (dg->model) - dg->instance = dg->model->GENinstances; - } else if (dg->dev_type_no < DEVmaxnum) { - dg->dev_type_no += 1; - if (dg->dev_type_no < DEVmaxnum) { - dg->model = ((CKTcircuit *) - (dg->ckt))->CKThead[dg->dev_type_no]; - if (dg->model) - dg->instance = dg->model->GENinstances; - } else { - done = 2; - break; - } - } else { - done = 2; - break; - } + if (dg->instance) { + /* next instance */ + dg->instance = dg->instance->GENnextInstance; + } else if (dg->model) { + dg->model = dg->model->GENnextModel; + if (dg->model) + dg->instance = dg->model->GENinstances; + } else if (dg->dev_type_no < DEVmaxnum) { + dg->dev_type_no += 1; + if (dg->dev_type_no < DEVmaxnum) { + dg->model = ((CKTcircuit *)(dg->ckt))->CKThead[dg->dev_type_no]; + if (dg->model) + dg->instance = dg->model->GENinstances; + } else { + done = 2; + break; + } + } else { + done = 2; + break; + } - if (need & DGEN_INSTANCE && !dg->instance) - continue; - if (need & DGEN_MODEL && !dg->model) - continue; + if (need & DGEN_INSTANCE && !dg->instance) + continue; + if (need & DGEN_MODEL && !dg->model) + continue; - /* Filter */ - if (!dg->dev_list) { - if ((dg->flags & DGEN_ALLDEVS) - || ((dg->flags & DGEN_DEFDEVS) - && (ft_sim->devices[dg->dev_type_no]->flags - & DEV_DEFAULT))) - { - done = 1; - } else { - done = 0; - } - continue; - } + /* Filter */ + if (!dg->dev_list) { + if ((dg->flags & DGEN_ALLDEVS) || + ((dg->flags & DGEN_DEFDEVS) && + (ft_sim->devices[dg->dev_type_no]->flags & DEV_DEFAULT))) + { + done = 1; + } else { + done = 0; + } + continue; + } - done = 0; + done = 0; - for (w = dg->dev_list; w && !done; w = w->wl_next) { + for (w = dg->dev_list; w && !done; w = w->wl_next) { - /* assume a match (have to reset done every time - * through - */ - done = 1; - word = w->wl_word; + /* assume a match (have to reset done every time + * through + */ + done = 1; + word = w->wl_word; - if (!word || !*word) { - break; - } + if (!word || !*word) { + break; + } - /* Break up word into type, subcircuit, model, device, - * must be nodestructive to "word" - */ + /* Break up word into type, subcircuit, model, device, + * must be nodestructive to "word" + */ - /* type */ - if (*word == ':' || *word == '#') - type = '\0'; - else - type = *word++; + /* type */ + if (*word == ':' || *word == '#') + type = '\0'; + else + type = *word++; - /* subcircuit */ + /* subcircuit */ - subckt = word; - /* look for last ":" or "#" in word */ - for (p = word + strlen(word) /* do '\0' first time */; - p != word && *p != ':' && *p != '#'; p--) - { - ; - } + subckt = word; + /* look for last ":" or "#" in word */ + for (p = word + strlen(word) /* do '\0' first time */; + p != word && *p != ':' && *p != '#'; p--) + { + ; + } - if (*p != ':' && *p != '#') { - /* No subcircuit name specified */ - subckt = NULL; - subckt_len = 0; - } else { + if (*p != ':' && *p != '#') { + /* No subcircuit name specified */ + subckt = NULL; + subckt_len = 0; + } else { - if (p[-1] == ':') { - head_match = 1; - subckt_len = (int)(p - word) - 1; - } else { - head_match = 0; - subckt_len = (int)(p - word); - } + if (p[-1] == ':') { + head_match = 1; + subckt_len = (int)(p - word) - 1; + } else { + head_match = 0; + subckt_len = (int)(p - word); + } - if (subckt_len == 0) { - /* Top level only */ - if (head_match) - subckt = NULL; - else - subckt = Top_Level; - } - word = p + 1; - } + if (subckt_len == 0) { + /* Top level only */ + if (head_match) + subckt = NULL; + else + subckt = Top_Level; + } + word = p + 1; + } - /* model or device */ + /* model or device */ - if (*p == '#') { - model = word; - device = NULL; - } else { - model = NULL; - device = word; - } + if (*p == '#') { + model = word; + device = NULL; + } else { + model = NULL; + device = word; + } - /* Now compare */ - if (dg->instance) - dev_name = dg->instance->GENname; - else - dev_name = NULL; + /* Now compare */ + if (dg->instance) + dev_name = dg->instance->GENname; + else + dev_name = NULL; - if (dg->model) - mod_name = dg->model->GENmodName; - else - mod_name = NULL; + if (dg->model) + mod_name = dg->model->GENmodName; + else + mod_name = NULL; - if (type) { - if (!dev_name) { - done = 0; - /*printf("No device.\n");*/ - need |= DGEN_MODEL; - continue; - } else if (type != *dev_name) { - done = 0; - /*printf("Wrong type.\n");*/ - /* Bleh ... plan breaks down here */ - /* need = DGEN_TYPE; */ - continue; - } - } + if (type) { + if (!dev_name) { + done = 0; + /*printf("No device.\n");*/ + need |= DGEN_MODEL; + continue; + } else if (type != *dev_name) { + done = 0; + /*printf("Wrong type.\n");*/ + /* Bleh ... plan breaks down here */ + /* need = DGEN_TYPE; */ + continue; + } + } - if (subckt == Top_Level) { - if (dev_name && dev_name[1] == ':') { - need |= DGEN_INSTANCE; - done = 0; - /*printf("Wrong level.\n");*/ - continue; - } - } else if (subckt && (!dev_name - || !ciprefix(subckt, dev_name + 1))) - { - need |= DGEN_INSTANCE; - done = 0; - /*printf("Wrong subckt.\n"); */ - continue; - } + if (subckt == Top_Level) { + if (dev_name && dev_name[1] == ':') { + need |= DGEN_INSTANCE; + done = 0; + /*printf("Wrong level.\n");*/ + continue; + } + } else if (subckt && (!dev_name || !ciprefix(subckt, dev_name + 1))) { + need |= DGEN_INSTANCE; + done = 0; + /*printf("Wrong subckt.\n"); */ + continue; + } - if (device && *device) { - need |= DGEN_INSTANCE | DGEN_MODEL; - if (!dev_name) { - done = 0; - /*printf("Didn't get dev name.\n");*/ - continue; - } else if (strcmp(device, - dev_name + 1 + subckt_len)) - { - done = 0; - /*printf("Wrong name.\n");*/ - continue; - } - } else if (model && *model) { - if (strcmp(model, mod_name)) { - done = 0; - need |= DGEN_MODEL; - /*printf("Wrong model name.\n");*/ - continue; - } - } + if (device && *device) { + need |= DGEN_INSTANCE | DGEN_MODEL; + if (!dev_name) { + done = 0; + /*printf("Didn't get dev name.\n");*/ + continue; + } else if (strcmp(device, dev_name + 1 + subckt_len)) { + done = 0; + /*printf("Wrong name.\n");*/ + continue; + } + } else if (model && *model) { + if (strcmp(model, mod_name)) { + done = 0; + need |= DGEN_MODEL; + /*printf("Wrong model name.\n");*/ + continue; + } + } - break; - } + break; + } - } + } - if (done == 2) - *dgx = NULL; + if (done == 2) + *dgx = NULL; } diff --git a/src/frontend/hpgl.c b/src/frontend/hpgl.c index 29d32988c..e327a7a9b 100644 --- a/src/frontend/hpgl.c +++ b/src/frontend/hpgl.c @@ -65,14 +65,14 @@ typedef struct { } GLdevdep; static char *linestyle[] = { - "", /* solid */ - "1", /* was 1 - dotted */ - "", /* longdashed */ - "3", /* shortdashed */ - "4", /* longdotdashed */ - "5", /* shortdotdashed */ - "1" - }; + "", /* solid */ + "1", /* was 1 - dotted */ + "", /* longdashed */ + "3", /* shortdashed */ + "4", /* longdotdashed */ + "5", /* shortdotdashed */ + "1" +}; static FILE *plotfile; extern char psscale[32]; @@ -84,6 +84,7 @@ static double tocm = 0.0025; static double scale; /* Used for fine tuning */ static int hcopygraphid; + int GL_Init(void) { if (!cp_getvar("hcopyscale", CP_STRING, psscale)) { @@ -105,30 +106,28 @@ int GL_Init(void) dispdev->minx = (int)(XOFF * 1.0); dispdev->miny = (int)(YOFF * 1.0); - return(0); - + return (0); } -/* devdep initially contains name of output file */ -int GL_NewViewport( -GRAPH *graph) -{ -/* double scaleps, scalex, scaley; */ +/* devdep initially contains name of output file */ +int +GL_NewViewport(GRAPH *graph) +{ hcopygraphid = graph->graphid; if ((plotfile = fopen((char*) graph->devdep, "w")) == NULL) { perror((char*) graph->devdep); - graph->devdep = NULL; - return(1); + graph->devdep = NULL; + return (1); } if (graph->absolute.width) { - /* hardcopying from the screen */ + /* hardcopying from the screen */ - screenflag = 1; + screenflag = 1; - /* scale to fit on 8 1/2 square */ + /* scale to fit on 8 1/2 square */ } @@ -147,13 +146,13 @@ GRAPH *graph) /* start file off with a % */ fprintf(plotfile, "IN;DF;PA;"); - fprintf(plotfile, "SI %f,%f;", tocm*jgmult*fontwidth*scale,tocm*jgmult*fontheight*scale); + fprintf(plotfile, "SI %f,%f;", tocm*jgmult*fontwidth*scale, tocm*jgmult*fontheight*scale); #ifdef notdef if (!screenflag) #endif - graph->devdep = TMALLOC(GLdevdep, 1); + graph->devdep = TMALLOC(GLdevdep, 1); DEVDEP(graph).lastlinestyle = -1; DEVDEP(graph).lastx = -1; DEVDEP(graph).lasty = -1; @@ -163,51 +162,52 @@ GRAPH *graph) return 0; } -int GL_Close(void) -{ +int +GL_Close(void) +{ /* in case GL_Close is called as part of an abort, - w/o having reached GL_NewViewport */ + w/o having reached GL_NewViewport */ if (plotfile) { - if (DEVDEP(currentgraph).lastlinestyle != -1) { - DEVDEP(currentgraph).linecount = 0; - } - fclose(plotfile); - plotfile = NULL; + if (DEVDEP(currentgraph).lastlinestyle != -1) { + DEVDEP(currentgraph).linecount = 0; + } + fclose(plotfile); + plotfile = NULL; } /* In case of hardcopy command destroy the hardcopy graph * and reset currentgraph to graphid 1, if possible */ if (!screenflag) { - DestroyGraph(hcopygraphid); - currentgraph = FindGraph(1); + DestroyGraph(hcopygraphid); + currentgraph = FindGraph(1); } return 0; } -int GL_Clear(void) + +int +GL_Clear(void) { - /* do nothing */ - return 0; } -int GL_DrawLine( -int x1, int y1, int x2, int y2) -{ +int +GL_DrawLine(int x1, int y1, int x2, int y2) +{ /* note: this is not extendible to more than one graph - => will have to give NewViewport a writeable graph XXX */ + => will have to give NewViewport a writeable graph XXX */ if (DEVDEP(currentgraph).linecount == 0 - || x1 != DEVDEP(currentgraph).lastx - || y1 != DEVDEP(currentgraph).lasty) + || x1 != DEVDEP(currentgraph).lastx + || y1 != DEVDEP(currentgraph).lasty) { - fprintf(plotfile, "PU;PA %d , %d ;", jgmult*(x1 + xoff), jgmult*(y1 + yoff)); + fprintf(plotfile, "PU;PA %d , %d ;", jgmult*(x1 + xoff), jgmult*(y1 + yoff)); } if (x1 != x2 || y1 != y2) { fprintf(plotfile, "PD;PA %d , %d ;", jgmult*(x2 + xoff), jgmult*(y2 + yoff)); @@ -221,10 +221,10 @@ int x1, int y1, int x2, int y2) return 0; } + /* ARGSUSED */ -int GL_Arc( -int x0, int y0, int r, -double theta, double delta_theta) +int +GL_Arc(int x0, int y0, int r, double theta, double delta_theta) { int x1, y1, angle; @@ -241,14 +241,10 @@ double theta, double delta_theta) return 0; } -int GL_Text( -char *text, -int x, int y) + +int +GL_Text(char *text, int x, int y) { - -/* int savedlstyle; */ - - /* move to (x, y) */ fprintf(plotfile, "PU;PA %d , %d;", jgmult*(x+xoff+XTADJ), jgmult*(y+yoff+YTADJ)); @@ -257,49 +253,47 @@ int x, int y) DEVDEP(currentgraph).lastx = -1; DEVDEP(currentgraph).lasty = -1; - return 0; } -int -GL_SetLinestyle( -int linestyleid) -{ +int +GL_SetLinestyle(int linestyleid) +{ /* special case - get it when GL_Text restores a -1 linestyle */ + get it when GL_Text restores a -1 linestyle */ if (linestyleid == -1) { - currentgraph->linestyle = -1; - return 0; + currentgraph->linestyle = -1; + return 0; } if (linestyleid < 0 || linestyleid > dispdev->numlinestyles) { - internalerror("bad linestyleid"); - return 0; + internalerror("bad linestyleid"); + return 0; } if (currentgraph->linestyle != linestyleid) { - fprintf(plotfile, "LT %s ;", linestyle[linestyleid]); - currentgraph->linestyle = linestyleid; + fprintf(plotfile, "LT %s ;", linestyle[linestyleid]); + currentgraph->linestyle = linestyleid; } - return 0; + return 0; } -/* ARGSUSED */ -int GL_SetColor( -int colorid) -{ -/*va: unused: static int flag = 0;*/ /* A hack */ +/* ARGSUSED */ +int +GL_SetColor(int colorid) +{ fprintf(plotfile, "SP %d;", colorid); return 0; } -int GL_Update(void) -{ +int +GL_Update(void) +{ fflush(plotfile); return 0; diff --git a/src/frontend/inp.c b/src/frontend/inp.c index c06c5ac26..ad5d9f33f 100644 --- a/src/frontend/inp.c +++ b/src/frontend/inp.c @@ -381,7 +381,7 @@ inp_spsource(FILE *fp, bool comfile, char *filename) /* Ignore comment lines, but not lines begining with '*#', but remove them, if they are in a .control ... .endc section */ s = dd->li_line; - while(isspace(*s)) + while (isspace(*s)) s++; if ((*s == '*') && ((s != dd->li_line) || (s[1] != '#'))) { if (commands) { @@ -419,9 +419,9 @@ inp_spsource(FILE *fp, bool comfile, char *filename) fprintf(cp_err, "Warning: misplaced .endc card\n"); } else if (commands || prefix("*#", dd->li_line)) { /* more control lines */ - if (prefix("*#", dd->li_line)) + if (prefix("*#", dd->li_line)) { s = copy(dd->li_line + 2); - else { + } else { s = dd->li_line; dd->li_line = 0; /* SJB - prevent line_free() freeing the string (now pointed at by wl->wl_word) */ } @@ -430,14 +430,14 @@ inp_spsource(FILE *fp, bool comfile, char *filename) /* Look for set or unset numparams. If either are found then we evaluate these lines immediately so they take effect before netlist parsing */ - while(isspace(*s)) /* step past any white space */ + while (isspace(*s)) /* step past any white space */ s++; if (ciprefix("set", s)) s += 3; else if (ciprefix("unset", s)) s += 5; if (s != dd->li_line) { /* one of the above must have matched */ - while(isspace(*s)) /* step past white space */ + while (isspace(*s)) /* step past white space */ s++; if (ciprefix("numparams", s)) cp_evloop(wl->wl_word); @@ -834,8 +834,7 @@ inp_dodeck( dd->li_linenum_orig, dd->li_line, dd->li_error); if (ft_stricterror) controlled_exit(EXIT_BAD); - } - else { + } else { out_printf("%s\n", p); } @@ -895,23 +894,23 @@ inp_dodeck( ct->ci_filename = NULL; if (!noparse) { - /* for (; options; options = options->li_next) { - for (s = options->li_line; *s && !isspace(*s); s++) - ; - - ii = cp_interactive; - cp_interactive = FALSE; - wl = cp_lexer(s); - cp_interactive = ii; - if (!wl || !wl->wl_word || !*wl->wl_word) - continue; - if (eev) - eev->va_next = cp_setparse(wl); - else - ct->ci_vars = eev = cp_setparse(wl); - while (eev->va_next) - eev = eev->va_next; - } + /* + * for (; options; options = options->li_next) { + * for (s = options->li_line; *s && !isspace(*s); s++) + * ; + * ii = cp_interactive; + * cp_interactive = FALSE; + * wl = cp_lexer(s); + * cp_interactive = ii; + * if (!wl || !wl->wl_word || !*wl->wl_word) + * continue; + * if (eev) + * eev->va_next = cp_setparse(wl); + * else + * ct->ci_vars = eev = cp_setparse(wl); + * while (eev->va_next) + * eev = eev->va_next; + * } */ for (eev = ct->ci_vars; eev; eev = eev->va_next) { bool one = TRUE; /* FIXME, actually eev->va_bool should be TRUE anyway */ @@ -1108,7 +1107,7 @@ com_source(wordlist *wl) void inp_source(char *file) { - static struct wordlist wl = { NULL, NULL, NULL } ; + static struct wordlist wl = { NULL, NULL, NULL }; wl.wl_word = file; com_source(&wl); } diff --git a/src/frontend/inpcom.c b/src/frontend/inpcom.c index cd07b6487..4275d8ada 100644 --- a/src/frontend/inpcom.c +++ b/src/frontend/inpcom.c @@ -59,35 +59,35 @@ int dynMaxckt = 0; /* subckt.c 307 */ /* number of parameter substitutions */ long dynsubst; /* spicenum.c 221 */ -/* static declarations */ -static char * readline(FILE *fd); -static int get_number_terminals( char *c ); + +static char *readline(FILE *fd); +static int get_number_terminals(char *c); static void inp_stripcomments_deck(struct line *deck); -static void inp_stripcomments_line(char * s); +static void inp_stripcomments_line(char *s); static void inp_fix_for_numparam(struct line *deck); static void inp_remove_excess_ws(struct line *deck); static void inp_determine_libraries(struct line *deck, char *lib_name); static void inp_init_lib_data(void); static void inp_grab_func(struct line *deck); -static void inp_fix_inst_calls_for_numparam( struct line *deck); +static void inp_fix_inst_calls_for_numparam(struct line *deck); static void inp_expand_macros_in_func(void); -static void inp_expand_macros_in_deck( struct line *deck ); -static void inp_fix_param_values( struct line *deck ); -static void inp_reorder_params( struct line *deck, struct line *list_head, struct line *end ); -static int inp_split_multi_param_lines( struct line *deck, int line_number ); -static void inp_sort_params( struct line *start_card, struct line *end_card, struct line *card_bf_start, struct line *s_c, struct line *e_c ); -static char* inp_remove_ws( char *s ); +static void inp_expand_macros_in_deck(struct line *deck); +static void inp_fix_param_values(struct line *deck); +static void inp_reorder_params(struct line *deck, struct line *list_head, struct line *end); +static int inp_split_multi_param_lines(struct line *deck, int line_number); +static void inp_sort_params(struct line *start_card, struct line *end_card, struct line *card_bf_start, struct line *s_c, struct line *e_c); +static char *inp_remove_ws(char *s); static void inp_compat(struct line *deck); static void inp_bsource_compat(struct line *deck); -static bool chk_for_line_continuation( char *line ); -static void comment_out_unused_subckt_models( struct line *start_card , int no_of_lines); -static void inp_fix_macro_param_func_paren_io( struct line *begin_card ); -static char* inp_fix_ternary_operator_str( char *line, bool all); -static void inp_fix_ternary_operator( struct line *start_card ); -static void inp_fix_gnd_name( struct line *deck ); -static void inp_chk_for_multi_in_vcvs( struct line *deck, int *line_number ); -static void inp_add_control_section( struct line *deck, int *line_number ); +static bool chk_for_line_continuation(char *line); +static void comment_out_unused_subckt_models(struct line *start_card, int no_of_lines); +static void inp_fix_macro_param_func_paren_io(struct line *begin_card); +static char *inp_fix_ternary_operator_str(char *line, bool all); +static void inp_fix_ternary_operator(struct line *start_card); +static void inp_fix_gnd_name(struct line *deck); +static void inp_chk_for_multi_in_vcvs(struct line *deck, int *line_number); +static void inp_add_control_section(struct line *deck, int *line_number); static char *get_quoted_token(char *string, char **token); /*------------------------------------------------------------------------- @@ -157,13 +157,13 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c int i, j; bool found_lib_name, found_end = FALSE, shell_eol_continuation = FALSE; - if ( call_depth == 0 ) { + if (call_depth == 0) { num_subckt_w_params = 0; num_libraries = 0; num_functions = 0; global = NULL; found_end = FALSE; - inp_compat_mode = ngspice_compat_mode() ; + inp_compat_mode = ngspice_compat_mode(); } /* gtri - modify - 12/12/90 - wbk - read from mailbox if ipc enabled */ @@ -172,31 +172,29 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c /* First read in all lines & put them in the struct cc */ for (;;) { /* If IPC is not enabled, do equivalent of what SPICE did before */ - if(! g_ipc.enabled) { - if ( call_depth == 0 && line_count == 0 ) { + if (! g_ipc.enabled) { + if (call_depth == 0 && line_count == 0) { line_count++; - if ( fgets( big_buff, 5000, fp ) ) { + if (fgets(big_buff, 5000, fp)) buffer = copy(big_buff); - } } else { buffer = readline(fp); - if(! buffer) { + if (!buffer) break; - } } } else { /* else, get the line from the ipc channel. */ /* We assume that newlines are not sent by the client */ /* so we add them here */ ipc_status = ipc_get_line(ipc_buffer, &ipc_len, IPC_WAIT); - if(ipc_status == IPC_STATUS_END_OF_DECK) { + if (ipc_status == IPC_STATUS_END_OF_DECK) { buffer = NULL; break; - } else if(ipc_status == IPC_STATUS_OK) { + } else if (ipc_status == IPC_STATUS_OK) { buffer = TMALLOC(char, strlen(ipc_buffer) + 3); strcpy(buffer, ipc_buffer); strcat(buffer, "\n"); - } else { /* No good way to report this so just die */ + } else { /* No good way to report this so just die */ controlled_exit(EXIT_FAILURE); } } @@ -208,39 +206,40 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c #ifdef TRACE /* SDB debug statement */ - printf ("in inp_readall, just read %s", buffer); + printf("in inp_readall, just read %s", buffer); #endif - if ( !buffer ) { + if (!buffer) continue; - } + /* OK -- now we have loaded the next line into 'buffer'. Process it. */ /* If input line is blank, ignore it & continue looping. */ - if ( (strcmp(buffer,"\n") == 0) || (strcmp(buffer,"\r\n") == 0) ) { - if ( call_depth != 0 || (call_depth == 0 && cc != NULL) ) { + if ((strcmp(buffer, "\n") == 0) || (strcmp(buffer, "\r\n") == 0)) + if (call_depth != 0 || (call_depth == 0 && cc != NULL)) { line_number_orig++; - tfree(buffer); /* was allocated by readline() */ + tfree(buffer); /* was allocated by readline() */ continue; } - } if (*buffer == '@') { - tfree(buffer); /* was allocated by readline() */ + tfree(buffer); /* was allocated by readline() */ break; } /* now handle .title statement */ if (ciprefix(".title", buffer)) { - for ( s = buffer; *s && !isspace(*s); s++ ) /* skip over .title */ + for (s = buffer; *s && !isspace(*s); s++) /* skip over .title */ ; - while ( isspace(*s) ) s++; /* advance past space chars */ + while (isspace(*s)) /* advance past space chars */ + s++; /* only the last title line remains valid */ - if (new_title != NULL) tfree(new_title); + if (new_title != NULL) + tfree(new_title); new_title = copy(s); if ((s = strstr(new_title, "\n")) != NULL) *s = ' '; - *buffer = '*'; /* change .TITLE line to comment line */ + *buffer = '*'; /* change .TITLE line to comment line */ } /* now handle .lib statements */ @@ -250,55 +249,55 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c char *z = NULL; /* libname */ inp_stripcomments_line(buffer); - for ( s = buffer; *s && !isspace(*s); s++ ) /* skip over .lib */ + for (s = buffer; *s && !isspace(*s); s++) /* skip over .lib */ ; s = strdup(s); t = get_quoted_token(s, &y); - if ( !y ) { + if (!y) { fprintf(cp_err, "Error: .lib filename missing\n"); - tfree(buffer); /* was allocated by readline() */ + tfree(buffer); /* was allocated by readline() */ controlled_exit(EXIT_FAILURE); } t = get_quoted_token(t, &z); - if ( z && (inp_compat_mode == COMPATMODE_ALL || - inp_compat_mode == COMPATMODE_HS || - inp_compat_mode == COMPATMODE_NATIVE) ) { /* .lib */ + if (z && (inp_compat_mode == COMPATMODE_ALL || + inp_compat_mode == COMPATMODE_HS || + inp_compat_mode == COMPATMODE_NATIVE)) { /* .lib */ char *copyy = NULL; - if ( *y == '~' ) { + if (*y == '~') { copyy = cp_tildexpand(y); /* allocates memory, but can also return NULL */ - if ( copyy ) - y = copyy; /* reuse y, but remember, buffer still points to allocated memory */ + if (copyy) + y = copyy; /* reuse y, but remember, buffer still points to allocated memory */ } - for ( i = 0; i < num_libraries; i++ ) - if ( cieq( library_file[i], y ) ) + for (i = 0; i < num_libraries; i++) + if (cieq(library_file[i], y)) break; - if ( i >= num_libraries ) { + if (i >= num_libraries) { bool dir_name_flag = FALSE; - FILE *newfp = inp_pathopen( y, "r" ); + FILE *newfp = inp_pathopen(y, "r"); - if ( !newfp ) { + if (!newfp) { char big_buff2[5000]; - if ( dir_name ) - sprintf( big_buff2, "%s/%s", dir_name, y ); + if (dir_name) + sprintf(big_buff2, "%s/%s", dir_name, y); else - sprintf( big_buff2, "./%s", y ); + sprintf(big_buff2, "./%s", y); - newfp = inp_pathopen( big_buff2, "r" ); - if ( !newfp ) { + newfp = inp_pathopen(big_buff2, "r"); + if (!newfp) { fprintf(cp_err, "Error: Could not find library file %s\n", y); - if ( copyy ) - tfree(copyy); /* allocated by the cp_tildexpand() above */ + if (copyy) + tfree(copyy); /* allocated by the cp_tildexpand() above */ tfree(s); tfree(buffer); controlled_exit(EXIT_FAILURE); @@ -309,7 +308,7 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c library_file[num_libraries++] = strdup(y); - if ( dir_name_flag == FALSE ) { + if (dir_name_flag == FALSE) { char *y_dir_name = ngdirname(y); inp_readall(newfp, &libraries[num_libraries-1], call_depth+1, y_dir_name, FALSE); tfree(y_dir_name); @@ -320,17 +319,17 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c fclose(newfp); } - if ( copyy ) + if (copyy) tfree(copyy); /* allocated by the cp_tildexpand() above */ tfree(s); /* Make the .lib a comment */ *buffer = '*'; - } else if (inp_compat_mode == COMPATMODE_PS) { + } else if (inp_compat_mode == COMPATMODE_PS) { /* .lib (no lib name given ) */ fprintf(cp_err, "Warning: library name missing in line\n %s", buffer); fprintf(cp_err, " File included as: .inc %s\n", s); - memcpy(buffer, ".inc",4); + memcpy(buffer, ".inc", 4); } } /* end of .lib handling */ @@ -348,37 +347,37 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c t = get_quoted_token(s, &y); - if ( !y ) { - fprintf(cp_err, "Error: .include filename missing\n"); - tfree(buffer); /* was allocated by readline() */ + if (!y) { + fprintf(cp_err, "Error: .include filename missing\n"); + tfree(buffer); /* was allocated by readline() */ controlled_exit(EXIT_FAILURE); } if (*y == '~') { copyy = cp_tildexpand(y); /* allocates memory, but can also return NULL */ - if ( copyy ) - y = copyy; /* reuse y, but remember, buffer still points to allocated memory */ + if (copyy) + y = copyy; /* reuse y, but remember, buffer still points to allocated memory */ } { bool dir_name_flag = FALSE; FILE *newfp = inp_pathopen(y, "r"); - if ( !newfp ) { + if (!newfp) { char big_buff2[5000]; /* open file specified by .include statement */ - if ( dir_name ) - sprintf( big_buff2, "%s/%s", dir_name, y ); + if (dir_name) + sprintf(big_buff2, "%s/%s", dir_name, y); else - sprintf( big_buff2, "./%s", y ); + sprintf(big_buff2, "./%s", y); - newfp = inp_pathopen( big_buff2, "r" ); - if ( !newfp ) { + newfp = inp_pathopen(big_buff2, "r"); + if (!newfp) { perror(y); - if ( copyy ) + if (copyy) tfree(copyy); /* allocated by the cp_tildexpand() above */ - fprintf(cp_err, "Error: .include statement failed.\n"); + fprintf(cp_err, "Error: .include statement failed.\n"); tfree(buffer); /* allocated by readline() above */ controlled_exit(EXIT_FAILURE); } @@ -386,7 +385,7 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c dir_name_flag = TRUE; } - if ( dir_name_flag == FALSE ) { + if (dir_name_flag == FALSE) { char *y_dir_name = ngdirname(y); inp_readall(newfp, &newcard, call_depth+1, y_dir_name, FALSE); /* read stuff in include file into netlist */ tfree(y_dir_name); @@ -397,20 +396,20 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c (void) fclose(newfp); } - if ( copyy ) - tfree(copyy); /* allocated by the cp_tildexpand() above */ + if (copyy) + tfree(copyy); /* allocated by the cp_tildexpand() above */ /* Make the .include a comment */ *buffer = '*'; /* now check if this is the first pass (i.e. end points to null) */ - if (end) { /* end already exists */ + if (end) { /* end already exists */ end->li_next = alloc(struct line); /* create next card */ end = end->li_next; /* make end point to next card */ } else { end = cc = alloc(struct line); /* create the deck & end. cc will - point to beginning of deck, end to - the end */ + point to beginning of deck, end to + the end */ } /* now fill out rest of struct end. */ @@ -427,8 +426,8 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c end->li_linenum = line_number++; end->li_linenum_orig = line_number_inc++; } - end->li_linenum = line_number++; /* SJB - renumber the last line */ - end->li_linenum_orig = line_number_inc++; /* SJB - renumber the last line */ + end->li_linenum = line_number++; /* SJB - renumber the last line */ + end->li_linenum_orig = line_number_inc++; /* SJB - renumber the last line */ } /* Fix the buffer up a bit. */ @@ -438,43 +437,42 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c /* loop through 'buffer' until end is reached. Then test for premature end. If premature end is reached, spew error and zap the line. */ - if ( !ciprefix( "write", buffer ) ) { // exclude 'write' command so filename case preserved + if (!ciprefix("write", buffer)) { // exclude 'write' command so filename case preserved for (s = buffer; *s && (*s != '\n'); s++) *s = (char) tolower(*s); if (!*s) { - //fprintf(cp_err, "Warning: premature EOF\n"); + // fprintf(cp_err, "Warning: premature EOF\n"); } *s = '\0'; /* Zap the newline. */ - if((s-1) >= buffer && *(s-1) == '\r') /* Zop the carriage return under windows */ + if ((s-1) >= buffer && *(s-1) == '\r') /* Zop the carriage return under windows */ *(s-1) = '\0'; } - /* find the true .end command out of .endc, .ends, .endl, .end (comments may follow) */ - if (ciprefix(".end", buffer)) { - if ((*(buffer+4) == '\0') || ( isspace(*(buffer+4)))) { + /* find the true .end command out of .endc, .ends, .endl, .end (comments may follow) */ + if (ciprefix(".end", buffer)) + if ((*(buffer+4) == '\0') || (isspace(*(buffer+4)))) { found_end = TRUE; *buffer = '*'; } - } - if ( shell_eol_continuation ) { + if (shell_eol_continuation) { char *new_buffer = TMALLOC(char, strlen(buffer) + 2); - sprintf( new_buffer, "+%s", buffer ); + sprintf(new_buffer, "+%s", buffer); tfree(buffer); buffer = new_buffer; } - shell_eol_continuation = chk_for_line_continuation( buffer ); + shell_eol_continuation = chk_for_line_continuation(buffer); /* now check if this is the first pass (i.e. end points to null) */ - if (end) { /* end already exists */ - end->li_next = alloc(struct line); /* create next card */ - end = end->li_next; /* point to next card */ - } else { /* End doesn't exist. Create it. */ - end = cc = alloc(struct line); /* note that cc points to beginning - of deck, end to the end */ + if (end) { /* end already exists */ + end->li_next = alloc(struct line); /* create next card */ + end = end->li_next; /* point to next card */ + } else { /* End doesn't exist. Create it. */ + end = cc = alloc(struct line); /* note that cc points to beginning + of deck, end to the end */ } /* now put buffer into li */ @@ -492,10 +490,10 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c return; } - if ( call_depth == 0 && found_end == TRUE) { - if ( global == NULL ) { + if (call_depth == 0 && found_end == TRUE) { + if (global == NULL) { global = TMALLOC(char, strlen(".global gnd") + 1); - sprintf( global, ".global gnd" ); + sprintf(global, ".global gnd"); } global_card = alloc(struct line); global_card->li_error = NULL; @@ -515,13 +513,13 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c add libraries */ found_lib_name = FALSE; - if ( call_depth == 0 ) { - for( i = 0; i < num_libraries; i++ ) { + if (call_depth == 0) { + for (i = 0; i < num_libraries; i++) { working = libraries[i]; - while ( working ) { + while (working) { buffer = working->li_line; - if ( found_lib_name && ciprefix(".endl", buffer) ) { + if (found_lib_name && ciprefix(".endl", buffer)) { /* Make the .endl a comment */ *buffer = '*'; found_lib_name = FALSE; @@ -532,32 +530,33 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c working = tmp_ptr2; /* end = working; - * working = working->li_next; - * end->li_next = NULL; */ + * working = working->li_next; + * end->li_next = NULL; */ continue; } /* for ... */ - if ( ciprefix(".lib", buffer) ) { + if (ciprefix(".lib", buffer)) { char keep_char; - if ( found_lib_name == TRUE ) { - fprintf( stderr, "ERROR: .lib is missing .endl!\n" ); + if (found_lib_name == TRUE) { + fprintf(stderr, "ERROR: .lib is missing .endl!\n"); controlled_exit(EXIT_FAILURE); } - for ( s = buffer; *s && !isspace(*s); s++ ) /* skip over .lib */ - ; - while ( isspace(*s) || isquote(*s) ) s++; /* advance past space chars */ - for ( t = s; *t && !isspace(*t) && !isquote(*t); t++ ) /* skip to end of word */ - ; + for (s = buffer; *s && !isspace(*s); s++) + ; /* skip over .lib */ + while (isspace(*s) || isquote(*s)) + s++; /* advance past space chars */ + for (t = s; *t && !isspace(*t) && !isquote(*t); t++) + ; /* skip to end of word */ keep_char = *t; *t = '\0'; /* see if library we want to copy */ found_lib_name = FALSE; - for( j = 0; j < num_lib_names[i]; j++ ) { - if ( strcmp( library_name[i][j], s ) == 0 ) { + for (j = 0; j < num_lib_names[i]; j++) { + if (strcmp(library_name[i][j], s) == 0) { found_lib_name = TRUE; start_lib = working; @@ -569,7 +568,7 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c /* renumber lines */ line_number_lib = 1; - for ( start_lib = working; !ciprefix(".endl", start_lib->li_line); start_lib = start_lib->li_next ) { + for (start_lib = working; !ciprefix(".endl", start_lib->li_line); start_lib = start_lib->li_next) { start_lib->li_linenum = line_number++; start_lib->li_linenum_orig = line_number_lib++; } @@ -583,19 +582,19 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c prev = working; working = working->li_next; - if ( found_lib_name == FALSE ) { + if (found_lib_name == FALSE) { tfree(prev->li_line); tfree(prev); } } /* end while */ } /* end for */ - if ( found_end == TRUE ) { + if (found_end == TRUE) { end->li_next = alloc(struct line); /* create next card */ end = end->li_next; /* point to next card */ - buffer = TMALLOC(char, strlen( ".end" ) + 1); - sprintf( buffer, ".end" ); + buffer = TMALLOC(char, strlen(".end") + 1); + sprintf(buffer, ".end"); /* now put buffer into li */ end->li_next = NULL; @@ -615,7 +614,7 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c /* Now clean up li: remove comments & stitch together continuation lines. */ working = cc->li_next; /* cc points to head of deck. Start with the - next card. */ + next card. */ /* sjb - strip or convert end-of-line comments. This must be cone before stitching continuation lines. @@ -630,7 +629,7 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c #ifdef TRACE /* SDB debug statement */ - printf("In inp_readall, processing linked list element line = %d, s = %s . . . \n", working->li_linenum,s); + printf("In inp_readall, processing linked list element line = %d, s = %s . . . \n", working->li_linenum, s); #endif switch (c) { @@ -645,8 +644,7 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c case '+': /* handle continuation */ if (!prev) { - working->li_error = copy( - "Illegal continuation line: ignored."); + working->li_error = copy("Illegal continuation line: ignored."); working = working->li_next; break; } @@ -696,7 +694,7 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c inp_fix_for_numparam(working); inp_remove_excess_ws(working); - if ( call_depth == 0 ) { + if (call_depth == 0) { comment_out_unused_subckt_models(working, line_number); @@ -712,7 +710,7 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c /* get end card as last card in list; end card pntr does not appear to always be correct at this point */ - for(newcard = working; newcard != NULL; newcard = newcard->li_next) + for (newcard = working; newcard != NULL; newcard = newcard->li_next) end = newcard; inp_reorder_params(working, cc, end); @@ -744,7 +742,7 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c of parameter substitutions in a line*/ dynmaxline = 0; max_line_length = 0; - for(tmp_ptr1 = cc; tmp_ptr1 != NULL; tmp_ptr1 = tmp_ptr1->li_next) { + for (tmp_ptr1 = cc; tmp_ptr1 != NULL; tmp_ptr1 = tmp_ptr1->li_next) { char *s; unsigned int braces_per_line = 0; /* count number of lines */ @@ -755,14 +753,16 @@ inp_readall(FILE *fp, struct line **data, int call_depth, char *dir_name, bool c max_line_length = strlen(tmp_ptr1->li_line); /* count '{' */ for (s = tmp_ptr1->li_line; *s; s++) - if (*s == '{') braces_per_line++; - if (no_braces < braces_per_line) no_braces = braces_per_line; + if (*s == '{') + braces_per_line++; + if (no_braces < braces_per_line) + no_braces = braces_per_line; } if (ft_ngdebug) { /*debug: print into file*/ fdo = fopen("debug-out.txt", "w"); - for(tmp_ptr1 = cc; tmp_ptr1 != NULL; tmp_ptr1 = tmp_ptr1->li_next) + for (tmp_ptr1 = cc; tmp_ptr1 != NULL; tmp_ptr1 = tmp_ptr1->li_next) fprintf(fdo, "%d %d %s\n", tmp_ptr1->li_linenum_orig, tmp_ptr1->li_linenum, tmp_ptr1->li_line); (void) fclose(fdo); @@ -792,10 +792,12 @@ inp_pathopen(char *name, char *mode) /* If pathname is found, get path. (char *dirname(const char *name) might have been used here) */ if (substring(DIR_PATHSEP, buf2) || substring(DIR_PATHSEP_LINUX, buf2)) { - int i,j=0; - for (i=0; iva_num, DIR_PATHSEP, name); break; - case CP_REAL: /* This is foolish */ + case CP_REAL: /* This is foolish */ (void) sprintf(buf, "%g%s%s", v->va_real, DIR_PATHSEP, name); break; default: { - fprintf(stderr, "ERROR: enumeration value `CP_BOOL' or `CP_LIST' not handled in inp_pathopen\nAborting...\n" ); + fprintf(stderr, "ERROR: enumeration value `CP_BOOL' or `CP_LIST' not handled in inp_pathopen\nAborting...\n"); controlled_exit(EXIT_FAILURE); } } @@ -867,27 +868,25 @@ readline(FILE *fd) strlen = 0; memlen = STRGROW; strptr = TMALLOC(char, memlen); - memlen -= 1; /* Save constant -1's in while loop */ - while((c = getc(fd)) != EOF) { + memlen -= 1; /* Save constant -1's in while loop */ + while ((c = getc(fd)) != EOF) { if (strlen == 0 && (c == '\t' || c == ' ')) /* Leading spaces away */ continue; strptr[strlen] = (char) c; strlen++; - if( strlen >= memlen ) { + if (strlen >= memlen) { memlen += STRGROW; - if((strptr = TREALLOC(char, strptr, memlen + 1)) == NULL) { + if ((strptr = TREALLOC(char, strptr, memlen + 1)) == NULL) return (NULL); - } } - if (c == '\n') { + if (c == '\n') break; - } } if (!strlen) { tfree(strptr); return (NULL); } -// strptr[strlen] = '\0'; + // strptr[strlen] = '\0'; /* Trim the string */ strptr = TREALLOC(char, strptr, strlen + 1); strptr[strlen] = '\0'; @@ -898,23 +897,23 @@ readline(FILE *fd) /* replace "gnd" by " 0 " Delimiters of gnd may be ' ' or ',' or '(' or ')' */ static void -inp_fix_gnd_name( struct line *deck ) +inp_fix_gnd_name(struct line *deck) { struct line *c = deck; char *gnd; - while ( c != NULL ) { + while (c != NULL) { gnd = c->li_line; // if there is a comment or no gnd, go to next line - if (( *gnd == '*' ) || (strstr( gnd, "gnd" ) == NULL)) { + if ((*gnd == '*') || (strstr(gnd, "gnd") == NULL)) { c = c->li_next; continue; } // replace "§gnd§" by "§ 0 §", § being a ' ' ',' '(' ')'. - while ((gnd = strstr( gnd, "gnd" )) != NULL) { - if (( isspace(*(gnd-1)) || *(gnd-1) == '(' || *(gnd-1) == ',' ) && - ( isspace(*(gnd+3)) || *(gnd+3) == ')' || *(gnd+3) == ',' )) { - memcpy( gnd, " 0 ", 3 ); + while ((gnd = strstr(gnd, "gnd")) != NULL) { + if ((isspace(*(gnd-1)) || *(gnd-1) == '(' || *(gnd-1) == ',') && + (isspace(*(gnd+3)) || *(gnd+3) == ')' || *(gnd+3) == ',')) { + memcpy(gnd, " 0 ", 3); } gnd += 3; } @@ -925,8 +924,8 @@ inp_fix_gnd_name( struct line *deck ) } static struct line* -create_new_card( char *card_str, int *line_number ) { - char *str = strdup(card_str); +create_new_card(char *card_str, int *line_number) { + char *str = strdup(card_str); struct line *newcard = alloc(struct line); newcard->li_line = str; @@ -939,8 +938,9 @@ create_new_card( char *card_str, int *line_number ) { return newcard; } + static void -inp_chk_for_multi_in_vcvs( struct line *deck, int *line_number ) +inp_chk_for_multi_in_vcvs(struct line *deck, int *line_number) { struct line *c, *a_card, *model_card, *next_card; char *line, *bool_ptr, *str_ptr1, *str_ptr2, keep, *comma_ptr, *xy_values1[5], *xy_values2[5]; @@ -948,34 +948,38 @@ inp_chk_for_multi_in_vcvs( struct line *deck, int *line_number ) char big_buf[1000]; int xy_count1 = 0, xy_count2 = 0, skip_control = 0; - for ( c = deck; c != NULL; c = c->li_next ) { + for (c = deck; c != NULL; c = c->li_next) { str_ptr1 = line = c->li_line; /* there is no e source inside .control ... .endc */ - if ( ciprefix(".control", line) ) { + if (ciprefix(".control", line)) { skip_control ++; continue; - } else if( ciprefix(".endc", line) ) { + } else if (ciprefix(".endc", line)) { skip_control --; continue; - } else if(skip_control > 0) { + } else if (skip_control > 0) { continue; } - if ( *line == 'e' ) { - if ( (bool_ptr = strstr( line, "nand(" )) != NULL || - (bool_ptr = strstr( line, "and(" )) != NULL || - (bool_ptr = strstr( line, "nor(" )) != NULL || - (bool_ptr = strstr( line, "or(" )) != NULL ) { - while ( !isspace(*str_ptr1) ) str_ptr1++; + if (*line == 'e') { + if ((bool_ptr = strstr(line, "nand(")) != NULL || + (bool_ptr = strstr(line, "and(")) != NULL || + (bool_ptr = strstr(line, "nor(")) != NULL || + (bool_ptr = strstr(line, "or(")) != NULL) + { + while (!isspace(*str_ptr1)) + str_ptr1++; keep = *str_ptr1; *str_ptr1 = '\0'; model_name = strdup(line); *str_ptr1 = keep; str_ptr2 = bool_ptr - 1; - while ( isspace(*str_ptr1) ) str_ptr1++; - while ( isspace(*str_ptr2) ) str_ptr2--; + while (isspace(*str_ptr1)) + str_ptr1++; + while (isspace(*str_ptr2)) + str_ptr2--; str_ptr2++; keep = *str_ptr2; *str_ptr2 = '\0'; @@ -983,31 +987,37 @@ inp_chk_for_multi_in_vcvs( struct line *deck, int *line_number ) *str_ptr2 = keep; str_ptr1 = bool_ptr + 1; - while ( *str_ptr1 != '(' ) str_ptr1++; + while (*str_ptr1 != '(') + str_ptr1++; *str_ptr1 = '\0'; fcn_name = strdup(bool_ptr); *str_ptr1 = '('; - str_ptr1 = strstr( str_ptr1, ")" ); - comma_ptr = str_ptr2 = strstr( line, "," ); + str_ptr1 = strstr(str_ptr1, ")"); + comma_ptr = str_ptr2 = strstr(line, ","); if ((str_ptr1 == NULL)|| (str_ptr1 == NULL)) { - fprintf(stderr,"ERROR: mal formed line: %s\n", line); + fprintf(stderr, "ERROR: mal formed line: %s\n", line); controlled_exit(EXIT_FAILURE); } str_ptr1++; str_ptr2--; - while( isspace(*str_ptr2) ) str_ptr2--; - - while ( isspace(*str_ptr1) ) str_ptr1++; - if ( *str_ptr2 == '}' ) { - while ( *str_ptr2 != '{' ) str_ptr2--; + while (isspace(*str_ptr2)) + str_ptr2--; + while (isspace(*str_ptr1)) + str_ptr1++; + if (*str_ptr2 == '}') { + while (*str_ptr2 != '{') + str_ptr2--; xy_str1 = str_ptr2; str_ptr2--; - while ( isspace(*str_ptr2) ) str_ptr2--; + while (isspace(*str_ptr2)) + str_ptr2--; str_ptr2++; } else { - while ( !isspace(*str_ptr2) ) str_ptr2--; + while (!isspace(*str_ptr2)) + str_ptr2--; xy_str1 = str_ptr2 + 1; - while ( isspace(*str_ptr2) ) str_ptr2--; + while (isspace(*str_ptr2)) + str_ptr2--; str_ptr2++; } keep = *str_ptr2; @@ -1016,35 +1026,38 @@ inp_chk_for_multi_in_vcvs( struct line *deck, int *line_number ) *str_ptr2 = keep; str_ptr1 = comma_ptr + 1; - while ( isspace(*str_ptr1) ) str_ptr1++; - if ( *str_ptr1 == '{' ) { - while ( *str_ptr1 != '}' ) str_ptr1++; + while (isspace(*str_ptr1)) + str_ptr1++; + if (*str_ptr1 == '{') { + while (*str_ptr1 != '}') + str_ptr1++; str_ptr1++; } else { - while ( !isspace(*str_ptr1) ) str_ptr1++; + while (!isspace(*str_ptr1)) + str_ptr1++; } keep = *str_ptr1; *str_ptr1 = '\0'; - xy_count1 = get_comma_separated_values( xy_values1, xy_str1 ); + xy_count1 = get_comma_separated_values(xy_values1, xy_str1); *str_ptr1 = keep; - while ( isspace(*str_ptr1) ) str_ptr1++; - xy_count2 = get_comma_separated_values( xy_values2, str_ptr1 ); + while (isspace(*str_ptr1)) + str_ptr1++; + xy_count2 = get_comma_separated_values(xy_values2, str_ptr1); // place restrictions on only having 2 point values; this can change later - if ( xy_count1 != 2 && xy_count2 != 2 ) { - fprintf(stderr,"ERROR: only expecting 2 pair values for multi-input vcvs!\n"); - } + if (xy_count1 != 2 && xy_count2 != 2) + fprintf(stderr, "ERROR: only expecting 2 pair values for multi-input vcvs!\n"); - sprintf( big_buf, "%s %%vd[ %s ] %%vd( %s ) %s", - model_name, ctrl_node_str, node_str, model_name ); - a_card = create_new_card( big_buf, line_number ); + sprintf(big_buf, "%s %%vd[ %s ] %%vd( %s ) %s", + model_name, ctrl_node_str, node_str, model_name); + a_card = create_new_card(big_buf, line_number); *a_card->li_line = 'a'; - sprintf( big_buf, ".model %s multi_input_pwl ( x = [%s %s] y = [%s %s] model = \"%s\" )" - , model_name, xy_values1[0], xy_values2[0], - xy_values1[1], xy_values2[1], fcn_name ); - model_card = create_new_card( big_buf, line_number ); + sprintf(big_buf, ".model %s multi_input_pwl ( x = [%s %s] y = [%s %s] model = \"%s\" )", + model_name, xy_values1[0], xy_values2[0], + xy_values1[1], xy_values2[1], fcn_name); + model_card = create_new_card(big_buf, line_number); tfree(model_name); tfree(node_str); @@ -1065,38 +1078,43 @@ inp_chk_for_multi_in_vcvs( struct line *deck, int *line_number ) } } + static void -inp_add_control_section( struct line *deck, int *line_number ) +inp_add_control_section(struct line *deck, int *line_number) { struct line *c, *newcard, *prev_card = NULL; bool found_control = FALSE, found_run = FALSE; bool found_end = FALSE; char *op_line = NULL, rawfile[1000], *line; - for ( c = deck; c != NULL; c = c->li_next ) { - if ( *c->li_line == '*' ) continue; - if ( ciprefix( ".op ", c->li_line ) ) { + for (c = deck; c != NULL; c = c->li_next) { + if (*c->li_line == '*') + continue; + if (ciprefix(".op ", c->li_line)) { *c->li_line = '*'; op_line = c->li_line + 1; } - if ( ciprefix( ".end", c->li_line ) ) found_end = TRUE; - if ( found_control && ciprefix( "run", c->li_line ) ) found_run = TRUE; + if (ciprefix(".end", c->li_line)) + found_end = TRUE; + if (found_control && ciprefix("run", c->li_line)) + found_run = TRUE; - if ( ciprefix( ".control", c->li_line ) ) found_control = TRUE; - if ( ciprefix( ".endc", c->li_line ) ) { + if (ciprefix(".control", c->li_line)) + found_control = TRUE; + if (ciprefix(".endc", c->li_line)) { found_control = FALSE; - if ( !found_run ) { - newcard = create_new_card( "run", line_number ); + if (!found_run) { + newcard = create_new_card("run", line_number); prev_card->li_next = newcard; newcard->li_next = c; prev_card = newcard; found_run = TRUE; } - if ( cp_getvar( "rawfile", CP_STRING, rawfile ) ) { + if (cp_getvar("rawfile", CP_STRING, rawfile)) { line = TMALLOC(char, strlen("write") + strlen(rawfile) + 2); sprintf(line, "write %s", rawfile); - newcard = create_new_card( line, line_number ); + newcard = create_new_card(line, line_number); prev_card->li_next = newcard; newcard->li_next = c; prev_card = newcard; @@ -1106,50 +1124,52 @@ inp_add_control_section( struct line *deck, int *line_number ) prev_card = c; } // check if need to add control section - if ( !found_run && found_end ) { + if (!found_run && found_end) { prev_card = deck->li_next; - newcard = create_new_card( ".endc", line_number ); + newcard = create_new_card(".endc", line_number); deck->li_next = newcard; newcard->li_next = prev_card; - if ( cp_getvar( "rawfile", CP_STRING, rawfile ) ) { + if (cp_getvar("rawfile", CP_STRING, rawfile)) { line = TMALLOC(char, strlen("write") + strlen(rawfile) + 2); sprintf(line, "write %s", rawfile); prev_card = deck->li_next; - newcard = create_new_card( line, line_number ); + newcard = create_new_card(line, line_number); deck->li_next = newcard; newcard->li_next = prev_card; tfree(line); } - if ( op_line != NULL ) { + if (op_line != NULL) { prev_card = deck->li_next; - newcard = create_new_card( op_line, line_number ); + newcard = create_new_card(op_line, line_number); deck->li_next = newcard; newcard->li_next = prev_card; } prev_card = deck->li_next; - newcard = create_new_card( "run", line_number ); + newcard = create_new_card("run", line_number); deck->li_next = newcard; newcard->li_next = prev_card; prev_card = deck->li_next; - newcard = create_new_card( ".control", line_number ); + newcard = create_new_card(".control", line_number); deck->li_next = newcard; newcard->li_next = prev_card; } } + // look for shell-style end-of-line continuation '\\' static bool -chk_for_line_continuation( char *line ) +chk_for_line_continuation(char *line) { char *ptr = line + strlen(line) - 1; - if ( *line != '*' && *line != '$' ) { - while ( ptr >= line && *ptr && isspace(*ptr) ) ptr--; + if (*line != '*' && *line != '$') { + while (ptr >= line && *ptr && isspace(*ptr)) + ptr--; - if ( (ptr-1) >= line && *ptr == '\\' && *(ptr-1) && *(ptr-1) == '\\' ) { + if ((ptr-1) >= line && *ptr == '\\' && *(ptr-1) && *(ptr-1) == '\\') { *ptr = ' '; *(ptr-1) = ' '; return TRUE; @@ -1159,6 +1179,7 @@ chk_for_line_continuation( char *line ) return FALSE; } + // // change .macro --> .subckt // .eom --> .ends @@ -1168,45 +1189,51 @@ chk_for_line_continuation( char *line ) // .param func1(x,y) = {x*y} --> .func func1(x,y) {x*y} static void -inp_fix_macro_param_func_paren_io( struct line *begin_card ) +inp_fix_macro_param_func_paren_io(struct line *begin_card) { struct line *card; char *str_ptr, *new_str; bool is_func = FALSE; - for ( card = begin_card; card != NULL; card = card->li_next ) { + for (card = begin_card; card != NULL; card = card->li_next) { - if ( *card->li_line == '*' ) continue; + if (*card->li_line == '*') + continue; - if ( ciprefix( ".macro", card->li_line ) || ciprefix( ".eom", card->li_line ) ) { + if (ciprefix(".macro", card->li_line) || ciprefix(".eom", card->li_line)) { str_ptr = card->li_line; - while( !isspace(*str_ptr) ) str_ptr++; + while (!isspace(*str_ptr)) + str_ptr++; - if ( ciprefix( ".macro", card->li_line ) ) { + if (ciprefix(".macro", card->li_line)) { new_str = TMALLOC(char, strlen(".subckt") + strlen(str_ptr) + 1); - sprintf( new_str, ".subckt%s", str_ptr ); + sprintf(new_str, ".subckt%s", str_ptr); } else { new_str = TMALLOC(char, strlen(".ends") + strlen(str_ptr) + 1); - sprintf( new_str, ".ends%s", str_ptr ); + sprintf(new_str, ".ends%s", str_ptr); } - tfree( card->li_line ); + tfree(card->li_line); card->li_line = new_str; } - if ( ciprefix( ".subckt", card->li_line ) || ciprefix( "x", card->li_line ) ) { - /* remove ( ) */ + if (ciprefix(".subckt", card->li_line) || ciprefix("x", card->li_line)) { + /* remove () */ str_ptr = card->li_line; - while( !isspace(*str_ptr) ) str_ptr++; // skip over .subckt, instance name - while( isspace(*str_ptr) ) str_ptr++; - if ( ciprefix( ".subckt", card->li_line ) ) { - while( !isspace(*str_ptr) ) str_ptr++; // skip over subckt name - while( isspace(*str_ptr) ) str_ptr++; + while (!isspace(*str_ptr)) + str_ptr++; // skip over .subckt, instance name + while (isspace(*str_ptr)) + str_ptr++; + if (ciprefix(".subckt", card->li_line)) { + while (!isspace(*str_ptr)) + str_ptr++; // skip over subckt name + while (isspace(*str_ptr)) + str_ptr++; } - if ( *str_ptr == '(' ) { + if (*str_ptr == '(') { *str_ptr = ' '; - while ( *str_ptr && *str_ptr != '\0' ) { - if ( *str_ptr == ')' ) { + while (*str_ptr && *str_ptr != '\0') { + if (*str_ptr == ')') { *str_ptr = ' '; break; } @@ -1216,18 +1243,21 @@ inp_fix_macro_param_func_paren_io( struct line *begin_card ) } } is_func = FALSE; - if ( ciprefix( ".param", card->li_line ) ) { + if (ciprefix(".param", card->li_line)) { str_ptr = card->li_line; - while ( !isspace( *str_ptr ) ) str_ptr++; // skip over .param - while ( isspace( *str_ptr ) ) str_ptr++; - while ( !isspace( *str_ptr ) && *str_ptr != '=' ) { - if ( *str_ptr == '(' ) is_func = TRUE; + while (!isspace(*str_ptr)) + str_ptr++; // skip over .param + while (isspace(*str_ptr)) + str_ptr++; + while (!isspace(*str_ptr) && *str_ptr != '=') { + if (*str_ptr == '(') + is_func = TRUE; str_ptr++; } - if ( is_func ) { - str_ptr = strstr( card->li_line, "=" ); - if ( str_ptr ) + if (is_func) { + str_ptr = strstr(card->li_line, "="); + if (str_ptr) *str_ptr = ' '; str_ptr = card->li_line + 1; *str_ptr = 'f'; @@ -1240,8 +1270,9 @@ inp_fix_macro_param_func_paren_io( struct line *begin_card ) } } + static char * -get_instance_subckt( char *line ) +get_instance_subckt(char *line) { char *equal_ptr = NULL, *end_ptr = line + strlen(line) - 1, *inst_name_ptr = NULL, *inst_name = NULL; char keep = ' '; @@ -1249,35 +1280,44 @@ get_instance_subckt( char *line ) // see if instance has parameters if ((equal_ptr = strstr(line, "=")) != NULL) { end_ptr = equal_ptr - 1; - while ( isspace(*end_ptr) ) end_ptr--; - while ( !isspace(*end_ptr) ) end_ptr--; - while ( isspace(*end_ptr) ) end_ptr--; + while (isspace(*end_ptr)) + end_ptr--; + while (!isspace(*end_ptr)) + end_ptr--; + while (isspace(*end_ptr)) + end_ptr--; end_ptr++; keep = *end_ptr; *end_ptr = '\0'; } inst_name_ptr = end_ptr; - while ( !isspace(*inst_name_ptr) ) inst_name_ptr--; + while (!isspace(*inst_name_ptr)) + inst_name_ptr--; inst_name_ptr++; inst_name = strdup(inst_name_ptr); - if ( equal_ptr ) *end_ptr = keep; + if (equal_ptr) + *end_ptr = keep; return inst_name; } + static char* -get_subckt_model_name( char *line ) +get_subckt_model_name(char *line) { char *name = line, *end_ptr = NULL, *subckt_name; char keep; - while ( !isspace( *name ) ) name++; // eat .subckt|.model - while ( isspace( *name ) ) name++; + while (!isspace(*name)) + name++; // eat .subckt|.model + while (isspace(*name)) + name++; end_ptr = name; - while ( !isspace( *end_ptr ) ) end_ptr++; + while (!isspace(*end_ptr)) + end_ptr++; keep = *end_ptr; *end_ptr = '\0'; @@ -1287,60 +1327,76 @@ get_subckt_model_name( char *line ) return subckt_name; } + static char* -get_model_name( char *line, int num_terminals ) +get_model_name(char *line, int num_terminals) { char *beg_ptr = line, *end_ptr, keep, *model_name = NULL; int i = 0; - while ( !isspace( *beg_ptr ) && *beg_ptr != '\0' ) beg_ptr++; /* eat device name */ - while ( isspace( *beg_ptr ) && *beg_ptr != '\0' ) beg_ptr++; + while (!isspace(*beg_ptr) && *beg_ptr != '\0') + beg_ptr++; /* eat device name */ + while (isspace(*beg_ptr) && *beg_ptr != '\0') + beg_ptr++; - for ( i = 0; i < num_terminals; i++ ) { /* skip the terminals */ - while ( !isspace( *beg_ptr ) && *beg_ptr != '\0' ) beg_ptr++; - while ( isspace( *beg_ptr ) && *beg_ptr != '\0' ) beg_ptr++; + for (i = 0; i < num_terminals; i++) { /* skip the terminals */ + while (!isspace(*beg_ptr) && *beg_ptr != '\0') + beg_ptr++; + while (isspace(*beg_ptr) && *beg_ptr != '\0') + beg_ptr++; } - if ( *line == 'r' ) { /* special dealing for r models */ - if((*beg_ptr=='+') || (*beg_ptr=='-') || isdigit(*beg_ptr)) { /* looking for a value before model */ - while ( !isspace( *beg_ptr ) && *beg_ptr != '\0' ) beg_ptr++; /* skip the value */ - while ( isspace( *beg_ptr ) && *beg_ptr != '\0' ) beg_ptr++; + if (*line == 'r') /* special dealing for r models */ + if ((*beg_ptr == '+') || (*beg_ptr == '-') || isdigit(*beg_ptr)) { /* looking for a value before model */ + while (!isspace(*beg_ptr) && *beg_ptr != '\0') + beg_ptr++; /* skip the value */ + while (isspace(*beg_ptr) && *beg_ptr != '\0') + beg_ptr++; } - } + end_ptr = beg_ptr; - while ( *end_ptr != '\0' && !isspace( *end_ptr ) ) end_ptr++; + while (*end_ptr != '\0' && !isspace(*end_ptr)) + end_ptr++; keep = *end_ptr; *end_ptr = '\0'; - model_name = strdup( beg_ptr ); + model_name = strdup(beg_ptr); *end_ptr = keep; return model_name; } + static char* -get_model_type( char *line ) +get_model_type(char *line) { char *model_type, *beg_ptr = line; - if ( !( ciprefix( ".model", line ))) + if (!(ciprefix(".model", line))) return NULL; - while ( !isspace( *beg_ptr ) && *beg_ptr != '\0' ) beg_ptr++; /* eat .model */ - while ( isspace( *beg_ptr ) && *beg_ptr != '\0' ) beg_ptr++; - while ( !isspace( *beg_ptr ) && *beg_ptr != '\0' ) beg_ptr++; /* eat model name */ - while ( isspace( *beg_ptr ) && *beg_ptr != '\0' ) beg_ptr++; + while (!isspace(*beg_ptr) && *beg_ptr != '\0') + beg_ptr++; /* eat .model */ + while (isspace(*beg_ptr) && *beg_ptr != '\0') + beg_ptr++; + while (!isspace(*beg_ptr) && *beg_ptr != '\0') + beg_ptr++; /* eat model name */ + while (isspace(*beg_ptr) && *beg_ptr != '\0') + beg_ptr++; model_type = gettok(&beg_ptr); return model_type; } + static char * -get_adevice_model_name( char *line ) +get_adevice_model_name(char *line) { char *model_name, *ptr_end = line + strlen(line), *ptr_beg, keep; - while ( isspace( *(ptr_end-1) ) ) ptr_end--; + while (isspace(*(ptr_end-1))) + ptr_end--; ptr_beg = ptr_end - 1; - while ( !isspace(*ptr_beg) ) ptr_beg--; + while (!isspace(*ptr_beg)) + ptr_beg--; ptr_beg++; keep = *ptr_end; *ptr_end = '\0'; @@ -1350,62 +1406,68 @@ get_adevice_model_name( char *line ) return model_name; } + static void -get_subckts_for_subckt( struct line *start_card, char *subckt_name, +get_subckts_for_subckt(struct line *start_card, char *subckt_name, char *used_subckt_names[], int *num_used_subckt_names, char *used_model_names[], int *num_used_model_names, - bool has_models ) + bool has_models) { struct line *card; char *line = NULL, *curr_subckt_name, *inst_subckt_name, *model_name, *new_names[100]; bool found_subckt = FALSE, have_subckt = FALSE, found_model = FALSE; int i, num_terminals = 0, tmp_cnt = 0; - for ( card = start_card; card != NULL; card = card->li_next ) { + for (card = start_card; card != NULL; card = card->li_next) { line = card->li_line; - if ( *line == '*' ) continue; + if (*line == '*') + continue; - if ( ( ciprefix( ".ends", line ) || ciprefix( ".eom", line ) ) && found_subckt ) + if ((ciprefix(".ends", line) || ciprefix(".eom", line)) && found_subckt) break; - if ( ciprefix( ".subckt", line ) || ciprefix( ".macro", line ) ) { - curr_subckt_name = get_subckt_model_name( line ); + if (ciprefix(".subckt", line) || ciprefix(".macro", line)) { + curr_subckt_name = get_subckt_model_name(line); - if ( strcmp( curr_subckt_name, subckt_name ) == 0 ) { + if (strcmp(curr_subckt_name, subckt_name) == 0) found_subckt = TRUE; - } tfree(curr_subckt_name); } - if ( found_subckt ) { - if ( *line == 'x' ) { - inst_subckt_name = get_instance_subckt( line ); + if (found_subckt) { + if (*line == 'x') { + inst_subckt_name = get_instance_subckt(line); have_subckt = FALSE; - for ( i = 0; i < *num_used_subckt_names; i++ ) - if ( strcmp( used_subckt_names[i], inst_subckt_name ) == 0 ) + for (i = 0; i < *num_used_subckt_names; i++) + if (strcmp(used_subckt_names[i], inst_subckt_name) == 0) have_subckt = TRUE; - if ( !have_subckt ) { + if (!have_subckt) { new_names[tmp_cnt++] = used_subckt_names[*num_used_subckt_names] = inst_subckt_name; *num_used_subckt_names = *num_used_subckt_names + 1; - } else tfree( inst_subckt_name ); - } else if ( *line == 'a' ) { - model_name = get_adevice_model_name( line ); + } else { + tfree(inst_subckt_name); + } + } else if (*line == 'a') { + model_name = get_adevice_model_name(line); found_model = FALSE; - for ( i = 0; i < *num_used_model_names; i++ ) - if ( strcmp( used_model_names[i], model_name ) == 0 ) found_model = TRUE; - if ( !found_model ) { + for (i = 0; i < *num_used_model_names; i++) + if (strcmp(used_model_names[i], model_name) == 0) + found_model = TRUE; + if (!found_model) { used_model_names[*num_used_model_names] = model_name; *num_used_model_names = *num_used_model_names + 1; - } else tfree( model_name ); - } else if ( has_models ) { - num_terminals = get_number_terminals( line ); + } else { + tfree(model_name); + } + } else if (has_models) { + num_terminals = get_number_terminals(line); - if ( num_terminals != 0 ) { + if (num_terminals != 0) { char *tmp_name, *tmp_name1; - tmp_name1 = tmp_name = model_name = get_model_name( line, num_terminals ); + tmp_name1 = tmp_name = model_name = get_model_name(line, num_terminals); - if ( isalpha( *model_name ) || + if (isalpha(*model_name) || /* first character is digit, second is alpha, third is digit, e.g. 1N4002 */ ((strlen(model_name) > 2) && isdigit(*tmp_name) && @@ -1415,252 +1477,302 @@ get_subckts_for_subckt( struct line *start_card, char *subckt_name, ((strlen(model_name) > 3) && isdigit(*tmp_name1) && isalpha(*(++tmp_name1)) && isalpha(*(++tmp_name1)) && isdigit(*(++tmp_name1)))) { found_model = FALSE; - for ( i = 0; i < *num_used_model_names; i++ ) - if ( strcmp( used_model_names[i], model_name ) == 0 ) found_model = TRUE; - if ( !found_model ) { + for (i = 0; i < *num_used_model_names; i++) + if (strcmp(used_model_names[i], model_name) == 0) found_model = TRUE; + if (!found_model) { used_model_names[*num_used_model_names] = model_name; *num_used_model_names = *num_used_model_names + 1; - } else tfree( model_name ); + } else { + tfree(model_name); + } } else { - tfree( model_name ); + tfree(model_name); } } } } } // now make recursive call on instances just found above - for ( i = 0; i < tmp_cnt; i++ ) - get_subckts_for_subckt( start_card, new_names[i], used_subckt_names, num_used_subckt_names, - used_model_names, num_used_model_names, has_models ); + for (i = 0; i < tmp_cnt; i++) + get_subckts_for_subckt(start_card, new_names[i], used_subckt_names, num_used_subckt_names, + used_model_names, num_used_model_names, has_models); } + /* check if current token matches model bin name -- .[0-9]+ */ static bool -model_bin_match( char* token, char* model_name ) +model_bin_match(char *token, char *model_name) { - char* dot_char; + char *dot_char; bool flag = FALSE; - if ( strncmp( model_name, token, strlen(token) ) == 0 ) { - if ((dot_char = strstr( model_name, "." )) != NULL) { + if (strncmp(model_name, token, strlen(token)) == 0) + if ((dot_char = strstr(model_name, ".")) != NULL) { flag = TRUE; dot_char++; - while( *dot_char != '\0' ) { - if ( !isdigit( *dot_char ) ) { + while (*dot_char != '\0') { + if (!isdigit(*dot_char)) { flag = FALSE; break; } dot_char++; } } - } + return flag; } + /* iterate through the deck and comment out unused subckts, models (don't want to waste time processing everything) also comment out .param lines with no parameters defined */ static void -comment_out_unused_subckt_models( struct line *start_card , int no_of_lines) +comment_out_unused_subckt_models(struct line *start_card, int no_of_lines) { struct line *card; char **used_subckt_names, **used_model_names, *line = NULL, *subckt_name, *model_name; int num_used_subckt_names = 0, num_used_model_names = 0, i = 0, num_terminals = 0, tmp_cnt = 0; - bool processing_subckt = FALSE, found_subckt = FALSE, remove_subckt = FALSE, found_model = FALSE, has_models = FALSE; + bool processing_subckt = FALSE, found_subckt = FALSE, remove_subckt = FALSE, found_model = FALSE, has_models = FALSE; int skip_control = 0, nested_subckt = 0; /* generate arrays of *char for subckt or model names. Start with 1000, but increase, if number of lines in deck is larger */ - if (no_of_lines < 1000) no_of_lines = 1000; + if (no_of_lines < 1000) + no_of_lines = 1000; used_subckt_names = TMALLOC(char*, no_of_lines); used_model_names = TMALLOC(char*, no_of_lines); - for ( card = start_card; card != NULL; card = card->li_next ) { - if ( ciprefix( ".model", card->li_line ) ) has_models = TRUE; - if ( ciprefix( ".cmodel", card->li_line ) ) has_models = TRUE; - if ( ciprefix( ".param", card->li_line ) && !strstr( card->li_line, "=" ) ) *card->li_line = '*'; + for (card = start_card; card != NULL; card = card->li_next) { + if (ciprefix(".model", card->li_line)) + has_models = TRUE; + if (ciprefix(".cmodel", card->li_line)) + has_models = TRUE; + if (ciprefix(".param", card->li_line) && !strstr(card->li_line, "=")) + *card->li_line = '*'; } - for ( card = start_card; card != NULL; card = card->li_next ) { + for (card = start_card; card != NULL; card = card->li_next) { line = card->li_line; - if ( *line == '*' ) continue; + if (*line == '*') + continue; /* there is no .subckt, .model or .param inside .control ... .endc */ - if ( ciprefix(".control", line) ) { + if (ciprefix(".control", line)) { skip_control ++; continue; - } else if( ciprefix(".endc", line) ) { + } else if (ciprefix(".endc", line)) { skip_control --; continue; - } else if(skip_control > 0) { + } else if (skip_control > 0) { continue; } - if ( ciprefix( ".subckt", line ) || ciprefix( ".macro", line ) ) processing_subckt = TRUE; - if ( ciprefix( ".ends", line ) || ciprefix( ".eom", line ) ) processing_subckt = FALSE; - if ( !processing_subckt ) { - if ( *line == 'x' ) { - subckt_name = get_instance_subckt( line ); + if (ciprefix(".subckt", line) || ciprefix(".macro", line)) + processing_subckt = TRUE; + if (ciprefix(".ends", line) || ciprefix(".eom", line)) + processing_subckt = FALSE; + if (!processing_subckt) { + if (*line == 'x') { + subckt_name = get_instance_subckt(line); found_subckt = FALSE; - for ( i = 0; i < num_used_subckt_names; i++ ) - if ( strcmp( used_subckt_names[i], subckt_name ) == 0 ) found_subckt = TRUE; - if ( !found_subckt ) { + for (i = 0; i < num_used_subckt_names; i++) + if (strcmp(used_subckt_names[i], subckt_name) == 0) found_subckt = TRUE; + if (!found_subckt) { used_subckt_names[num_used_subckt_names++] = subckt_name; tmp_cnt++; - } else tfree( subckt_name ); - } else if ( *line == 'a' ) { - model_name = get_adevice_model_name( line ); + } else { + tfree(subckt_name); + } + } else if (*line == 'a') { + model_name = get_adevice_model_name(line); found_model = FALSE; - for ( i = 0; i < num_used_model_names; i++ ) - if ( strcmp( used_model_names[i], model_name ) == 0 ) found_model = TRUE; - if ( !found_model ) used_model_names[num_used_model_names++] = model_name; - else tfree( model_name ); - } else if ( has_models ) { + for (i = 0; i < num_used_model_names; i++) + if (strcmp(used_model_names[i], model_name) == 0) + found_model = TRUE; + if (!found_model) + used_model_names[num_used_model_names++] = model_name; + else + tfree(model_name); + } else if (has_models) { /* This is a preliminary version, until we have found a reliable method to detect the model name out of the input line (Many options have to be taken into account.). */ - num_terminals = get_number_terminals( line ); - if ( num_terminals != 0 ) { + num_terminals = get_number_terminals(line); + if (num_terminals != 0) { bool model_ok = FALSE; char *tmp_name, *tmp_name1; - tmp_name = tmp_name1 = model_name = get_model_name( line, num_terminals ); + tmp_name = tmp_name1 = model_name = get_model_name(line, num_terminals); /* first character of model name is character from alphabet */ - if ( isalpha( *model_name ) ) model_ok = TRUE; + if (isalpha(*model_name)) + model_ok = TRUE; /* first character is digit, second is alpha, third is digit, e.g. 1N4002 */ - else if ((strlen(model_name) > 2) && isdigit(*tmp_name) && isalpha(*(++tmp_name)) && - isdigit(*(++tmp_name))) model_ok = TRUE; + else if ((strlen(model_name) > 2) && isdigit(*tmp_name) && + isalpha(*(++tmp_name)) && isdigit(*(++tmp_name))) + model_ok = TRUE; /* first character is is digit, second is alpha, third is alpha, fourth is digit e.g. 2SK456 */ - else if ((strlen(model_name) > 3) && isdigit(*tmp_name1) && isalpha(*(++tmp_name1)) && - isalpha(*(++tmp_name1)) && isdigit(*(++tmp_name1))) model_ok = TRUE; + else if ((strlen(model_name) > 3) && isdigit(*tmp_name1) && + isalpha(*(++tmp_name1)) && isalpha(*(++tmp_name1)) && + isdigit(*(++tmp_name1))) + model_ok = TRUE; /* Check if model has already been recognized, if not, add its name to list used_model_names[i] */ if (model_ok) { found_model = FALSE; - for ( i = 0; i < num_used_model_names; i++ ) - if ( strcmp( used_model_names[i], model_name ) == 0 ) found_model = TRUE; - if ( !found_model ) used_model_names[num_used_model_names++] = model_name; - else tfree( model_name ); + for (i = 0; i < num_used_model_names; i++) + if (strcmp(used_model_names[i], model_name) == 0) + found_model = TRUE; + if (!found_model) + used_model_names[num_used_model_names++] = model_name; + else + tfree(model_name); } else { - tfree( model_name ); + tfree(model_name); } } - } /* if ( has_models ) */ - } /* if ( !processing_subckt ) */ + } /* if (has_models) */ + } /* if (!processing_subckt) */ } /* for loop through all cards */ - for ( i = 0; i < tmp_cnt; i++ ) - get_subckts_for_subckt( start_card, used_subckt_names[i], used_subckt_names, - &num_used_subckt_names, used_model_names, &num_used_model_names, has_models ); + for (i = 0; i < tmp_cnt; i++) + get_subckts_for_subckt + (start_card, used_subckt_names[i], + used_subckt_names, &num_used_subckt_names, + used_model_names, &num_used_model_names, has_models); /* comment out any unused subckts, currently only at top level */ - for ( card = start_card; card != NULL; card = card->li_next ) { + for (card = start_card; card != NULL; card = card->li_next) { line = card->li_line; - if ( *line == '*' ) continue; + if (*line == '*') + continue; - if ( ciprefix( ".subckt", line ) || ciprefix( ".macro", line ) ) { + if (ciprefix(".subckt", line) || ciprefix(".macro", line)) { nested_subckt++; - subckt_name = get_subckt_model_name( line ); - if ( nested_subckt == 1 ) { + subckt_name = get_subckt_model_name(line); + if (nested_subckt == 1) { /* check if unused, only at top level */ remove_subckt = TRUE; - for ( i = 0; i < num_used_subckt_names; i++ ) - if ( strcmp( used_subckt_names[i], subckt_name ) == 0 ) remove_subckt = FALSE; + for (i = 0; i < num_used_subckt_names; i++) + if (strcmp(used_subckt_names[i], subckt_name) == 0) + remove_subckt = FALSE; } tfree(subckt_name); } - if ( ciprefix( ".ends", line ) || ciprefix( ".eom", line ) ) { + if (ciprefix(".ends", line) || ciprefix(".eom", line)) { nested_subckt--; - if ( remove_subckt ) + if (remove_subckt) *line = '*'; - if ( nested_subckt == 0 ) + if (nested_subckt == 0) remove_subckt = FALSE; } - if ( remove_subckt ) *line = '*'; - else if ( has_models && (ciprefix( ".model", line ) || ciprefix( ".cmodel", line )) ) { - char *model_type = get_model_type( line ); - model_name = get_subckt_model_name( line ); + if (remove_subckt) + *line = '*'; + else if (has_models && + (ciprefix(".model", line) || ciprefix(".cmodel", line))) + { + char *model_type = get_model_type(line); + model_name = get_subckt_model_name(line); /* keep R, L, C models because in addition to no. of terminals the value may be given, - as in RE1 1 2 800 newres dtemp=5, so model name may be token no. 4 or 5, + as in RE1 1 2 800 newres dtemp=5, so model name may be token no. 4 or 5, and, if 5, will not be detected by get_subckt_model_name()*/ - if (cieq(model_type,"c") || cieq(model_type,"l") || cieq(model_type,"r")) + if (cieq(model_type, "c") || + cieq(model_type, "l") || + cieq(model_type, "r")) + { found_model = TRUE; - else { + } else { found_model = FALSE; - for ( i = 0; i < num_used_model_names; i++ ) - if ( strcmp( used_model_names[i], model_name ) == 0 || model_bin_match( used_model_names[i], model_name ) ) found_model = TRUE; + for (i = 0; i < num_used_model_names; i++) + if (strcmp(used_model_names[i], model_name) == 0 || + model_bin_match(used_model_names[i], model_name)) + found_model = TRUE; } - if (model_type) tfree(model_type); + if (model_type) + tfree(model_type); #if ADMS >= 3 /* ngspice strategy to detect unused models fails with dynamic models - reason: # of terms unknown during parsing */ #else - if ( !found_model ) *line = '*'; + if (!found_model) + *line = '*'; #endif tfree(model_name); } } - for ( i = 0; i < num_used_subckt_names; i++ ) tfree(used_subckt_names[i]); - for ( i = 0; i < num_used_model_names; i++ ) tfree(used_model_names[i]); + for (i = 0; i < num_used_subckt_names; i++) + tfree(used_subckt_names[i]); + for (i = 0; i < num_used_model_names; i++) + tfree(used_model_names[i]); tfree(used_subckt_names); tfree(used_model_names); } - -/* replace ternary operator ? : by fcn ternary_fcn() in .param, .func, and .meas lines, +/* replace ternary operator ? : by fcn ternary_fcn() in .param, .func, and .meas lines, if all is FALSE, for all lines if all is TRUE */ static char* -inp_fix_ternary_operator_str( char *line, bool all ) +inp_fix_ternary_operator_str(char *line, bool all) { char *conditional, *if_str, *else_str, *question, *colon, keep, *str_ptr, *str_ptr2, *new_str; char *paren_ptr = NULL, *end_str = NULL, *beg_str = NULL; int count = 0; - if ( !strstr( line, "?" ) && !strstr( line, ":" ) ) return line; + if (!strstr(line, "?") && !strstr(line, ":")) + return line; str_ptr = line; - if ( all || ciprefix( ".param", line ) || ciprefix( ".func", line ) || ciprefix( ".meas", line ) ) { - + if (all || ciprefix(".param", line) || + ciprefix(".func", line) || ciprefix(".meas", line)) + { str_ptr = line; - if ( ciprefix( ".param", line ) || ciprefix( ".meas", line ) ) str_ptr = strstr( line, "=" ); - else str_ptr = strstr( line, ")" ); - if ((str_ptr == NULL) && all==FALSE) { - fprintf(stderr,"ERROR: mal formed .param, .func or .meas line: %s\n", line); + if (ciprefix(".param", line) || ciprefix(".meas", line)) + str_ptr = strstr(line, "="); + else + str_ptr = strstr(line, ")"); + + if ((str_ptr == NULL) && all == FALSE) { + fprintf(stderr, "ERROR: mal formed .param, .func or .meas line: %s\n", line); controlled_exit(EXIT_FAILURE); } str_ptr++; - while( isspace(*str_ptr) ) str_ptr++; - if ( *str_ptr == '{' ) { + while (isspace(*str_ptr)) str_ptr++; - while( isspace(*str_ptr) ) str_ptr++; + if (*str_ptr == '{') { + str_ptr++; + while (isspace(*str_ptr)) + str_ptr++; } - question = strstr( str_ptr, "?" ); - paren_ptr = strstr( str_ptr, "(" ); + question = strstr(str_ptr, "?"); + paren_ptr = strstr(str_ptr, "("); - if ( paren_ptr != NULL && paren_ptr < question ) { + if (paren_ptr != NULL && paren_ptr < question) paren_ptr = NULL; - } - } else return line; + + } else { + return line; + } // get conditional - str_ptr2 = question = strstr( str_ptr, "?" ); + str_ptr2 = question = strstr(str_ptr, "?"); str_ptr2--; - while ( isspace(*str_ptr2) ) str_ptr2--; - if ( *str_ptr2 == ')' ) { + while (isspace(*str_ptr2)) + str_ptr2--; + if (*str_ptr2 == ')') { count = 1; str_ptr = str_ptr2; - while ( (count != 0) && (str_ptr != line) ) { + while ((count != 0) && (str_ptr != line)) { str_ptr--; - if ( *str_ptr == '(' ) count--; - if ( *str_ptr == ')' ) count++; + if (*str_ptr == '(') + count--; + if (*str_ptr == ')') + count++; } } str_ptr2++; @@ -1677,33 +1789,39 @@ inp_fix_ternary_operator_str( char *line, bool all ) // get if str_ptr = question + 1; - while ( isspace(*str_ptr) ) str_ptr++; - if ( *str_ptr == '(' ) { + while (isspace(*str_ptr)) + str_ptr++; + if (*str_ptr == '(') { // find closing paren count = 1; str_ptr2 = str_ptr/* + 1*/; - while ( count != 0 && *str_ptr2 != '\0' ) { + while (count != 0 && *str_ptr2 != '\0') { str_ptr2++; - if ( *str_ptr2 == '(' ) count++; - if ( *str_ptr2 == ')' ) count--; + if (*str_ptr2 == '(') + count++; + if (*str_ptr2 == ')') + count--; } - if ( count != 0 ) { + if (count != 0) { fprintf(stderr, "ERROR: problem parsing 'if' of ternary string %s!\n", line); controlled_exit(EXIT_FAILURE); } colon = str_ptr2 + 1; - while ( *colon != ':' && *colon != '\0' ) colon++; - if ( *colon != ':' ) { - fprintf(stderr,"ERROR: problem parsing ternary string (finding ':') %s!\n", line); + while (*colon != ':' && *colon != '\0') + colon++; + if (*colon != ':') { + fprintf(stderr, "ERROR: problem parsing ternary string (finding ':') %s!\n", line); controlled_exit(EXIT_FAILURE); } str_ptr2 = colon - 1; - while ( isspace(*str_ptr2) ) str_ptr2--; - } else if ((colon = strstr( str_ptr, ":" )) != NULL) { + while (isspace(*str_ptr2)) + str_ptr2--; + } else if ((colon = strstr(str_ptr, ":")) != NULL) { str_ptr2 = colon - 1; - while ( isspace(*str_ptr2) ) str_ptr2--; + while (isspace(*str_ptr2)) + str_ptr2--; } else { - fprintf(stderr,"ERROR: problem parsing ternary string (missing ':') %s!\n", line); + fprintf(stderr, "ERROR: problem parsing ternary string (missing ':') %s!\n", line); controlled_exit(EXIT_FAILURE); } str_ptr2++; @@ -1714,29 +1832,32 @@ inp_fix_ternary_operator_str( char *line, bool all ) // get else str_ptr = colon + 1; - while ( isspace(*str_ptr) ) str_ptr++; - if ( paren_ptr != NULL ) { + while (isspace(*str_ptr)) + str_ptr++; + if (paren_ptr != NULL) { // find end paren ')' bool found_paren = FALSE; count = 0; str_ptr2 = str_ptr; - while ( *str_ptr2 != '\0' ) { - if ( *str_ptr2 == '(' ) { + while (*str_ptr2 != '\0') { + if (*str_ptr2 == '(') { count++; found_paren = TRUE; } - if ( *str_ptr2 == ')' ) count--; + if (*str_ptr2 == ')') + count--; str_ptr2++; - if ( found_paren && count == 0 ) break; + if (found_paren && count == 0) + break; } - if ( found_paren && count != 0 ) { - fprintf( stderr, "ERROR: problem parsing ternary line %s!\n", line ); + if (found_paren && count != 0) { + fprintf(stderr, "ERROR: problem parsing ternary line %s!\n", line); controlled_exit(EXIT_FAILURE); } keep = *str_ptr2; *str_ptr2 = '\0'; else_str = inp_fix_ternary_operator_str(strdup(str_ptr), all); - if ( keep != '}' ) { + if (keep != '}') { end_str = inp_fix_ternary_operator_str(strdup(str_ptr2+1), all); } else { *str_ptr2 = keep; @@ -1754,21 +1875,21 @@ inp_fix_ternary_operator_str( char *line, bool all ) } } - if ( end_str != NULL ) { - if ( beg_str != NULL ) { + if (end_str != NULL) { + if (beg_str != NULL) { new_str = TMALLOC(char, strlen(beg_str) + strlen("ternary_fcn") + strlen(conditional) + strlen(if_str) + strlen(else_str) + strlen(end_str) + 5); - sprintf( new_str, "%sternary_fcn(%s,%s,%s)%s", beg_str, conditional, if_str, else_str, end_str ); + sprintf(new_str, "%sternary_fcn(%s,%s,%s)%s", beg_str, conditional, if_str, else_str, end_str); } else { new_str = TMALLOC(char, strlen("ternary_fcn") + strlen(conditional) + strlen(if_str) + strlen(else_str) + strlen(end_str) + 5); - sprintf( new_str, "ternary_fcn(%s,%s,%s)%s", conditional, if_str, else_str, end_str ); + sprintf(new_str, "ternary_fcn(%s,%s,%s)%s", conditional, if_str, else_str, end_str); } } else { - if ( beg_str != NULL ) { + if (beg_str != NULL) { new_str = TMALLOC(char, strlen(beg_str) + strlen("ternary_fcn") + strlen(conditional) + strlen(if_str) + strlen(else_str) + 5); - sprintf( new_str, "%sternary_fcn(%s,%s,%s)", beg_str, conditional, if_str, else_str ); + sprintf(new_str, "%sternary_fcn(%s,%s,%s)", beg_str, conditional, if_str, else_str); } else { new_str = TMALLOC(char, strlen("ternary_fcn") + strlen(conditional) + strlen(if_str) + strlen(else_str) + 5); - sprintf( new_str, "ternary_fcn(%s,%s,%s)", conditional, if_str, else_str ); + sprintf(new_str, "ternary_fcn(%s,%s,%s)", conditional, if_str, else_str); } } @@ -1776,36 +1897,44 @@ inp_fix_ternary_operator_str( char *line, bool all ) tfree(conditional); tfree(if_str); tfree(else_str); - if ( beg_str != NULL ) tfree(beg_str); - if ( end_str != NULL ) tfree(end_str); + if (beg_str != NULL) + tfree(beg_str); + if (end_str != NULL) + tfree(end_str); return new_str; } + static void -inp_fix_ternary_operator( struct line *start_card ) +inp_fix_ternary_operator(struct line *start_card) { struct line *card; char *line; bool found_control = FALSE; - for ( card = start_card; card != NULL; card = card->li_next ) { + for (card = start_card; card != NULL; card = card->li_next) { line = card->li_line; /* exclude replacement of ternary function between .control and .endc */ - if ( ciprefix( ".control", line ) ) found_control = TRUE; - if ( ciprefix( ".endc", line ) ) found_control = FALSE; - if (found_control) continue; + if (ciprefix(".control", line)) + found_control = TRUE; + if (ciprefix(".endc", line)) + found_control = FALSE; + if (found_control) + continue; /* ternary operator for B source done elsewhere */ - if ( *line == 'B' || *line == 'b' ) continue; - if ( *line == '*' ) continue; - if ( strstr( line, "?" ) && strstr( line, ":" ) ) { - card->li_line = inp_fix_ternary_operator_str( line, FALSE ); - } + if (*line == 'B' || *line == 'b') + continue; + if (*line == '*') + continue; + if (strstr(line, "?") && strstr(line, ":")) + card->li_line = inp_fix_ternary_operator_str(line, FALSE); } } + /*-------------------------------------------------------------------------* removes " " quotes, returns lower case letters, replaces non-printable characterss with '_' * @@ -1824,7 +1953,8 @@ inp_casefix(char *string) *string++ = ' '; while (*string && *string != '"') string++; - if (*string== '\0') continue; /* needed if string is "something ! */ + if (*string == '\0') + continue; /* needed if string is "something ! */ if (*string == '"') *string = ' '; } @@ -1838,14 +1968,15 @@ inp_casefix(char *string) #endif } + /* Strip all end-of-line comments from a deck */ static void inp_stripcomments_deck(struct line *deck) { - struct line *c=deck; - while( c!=NULL) { + struct line *c = deck; + while (c != NULL) { inp_stripcomments_line(c->li_line); - c= c->li_next; + c = c->li_next; } } @@ -1870,40 +2001,42 @@ inp_stripcomments_deck(struct line *deck) begins with a '*'). BUG: comment characters in side of string literals are not ignored. */ static void -inp_stripcomments_line(char * s) +inp_stripcomments_line(char *s) { - char c = ' '; /* anything other than a comment character */ - char * d = s; - if(*s=='\0') return; /* empty line */ - if(*s=='*') return; /* line is already a comment */ + char c = ' '; /* anything other than a comment character */ + char *d = s; + if (*s == '\0') + return; /* empty line */ + if (*s == '*') + return; /* line is already a comment */ /* look for comments */ - while((c=*d)!='\0') { + while ((c = *d) != '\0') { d++; - if (*d==';') { + if (*d == ';') { break; - } else if ((c=='$') && (*d==' ')) { - d--; /* move d back to first comment character */ + } else if ((c == '$') && (*d == ' ')) { + d--; /* move d back to first comment character */ break; - } else if( (*d==c) && ((c=='/') || (c=='-'))) { - d--; /* move d back to first comment character */ + } else if ((*d == c) && ((c == '/') || (c == '-'))) { + d--; /* move d back to first comment character */ break; } } /* d now points to the first comment character of the null at the string end */ /* check for special case of comment at start of line */ - if(d==s) { - *s = '*'; /* turn into normal comment */ + if (d == s) { + *s = '*'; /* turn into normal comment */ return; } - if(d>s) { + if (d>s) { d--; /* d now points to character just before comment */ /* eat white space at end of line */ - while(d>=s) { - if( (*d!=' ') && (*d!='\t' ) ) + while (d >= s) { + if ((*d != ' ') && (*d != '\t')) break; d--; } @@ -1915,22 +2048,23 @@ inp_stripcomments_line(char * s) /* Check for special case of comment at start of line with or without preceeding white space */ - if(d<=s) { + if (d <= s) { *s = '*'; /* turn the whole line into normal comment */ return; } - *d='\0'; /* terminate line in new location */ + *d = '\0'; /* terminate line in new location */ } + static void -inp_change_quotes( char *s ) +inp_change_quotes(char *s) { bool first_quote = FALSE; - while ( *s ) { - if ( *s == '\'' ) { - if ( first_quote == FALSE ) { + while (*s) { + if (*s == '\'') { + if (first_quote == FALSE) { *s = '{'; first_quote = TRUE; } else { @@ -1942,21 +2076,23 @@ inp_change_quotes( char *s ) } } + static char* -inp_fix_subckt( char *s ) +inp_fix_subckt(char *s) { - struct line *head=NULL, *newcard=NULL, *start_card=NULL, *end_card=NULL, *prev_card=NULL, *c=NULL; + struct line *head = NULL, *newcard = NULL, *start_card = NULL, *end_card = NULL, *prev_card = NULL, *c = NULL; char *equal, *beg, *buffer, *ptr1, *ptr2, *str, *new_str = NULL; char keep; int num_params = 0, i = 0, bracedepth = 0; /* find first '=' */ - equal = strstr( s, "=" ); - if ( !strstr( s, "params:" ) && equal != NULL ) { + equal = strstr(s, "="); + if (!strstr(s, "params:") && equal != NULL) { /* get subckt name (ptr1 will point to name) */ - for ( ptr1 = s; *ptr1 && !isspace(*ptr1); ptr1++ ) + for (ptr1 = s; *ptr1 && !isspace(*ptr1); ptr1++) ; - while ( isspace(*ptr1) ) ptr1++; - for ( ptr2 = ptr1; *ptr2 && !isspace(*ptr2) && !isquote(*ptr2); ptr2++ ) + while (isspace(*ptr1)) + ptr1++; + for (ptr2 = ptr1; *ptr2 && !isspace(*ptr2) && !isquote(*ptr2); ptr2++) ; keep = *ptr2; @@ -1969,34 +2105,39 @@ inp_fix_subckt( char *s ) /* go to beginning of first parameter word */ /* s will contain only subckt definition */ /* beg will point to start of param list */ - for ( beg = equal-1; *beg && isspace(*beg); beg-- ) + for (beg = equal-1; *beg && isspace(*beg); beg--) ; - for ( ; *beg && !isspace(*beg); beg-- ) + for ( ; *beg && !isspace(*beg); beg--) ; *beg = '\0'; beg++; head = alloc(struct line); /* create list of parameters that need to get sorted */ - while ( *beg && (ptr1 = strstr( beg, "=" )) != NULL ) { + while (*beg && (ptr1 = strstr(beg, "=")) != NULL) { #ifndef NOBRACE /* alternative patch to cope with spaces: get expression between braces {...} */ ptr2 = ptr1+1; ptr1--; - while ( isspace(*ptr1) ) ptr1--; - while ( !isspace(*ptr1) && *ptr1 != '\0' ) ptr1--; - ptr1++; /* ptr1 points to beginning of parameter */ + while (isspace(*ptr1)) + ptr1--; + while (!isspace(*ptr1) && *ptr1 != '\0') + ptr1--; + ptr1++; /* ptr1 points to beginning of parameter */ - while ( isspace(*ptr2) ) ptr2++; + while (isspace(*ptr2)) + ptr2++; /* if parameter is an expression and starts with '{', find closing '}' Braces maybe nested (will they ever be ?). */ if (*ptr2 == '{') { bracedepth = 1; while (bracedepth > 0) { ptr2++; - if (*ptr2 == '{') bracedepth++; - else if (*ptr2 == '}') bracedepth--; + if (*ptr2 == '{') + bracedepth++; + else if (*ptr2 == '}') + bracedepth--; else if (*ptr2 == '\0') { fprintf(stderr, "Error: Missing } in line %s\n", s); controlled_exit(EXIT_FAILURE); @@ -2006,15 +2147,16 @@ inp_fix_subckt( char *s ) } else /* take only the next token (separated by space) as the parameter */ - while ( *ptr2 && !isspace(*ptr2) ) ptr2++; /* ptr2 points past end of parameter */ + while (*ptr2 && !isspace(*ptr2)) + ptr2++; /* ptr2 points past end of parameter */ keep = *ptr2; - if( keep == '\0' ) { + if (keep == '\0') { /* End of string - don't go over end. */ - beg = ptr2 ; + beg = ptr2; } else { - *ptr2 = '\0' ; - beg = ptr2+1 ; + *ptr2 = '\0'; + beg = ptr2+1; } newcard = alloc(struct line); @@ -2023,32 +2165,35 @@ inp_fix_subckt( char *s ) newcard->li_line = str; newcard->li_next = NULL; - if ( start_card == NULL ) head->li_next = start_card = newcard; - else prev_card->li_next = newcard; + if (start_card == NULL) + head->li_next = start_card = newcard; + else + prev_card->li_next = newcard; prev_card = end_card = newcard; num_params++; } #else /* patch provided by Ivan Riis Nielsen */ - bool done=FALSE; - int buf_len=32, buf_idx=0; - char* buf=TMALLOC(char,buf_len), *p1=beg, *p2=beg; + bool done = FALSE; + int buf_len = 32, buf_idx = 0; + char *buf = TMALLOC(char, buf_len), *p1 = beg, *p2 = beg; while (!done) { while (*p2 && !isspace(*p2)) { - if (buf_idx>=buf_len) { + if (buf_idx >= buf_len) { buf_len *= 2; - buf = TREALLOC(char,buf,buf_len); + buf = TREALLOC(char, buf, buf_len); } buf[buf_idx++] = *(p2++); } - for (p1=p2; isspace(*p1); ++p1); - if (*p1=='\0' || !(strchr("+-*/<>=(!,{",p2[-1]) || strchr("+-*/<>=()!,}",*p1))) { - if (buf_idx>=buf_len) { + for (p1 = p2; isspace(*p1); ++p1) + ; + if (*p1 == '\0' || !(strchr("+-*/<>=(!,{", p2[-1]) || strchr("+-*/<>=()!,}", *p1))) { + if (buf_idx >= buf_len) { buf_len *= 2; - buf = TREALLOC(char,buf,buf_len); + buf = TREALLOC(char, buf, buf_len); } buf[buf_idx++] = '\0'; beg = p1; @@ -2059,8 +2204,10 @@ inp_fix_subckt( char *s ) newcard->li_line = str; newcard->li_next = NULL; - if ( start_card == NULL ) head->li_next = start_card = newcard; - else prev_card->li_next = newcard; + if (start_card == NULL) + head->li_next = start_card = newcard; + else + prev_card->li_next = newcard; prev_card = end_card = newcard; num_params++; @@ -2073,17 +2220,18 @@ inp_fix_subckt( char *s ) } #endif /* now sort parameters in order of dependencies */ - inp_sort_params( start_card, end_card, head, start_card, end_card ); + inp_sort_params(start_card, end_card, head, start_card, end_card); /* create new ordered parameter string for subckt call */ - c=head->li_next; + c = head->li_next; tfree(head); - for( i = 0; i < num_params && c!= NULL; i++ ) { - if ( new_str == NULL ) new_str = strdup(c->li_line); - else { + for (i = 0; i < num_params && c != NULL; i++) { + if (new_str == NULL) { + new_str = strdup(c->li_line); + } else { str = new_str; new_str = TMALLOC(char, strlen(str) + strlen(c->li_line) + 2); - sprintf( new_str, "%s %s", str, c->li_line ); + sprintf(new_str, "%s %s", str, c->li_line); tfree(str); } tfree(c->li_line); @@ -2094,7 +2242,7 @@ inp_fix_subckt( char *s ) /* create buffer and insert params: */ buffer = TMALLOC(char, strlen(s) + 9 + strlen(new_str) + 1); - sprintf( buffer, "%s params: %s", s, new_str ); + sprintf(buffer, "%s params: %s", s, new_str); tfree(s); tfree(new_str); @@ -2104,8 +2252,9 @@ inp_fix_subckt( char *s ) return s; } + static char* -inp_remove_ws( char *s ) +inp_remove_ws(char *s) { char *big_buff; int big_buff_index = 0; @@ -2115,28 +2264,36 @@ inp_remove_ws( char *s ) big_buff = TMALLOC(char, strlen(s) + 1); curr = s; - while ( *curr != '\0' ) { - if ( *curr == '{' ) is_expression = TRUE; - if ( *curr == '}' ) is_expression = FALSE; + while (*curr != '\0') { + if (*curr == '{') + is_expression = TRUE; + if (*curr == '}') + is_expression = FALSE; big_buff[big_buff_index++] = *curr; - if ( *curr == '=' || (is_expression && (is_arith_char(*curr) || *curr == ',')) ) { + if (*curr == '=' || (is_expression && (is_arith_char(*curr) || *curr == ','))) { curr++; - while ( isspace(*curr) ) curr++; + while (isspace(*curr)) + curr++; - if ( *curr == '{' ) is_expression = TRUE; - if ( *curr == '}' ) is_expression = FALSE; + if (*curr == '{') + is_expression = TRUE; + if (*curr == '}') + is_expression = FALSE; big_buff[big_buff_index++] = *curr; } - if ( *curr != '\0' ) + if (*curr != '\0') curr++; - if ( isspace(*curr) ) { - while ( isspace(*curr) ) curr++; - if ( is_expression ) { - if ( *curr != '=' && !is_arith_char(*curr) && *curr != ',' ) big_buff[big_buff_index++] = ' '; + if (isspace(*curr)) { + while (isspace(*curr)) + curr++; + if (is_expression) { + if (*curr != '=' && !is_arith_char(*curr) && *curr != ',') + big_buff[big_buff_index++] = ' '; } else { - if ( *curr != '=' ) big_buff[big_buff_index++] = ' '; + if (*curr != '=') + big_buff[big_buff_index++] = ' '; } } } @@ -2151,29 +2308,32 @@ inp_remove_ws( char *s ) return buffer; } + /* change quotes from '' to {} .subckt name 1 2 3 params: l=1 w=2 --> .subckt name 1 2 3 l=1 w=2 - x1 1 2 3 params: l=1 w=2 --> x1 1 2 3 l=1 w=2 + x1 1 2 3 params: l=1 w=2 --> x1 1 2 3 l=1 w=2 modify .subckt lines by calling inp_fix_subckt() No changes to lines in .control section ! -*/ +*/ static void inp_fix_for_numparam(struct line *deck) { bool found_control = FALSE; - struct line *c=deck; + struct line *c = deck; char *str_ptr; - while( c!=NULL) { - if ( ciprefix( "*lib", c->li_line ) || ciprefix( "*inc", c->li_line ) ) { + while (c != NULL) { + if (ciprefix("*lib", c->li_line) || ciprefix("*inc", c->li_line)) { c = c->li_next; continue; } /* exclude lines between .control and .endc from getting quotes changed */ - if ( ciprefix( ".control", c->li_line ) ) found_control = TRUE; - if ( ciprefix( ".endc", c->li_line ) ) found_control = FALSE; + if (ciprefix(".control", c->li_line)) + found_control = TRUE; + if (ciprefix(".endc", c->li_line)) + found_control = FALSE; if (found_control) { c = c->li_next; continue; @@ -2181,39 +2341,39 @@ inp_fix_for_numparam(struct line *deck) inp_change_quotes(c->li_line); - if ((inp_compat_mode == COMPATMODE_ALL) || (inp_compat_mode == COMPATMODE_PS)) { - if ( ciprefix( ".subckt", c->li_line ) || ciprefix( "x", c->li_line ) ) { + if ((inp_compat_mode == COMPATMODE_ALL) || (inp_compat_mode == COMPATMODE_PS)) + if (ciprefix(".subckt", c->li_line) || ciprefix("x", c->li_line)) { /* remove params: */ str_ptr = strstr(c->li_line, "params:"); - if (str_ptr) { + if (str_ptr) memcpy(str_ptr, " ", 7); - } } - } - if ( ciprefix( ".subckt", c->li_line ) ) { + if (ciprefix(".subckt", c->li_line)) c->li_line = inp_fix_subckt(c->li_line); - } c = c->li_next; } } + static void -inp_remove_excess_ws(struct line *deck ) +inp_remove_excess_ws(struct line *deck) { struct line *c = deck; bool found_control = FALSE; - while ( c != NULL ) { - if ( *c->li_line == '*' ) { + while (c != NULL) { + if (*c->li_line == '*') { c = c->li_next; continue; } /* exclude echo lines between .control and .endc from removing white spaces */ - if ( ciprefix( ".control", c->li_line ) ) found_control = TRUE; - if ( ciprefix( ".endc", c->li_line ) ) found_control = FALSE; - if ((found_control) && (ciprefix( "echo", c->li_line ))) { + if (ciprefix(".control", c->li_line)) + found_control = TRUE; + if (ciprefix(".endc", c->li_line)) + found_control = FALSE; + if ((found_control) && (ciprefix("echo", c->li_line))) { c = c->li_next; continue; } @@ -2222,8 +2382,9 @@ inp_remove_excess_ws(struct line *deck ) } } + static void -inp_determine_libraries( struct line *deck, char *lib_name ) +inp_determine_libraries(struct line *deck, char *lib_name) { struct line *c = deck; char *line, *s, *t, *y, *z, keep_char1, keep_char2; @@ -2231,58 +2392,64 @@ inp_determine_libraries( struct line *deck, char *lib_name ) bool found_lib_name = FALSE; bool read_line = FALSE; - if ( lib_name == NULL ) read_line = TRUE; + if (lib_name == NULL) + read_line = TRUE; - while ( c != NULL ) { + while (c != NULL) { line = c->li_line; - if ( ciprefix( ".endl", line ) && lib_name != NULL ) read_line = FALSE; + if (ciprefix(".endl", line) && lib_name != NULL) + read_line = FALSE; - if ( ciprefix( "*lib", line ) || ciprefix( ".lib", line ) ) { - for ( s = line; *s && !isspace(*s); s++) + if (ciprefix("*lib", line) || ciprefix(".lib", line)) { + for (s = line; *s && !isspace(*s); s++) ; - while ( isspace(*s) || isquote(*s) ) s++; - for ( t = s; *t && !isspace(*t) && !isquote(*t); t++ ) + while (isspace(*s) || isquote(*s)) + s++; + for (t = s; *t && !isspace(*t) && !isquote(*t); t++) ; y = t; - while ( isspace(*y) || isquote(*y) ) y++; + while (isspace(*y) || isquote(*y)) + y++; /* .lib */ - if ( !*y ) { + if (!*y) { keep_char1 = *t; *t = '\0'; - if ( lib_name != NULL && strcmp( lib_name, s ) == 0 ) read_line = TRUE; + if (lib_name != NULL && strcmp(lib_name, s) == 0) + read_line = TRUE; *t = keep_char1; } /* .lib */ - else if ( read_line == TRUE ) { + else if (read_line == TRUE) { char *copys = NULL; - for ( z = y; *z && !isspace(*z) && !isquote(*z); z++ ) + for (z = y; *z && !isspace(*z) && !isquote(*z); z++) ; keep_char1 = *t; keep_char2 = *z; *t = '\0'; *z = '\0'; - if ( *s == '~' ) { + if (*s == '~') { copys = cp_tildexpand(s); - if ( copys ) + if (copys) s = copys; } - for ( i = 0; i < num_libraries; i++ ) - if ( cieq( library_file[i], s ) ) { + for (i = 0; i < num_libraries; i++) + if (cieq(library_file[i], s)) { found_lib_name = FALSE; - for ( j = 0; j < num_lib_names[i] && found_lib_name == FALSE; j++ ) - if ( strcmp( library_name[i][j], y ) == 0 ) found_lib_name = TRUE; + for (j = 0; j < num_lib_names[i] && found_lib_name == FALSE; j++) + if (strcmp(library_name[i][j], y) == 0) + found_lib_name = TRUE; - if ( found_lib_name == FALSE ) { + if (found_lib_name == FALSE) { library_ll_ptr[i][num_lib_names[i]] = c; library_name[i][num_lib_names[i]++] = strdup(y); /* see if other libraries referenced */ - inp_determine_libraries( libraries[i], y ); + inp_determine_libraries(libraries[i], y); } } *line = '*'; /* comment out .lib line */ @@ -2295,66 +2462,71 @@ inp_determine_libraries( struct line *deck, char *lib_name ) } } + static void inp_init_lib_data(void) { int i; - for ( i = 0; i < num_libraries; i++ ) + for (i = 0; i < num_libraries; i++) num_lib_names[i] = 0; } + static char* -inp_get_subckt_name( char *s ) +inp_get_subckt_name(char *s) { - char *end_ptr = strstr( s, "=" ); + char *end_ptr = strstr(s, "="); char *subckt_name, *subckt_name_copy; char keep; - if ( end_ptr != NULL ) { + if (end_ptr != NULL) { end_ptr--; - while ( isspace(*end_ptr) ) end_ptr--; - for(; *end_ptr && !isspace(*end_ptr); end_ptr--) + while (isspace(*end_ptr)) + end_ptr--; + for (; *end_ptr && !isspace(*end_ptr); end_ptr--) ; } else { end_ptr = s + strlen(s); } subckt_name = end_ptr; - while ( isspace( *subckt_name ) ) subckt_name--; - for(; !isspace(*subckt_name); subckt_name-- ) + while (isspace(*subckt_name)) + subckt_name--; + for (; !isspace(*subckt_name); subckt_name--) ; subckt_name++; keep = *end_ptr; *end_ptr = '\0'; - subckt_name_copy = strdup( subckt_name ); + subckt_name_copy = strdup(subckt_name); *end_ptr = keep; return subckt_name_copy; } + static int -inp_get_params( char *line, char *param_names[], char *param_values[] ) +inp_get_params(char *line, char *param_names[], char *param_values[]) { - char *equal_ptr = strstr( line, "=" ); + char *equal_ptr = strstr(line, "="); char *end, *name, *value; int num_params = 0; char tmp_str[1000]; char keep; bool is_expression = FALSE; - while ( (equal_ptr = strstr( line, "=" )) != NULL ) { + while ((equal_ptr = strstr(line, "=")) != NULL) { // check for equality '==' - if ( *(equal_ptr+1) == '=' ) { + if (*(equal_ptr+1) == '=') { line = equal_ptr+2; continue; } // check for '!=', '<=', '>=' - if ( *(equal_ptr-1) == '!' || *(equal_ptr-1) == '<' || *(equal_ptr-1) == '>' ) { + if (*(equal_ptr-1) == '!' || *(equal_ptr-1) == '<' || *(equal_ptr-1) == '>') { line = equal_ptr+1; continue; } @@ -2363,9 +2535,11 @@ inp_get_params( char *line, char *param_names[], char *param_values[] ) /* get parameter name */ name = equal_ptr - 1; - while ( *name && isspace(*name) ) name--; + while (*name && isspace(*name)) + name--; end = name + 1; - while ( *name && !isspace(*name) ) name--; + while (*name && !isspace(*name)) + name--; name++; keep = *end; @@ -2375,22 +2549,27 @@ inp_get_params( char *line, char *param_names[], char *param_values[] ) /* get parameter value */ value = equal_ptr + 1; - while ( *value && isspace(*value) ) value++; + while (*value && isspace(*value)) + value++; - if ( *value == '{' ) is_expression = TRUE; + if (*value == '{') + is_expression = TRUE; end = value; - if ( is_expression ) { - while ( *end && *end != '}' ) end++; - } else { - while ( *end && !isspace(*end) ) end++; - } - if ( is_expression ) end++; + if (is_expression) + while (*end && *end != '}') + end++; + else + while (*end && !isspace(*end)) + end++; + + if (is_expression) + end++; keep = *end; *end = '\0'; - if ( *value != '{' && - !( isdigit( *value ) || ( *value == '.' && isdigit(*(value+1)) ) ) ) { - sprintf( tmp_str, "{%s}", value ); + if (*value != '{' && + !(isdigit(*value) || (*value == '.' && isdigit(*(value+1))))) { + sprintf(tmp_str, "{%s}", value); value = tmp_str; } param_values[num_params-1] = strdup(value); @@ -2402,76 +2581,79 @@ inp_get_params( char *line, char *param_names[], char *param_values[] ) return num_params; } + static char* -inp_fix_inst_line( char *inst_line, +inp_fix_inst_line(char *inst_line, int num_subckt_params, char *subckt_param_names[], char *subckt_param_values[], - int num_inst_params, char *inst_param_names[], char *inst_param_values[] ) + int num_inst_params, char *inst_param_names[], char *inst_param_values[]) { - char *end = strstr( inst_line, "=" ), *inst_name, *inst_name_end = inst_line; + char *end = strstr(inst_line, "="), *inst_name, *inst_name_end = inst_line; char *curr_line = inst_line, *new_line = NULL; char keep; int i, j; - while ( !isspace(*inst_name_end) ) inst_name_end++; + while (!isspace(*inst_name_end)) + inst_name_end++; keep = *inst_name_end; *inst_name_end = '\0'; - inst_name = strdup( inst_line ); + inst_name = strdup(inst_line); *inst_name_end = keep; - if ( end != NULL ) { + if (end != NULL) { end--; - while ( isspace( *end ) ) end--; - while ( !isspace( *end ) ) end--; + while (isspace(*end)) + end--; + while (!isspace(*end)) + end--; *end = '\0'; } - for ( i = 0; i < num_subckt_params; i++ ) { - for ( j = 0; j < num_inst_params; j++ ) { - if ( strcmp( subckt_param_names[i], inst_param_names[j] ) == 0 ) { - tfree( subckt_param_values[i] ); - subckt_param_values[i] = strdup( inst_param_values[j] ); + for (i = 0; i < num_subckt_params; i++) + for (j = 0; j < num_inst_params; j++) + if (strcmp(subckt_param_names[i], inst_param_names[j]) == 0) { + tfree(subckt_param_values[i]); + subckt_param_values[i] = strdup(inst_param_values[j]); } - } - } - for ( i = 0; i < num_subckt_params; i++ ) { - new_line = TMALLOC(char, strlen( curr_line ) + strlen( subckt_param_values[i] ) + 2); - sprintf( new_line, "%s %s", curr_line, subckt_param_values[i] ); + for (i = 0; i < num_subckt_params; i++) { + new_line = TMALLOC(char, strlen(curr_line) + strlen(subckt_param_values[i]) + 2); + sprintf(new_line, "%s %s", curr_line, subckt_param_values[i]); - tfree( curr_line ); - tfree( subckt_param_names[i] ); - tfree( subckt_param_values[i] ); + tfree(curr_line); + tfree(subckt_param_names[i]); + tfree(subckt_param_values[i]); curr_line = new_line; } - for ( i = 0; i < num_inst_params; i++ ) { - tfree( inst_param_names[i] ); - tfree( inst_param_values[i] ); + for (i = 0; i < num_inst_params; i++) { + tfree(inst_param_names[i]); + tfree(inst_param_values[i]); } - tfree( inst_name ); + tfree(inst_name); return curr_line; } + static bool -found_mult_param( int num_params, char *param_names[] ) +found_mult_param(int num_params, char *param_names[]) { bool found_mult = FALSE; int i; - for ( i = 0; i < num_params; i++ ) { - if ( strcmp( param_names[i], "m" ) == 0 ) { + for (i = 0; i < num_params; i++) + if (strcmp(param_names[i], "m") == 0) found_mult = TRUE; - } - } + return found_mult; } + static int -inp_fix_subckt_multiplier( struct line *subckt_card, - int num_subckt_params, char *subckt_param_names[], char *subckt_param_values[] ) +inp_fix_subckt_multiplier(struct line *subckt_card, + int num_subckt_params, char *subckt_param_names[], char *subckt_param_values[]) { struct line *card; char *new_str; @@ -2480,37 +2662,38 @@ inp_fix_subckt_multiplier( struct line *subckt_card, subckt_param_values[num_subckt_params] = strdup("1"); num_subckt_params = num_subckt_params + 1; - if ( !strstr( subckt_card->li_line, "params:" ) ) { - new_str = TMALLOC(char, strlen( subckt_card->li_line ) + 13); - sprintf( new_str, "%s params: m=1", subckt_card->li_line ); - subckt_w_params[num_subckt_w_params++] = get_subckt_model_name( subckt_card->li_line ); + if (!strstr(subckt_card->li_line, "params:")) { + new_str = TMALLOC(char, strlen(subckt_card->li_line) + 13); + sprintf(new_str, "%s params: m=1", subckt_card->li_line); + subckt_w_params[num_subckt_w_params++] = get_subckt_model_name(subckt_card->li_line); } else { - new_str = TMALLOC(char, strlen( subckt_card->li_line ) + 5); - sprintf( new_str, "%s m=1", subckt_card->li_line ); + new_str = TMALLOC(char, strlen(subckt_card->li_line) + 5); + sprintf(new_str, "%s m=1", subckt_card->li_line); } - tfree( subckt_card->li_line ); + tfree(subckt_card->li_line); subckt_card->li_line = new_str; - for ( card = subckt_card->li_next; - card != NULL && !ciprefix( ".ends", card->li_line ); - card = card->li_next ) { + for (card = subckt_card->li_next; + card != NULL && !ciprefix(".ends", card->li_line); + card = card->li_next) { /* no 'm' for B line or comment line */ if ((*(card->li_line) == '*') || (*(card->li_line) == 'b')) continue; /* no 'm' for model cards */ if (ciprefix(".model", card->li_line)) continue; - new_str = TMALLOC(char, strlen( card->li_line ) + 7); - sprintf( new_str, "%s m={m}", card->li_line ); + new_str = TMALLOC(char, strlen(card->li_line) + 7); + sprintf(new_str, "%s m={m}", card->li_line); - tfree( card->li_line ); + tfree(card->li_line); card->li_line = new_str; } return num_subckt_params; } + static void inp_fix_inst_calls_for_numparam(struct line *deck) { @@ -2526,57 +2709,57 @@ inp_fix_inst_calls_for_numparam(struct line *deck) char name_w_space[1000]; int num_subckt_params = 0; int num_inst_params = 0; - int i,j,k; + int i, j, k; bool flag = FALSE; bool found_subckt = FALSE; bool found_param_match = FALSE; // first iterate through instances and find occurences where 'm' multiplier needs to be // added to the subcircuit -- subsequent instances will then need this parameter as well - for ( c = deck; c != NULL; c = c->li_next ) { + for (c = deck; c != NULL; c = c->li_next) { inst_line = c->li_line; - if ( *inst_line == '*' ) { + if (*inst_line == '*') continue; - } - if ( ciprefix( "x", inst_line ) ) { - num_inst_params = inp_get_params( inst_line, inst_param_names, inst_param_values ); - subckt_name = inp_get_subckt_name( inst_line ); - if ( found_mult_param( num_inst_params, inst_param_names ) ) { + if (ciprefix("x", inst_line)) { + num_inst_params = inp_get_params(inst_line, inst_param_names, inst_param_values); + subckt_name = inp_get_subckt_name(inst_line); + + if (found_mult_param(num_inst_params, inst_param_names)) { flag = FALSE; // iterate through the deck to find the subckt (last one defined wins) d = deck; - while ( d != NULL ) { + while (d != NULL) { subckt_line = d->li_line; - if ( ciprefix( ".subckt", subckt_line ) ) { - for ( ; *subckt_line && !isspace(*subckt_line); subckt_line++ ) + if (ciprefix(".subckt", subckt_line)) { + for (; *subckt_line && !isspace(*subckt_line); subckt_line++) ; - while ( isspace(*subckt_line) ) subckt_line++; + while (isspace(*subckt_line)) + subckt_line++; - sprintf( name_w_space, "%s ", subckt_name ); - if ( strncmp( subckt_line, name_w_space, strlen(name_w_space) ) == 0 ) { + sprintf(name_w_space, "%s ", subckt_name); + if (strncmp(subckt_line, name_w_space, strlen(name_w_space)) == 0) { p = d; flag = TRUE; } } d = d->li_next; } - if ( flag ) { - num_subckt_params = inp_get_params( p->li_line, subckt_param_names, subckt_param_values ); + if (flag) { + num_subckt_params = inp_get_params(p->li_line, subckt_param_names, subckt_param_values); - if ( num_subckt_params == 0 || !found_mult_param( num_subckt_params, subckt_param_names ) ) { - inp_fix_subckt_multiplier( p, num_subckt_params, subckt_param_names, subckt_param_values ); - } + if (num_subckt_params == 0 || !found_mult_param(num_subckt_params, subckt_param_names)) + inp_fix_subckt_multiplier(p, num_subckt_params, subckt_param_names, subckt_param_values); } } - tfree(subckt_name ); - if ( flag ) - for (i=0; i < num_subckt_params; i++) { + tfree(subckt_name); + if (flag) + for (i = 0; i < num_subckt_params; i++) { tfree(subckt_param_names[i]); tfree(subckt_param_values[i]); } - for (i=0; i < num_inst_params; i++) { + for (i = 0; i < num_inst_params; i++) { tfree(inst_param_names[i]); tfree(inst_param_values[i]); } @@ -2584,52 +2767,54 @@ inp_fix_inst_calls_for_numparam(struct line *deck) } c = deck; - while ( c != NULL ) { + while (c != NULL) { inst_line = c->li_line; - if ( *inst_line == '*' ) { + if (*inst_line == '*') { c = c->li_next; continue; } - if ( ciprefix( "x", inst_line ) ) { - subckt_name = inp_get_subckt_name( inst_line ); - for ( i = 0; i < num_subckt_w_params; i++ ) { - if ( strcmp( subckt_w_params[i], subckt_name ) == 0 ) { - sprintf( name_w_space, "%s ", subckt_name ); + if (ciprefix("x", inst_line)) { + subckt_name = inp_get_subckt_name(inst_line); + for (i = 0; i < num_subckt_w_params; i++) { + if (strcmp(subckt_w_params[i], subckt_name) == 0) { + sprintf(name_w_space, "%s ", subckt_name); /* find .subckt line */ found_subckt = FALSE; d = deck; - while ( d != NULL ) { + while (d != NULL) { subckt_line = d->li_line; - if ( ciprefix( ".subckt", subckt_line ) ) { - for ( ; *subckt_line && !isspace(*subckt_line); subckt_line++ ) + if (ciprefix(".subckt", subckt_line)) { + for (; *subckt_line && !isspace(*subckt_line); subckt_line++) ; - while ( isspace(*subckt_line) ) subckt_line++; + while (isspace(*subckt_line)) + subckt_line++; - if ( strncmp( subckt_line, name_w_space, strlen(name_w_space) ) == 0 ) { - num_subckt_params = inp_get_params( subckt_line, subckt_param_names, subckt_param_values ); - num_inst_params = inp_get_params( inst_line, inst_param_names, inst_param_values ); + if (strncmp(subckt_line, name_w_space, strlen(name_w_space)) == 0) { + num_subckt_params = inp_get_params(subckt_line, subckt_param_names, subckt_param_values); + num_inst_params = inp_get_params(inst_line, inst_param_names, inst_param_values); // make sure that if have inst params that one matches subckt found_param_match = FALSE; - if ( num_inst_params == 0 ) found_param_match = TRUE; - else { - for ( j = 0; j < num_inst_params; j++ ) { - for ( k = 0; k < num_subckt_params; k++ ) { - if ( strcmp( subckt_param_names[k], inst_param_names[j] ) == 0 ) { + if (num_inst_params == 0) { + found_param_match = TRUE; + } else { + for (j = 0; j < num_inst_params; j++) { + for (k = 0; k < num_subckt_params; k++) + if (strcmp(subckt_param_names[k], inst_param_names[j]) == 0) { found_param_match = TRUE; break; } - } - if ( found_param_match ) break; + if (found_param_match) + break; } } - if ( !found_param_match ) { + if (!found_param_match) { // comment out .subckt and continue - while ( d != NULL && !ciprefix( ".ends", d->li_line ) ) { + while (d != NULL && !ciprefix(".ends", d->li_line)) { *(d->li_line) = '*'; d = d->li_next; } @@ -2638,19 +2823,20 @@ inp_fix_inst_calls_for_numparam(struct line *deck) continue; } - c->li_line = inp_fix_inst_line( inst_line, num_subckt_params, subckt_param_names, subckt_param_values, num_inst_params, inst_param_names, inst_param_values ); + c->li_line = inp_fix_inst_line(inst_line, num_subckt_params, subckt_param_names, subckt_param_values, num_inst_params, inst_param_names, inst_param_values); found_subckt = TRUE; - for (i=0; i < num_subckt_params; i++) { + for (i = 0; i < num_subckt_params; i++) { tfree(subckt_param_names[i]); tfree(subckt_param_values[i]); } - for (i=0; i < num_inst_params; i++) { + for (i = 0; i < num_inst_params; i++) { tfree(inst_param_names[i]); tfree(inst_param_values[i]); } } } - if ( found_subckt ) break; + if (found_subckt) + break; d = d->li_next; } break; @@ -2662,8 +2848,9 @@ inp_fix_inst_calls_for_numparam(struct line *deck) } } + static void -inp_get_func_from_line( char *line ) +inp_get_func_from_line(char *line) { char *ptr, *end; char keep; @@ -2673,16 +2860,20 @@ inp_get_func_from_line( char *line ) int i = 0; /* get function name */ - while ( !isspace( *line ) ) line++; - while ( isspace( *line ) ) line++; + while (!isspace(*line)) + line++; + while (isspace(*line)) + line++; end = line; - while ( !isspace( *end ) && *end != '(' ) end++; + while (!isspace(*end) && *end != '(') + end++; keep = *end; *end = '\0'; /* see if already encountered this function */ - for ( i = 0; i < num_functions; i++ ) - if ( strcmp( func_names[i], line ) == 0 ) break; + for (i = 0; i < num_functions; i++) + if (strcmp(func_names[i], line) == 0) + break; func_names[num_functions++] = strdup(line); *end = keep; @@ -2690,23 +2881,27 @@ inp_get_func_from_line( char *line ) num_params = 0; /* get function parameters */ - while ( *end != '(' ) end++; - while ( *end != ')' ) { + while (*end != '(') end++; - while ( isspace( *end ) ) end++; + while (*end != ')') { + end++; + while (isspace(*end)) + end++; ptr = end; - while ( !isspace( *end ) && *end != ',' && *end != ')' ) end++; - if(end > ptr) + while (!isspace(*end) && *end != ',' && *end != ')') + end++; + if (end > ptr) func_params[num_functions-1][num_params++] = copy_substring(ptr, end); } num_parameters[num_functions-1] = num_params; /* get function macro */ str_len = 0; - while ( *end != '{' ) end++; + while (*end != '{') + end++; end++; - while ( *end && *end != '}' ) { - if ( !isspace(*end) ) + while (*end && *end != '}') { + if (!isspace(*end)) temp_buf[str_len++] = *end; end++; } @@ -2715,63 +2910,68 @@ inp_get_func_from_line( char *line ) func_macro[num_functions-1] = strdup(temp_buf); } + // // only grab global functions; skip subckt functions // static void -inp_grab_func( struct line *deck ) +inp_grab_func(struct line *deck) { struct line *c = deck; bool is_subckt = FALSE; - while ( c != NULL ) { - if ( *c->li_line == '*' ) { + while (c != NULL) { + if (*c->li_line == '*') { c = c->li_next; continue; } - if ( ciprefix( ".subckt", c->li_line ) ) is_subckt = TRUE; - if ( ciprefix( ".ends", c->li_line ) ) is_subckt = FALSE; + if (ciprefix(".subckt", c->li_line)) + is_subckt = TRUE; + if (ciprefix(".ends", c->li_line)) + is_subckt = FALSE; - if ( !is_subckt && ciprefix( ".func", c->li_line ) ) { - inp_get_func_from_line( c->li_line ); + if (!is_subckt && ciprefix(".func", c->li_line)) { + inp_get_func_from_line(c->li_line); *c->li_line = '*'; } c = c->li_next; } } + static void -inp_grab_subckt_func( struct line *subckt ) +inp_grab_subckt_func(struct line *subckt) { struct line *c = subckt; - while ( !ciprefix( ".ends", c->li_line ) ) { - if ( ciprefix( ".func", c->li_line ) ) { - inp_get_func_from_line( c->li_line ); + while (!ciprefix(".ends", c->li_line)) { + if (ciprefix(".func", c->li_line)) { + inp_get_func_from_line(c->li_line); *c->li_line = '*'; } c = c->li_next; } } + static char* -inp_do_macro_param_replace( int fcn_number, char *params[] ) +inp_do_macro_param_replace(int fcn_number, char *params[]) { char *param_ptr, *curr_ptr, *new_str, *curr_str = NULL, *search_ptr; char keep, before, after; int i; - if(num_parameters[fcn_number] == 0) + if (num_parameters[fcn_number] == 0) return strdup(func_macro[fcn_number]); - for ( i = 0; i < num_parameters[fcn_number]; i++ ) { - if ( curr_str == NULL ) + for (i = 0; i < num_parameters[fcn_number]; i++) { + if (curr_str == NULL) { search_ptr = curr_ptr = func_macro[fcn_number]; - else { + } else { search_ptr = curr_ptr = curr_str; curr_str = NULL; } - while ((param_ptr = strstr( search_ptr, func_params[fcn_number][i] ) ) != NULL ) { + while ((param_ptr = strstr(search_ptr, func_params[fcn_number][i])) != NULL) { /* make sure actually have the parameter name */ if (param_ptr == search_ptr) /* no valid 'before' */ @@ -2779,8 +2979,11 @@ inp_do_macro_param_replace( int fcn_number, char *params[] ) else before = *(param_ptr-1); after = *(param_ptr+strlen(func_params[fcn_number][i])); - if ( !(is_arith_char(before) || isspace(before) || before == ',' || before == '=' || (param_ptr-1) < curr_ptr ) || - !(is_arith_char(after) || isspace(after) || after == ',' || after == '=' || after == '\0' ) ) { + if (!(is_arith_char(before) || isspace(before) || + before == ',' || before == '=' || (param_ptr-1) < curr_ptr) || + !(is_arith_char(after) || isspace(after) || + after == ',' || after == '=' || after == '\0')) + { search_ptr = param_ptr + 1; continue; } @@ -2791,24 +2994,24 @@ inp_do_macro_param_replace( int fcn_number, char *params[] ) { size_t curr_str_len = curr_str ? strlen(curr_str) : 0; size_t len = strlen(curr_ptr) + strlen(params[i]) + 1; - if ( str_has_arith_char( params[i] ) ) { + if (str_has_arith_char(params[i])) { curr_str = TREALLOC(char, curr_str, curr_str_len + len + 2); - sprintf( curr_str + curr_str_len, "%s(%s)", curr_ptr, params[i] ); + sprintf(curr_str + curr_str_len, "%s(%s)", curr_ptr, params[i]); } else { curr_str = TREALLOC(char, curr_str, curr_str_len + len); - sprintf( curr_str + curr_str_len, "%s%s", curr_ptr, params[i] ); + sprintf(curr_str + curr_str_len, "%s%s", curr_ptr, params[i]); } } *param_ptr = keep; search_ptr = curr_ptr = param_ptr + strlen(func_params[fcn_number][i]); } - if ( param_ptr == NULL ) { - if ( curr_str == NULL ) { + if (param_ptr == NULL) { + if (curr_str == NULL) { curr_str = curr_ptr; } else { new_str = TMALLOC(char, strlen(curr_str) + strlen(curr_ptr) + 1); - sprintf( new_str, "%s%s", curr_str, curr_ptr ); + sprintf(new_str, "%s%s", curr_str, curr_ptr); tfree(curr_str); curr_str = new_str; } @@ -2817,8 +3020,9 @@ inp_do_macro_param_replace( int fcn_number, char *params[] ) return curr_str; } + static char* -inp_expand_macro_in_str( char *str ) +inp_expand_macro_in_str(char *str) { int i; char *c; @@ -2828,162 +3032,170 @@ inp_expand_macro_in_str( char *str ) char *orig_ptr = str, *search_ptr = str, *orig_str = strdup(str); char keep; -// printf("%s: enter(\"%s\")\n", __FUNCTION__, str); - while ( (open_paren_ptr = strchr(search_ptr, '(')) != NULL ) { + // printf("%s: enter(\"%s\")\n", __FUNCTION__, str); + while ((open_paren_ptr = strchr(search_ptr, '(')) != NULL) { fcn_name = open_paren_ptr; - while ( --fcn_name >= search_ptr ) - if(!isalnum(*fcn_name) && *fcn_name != '_') + while (--fcn_name >= search_ptr) + if (!isalnum(*fcn_name) && *fcn_name != '_') break; fcn_name++; search_ptr = open_paren_ptr + 1; - if ( open_paren_ptr == fcn_name ) + if (open_paren_ptr == fcn_name) continue; *open_paren_ptr = '\0'; - for ( i = 0; i < num_functions; i++ ) - if ( strcmp( func_names[i], fcn_name ) == 0 ) + for (i = 0; i < num_functions; i++) + if (strcmp(func_names[i], fcn_name) == 0) break; *open_paren_ptr = '('; - if(i >= num_functions) + if (i >= num_functions) continue; - /* find the closing paren */ num_parens = 1; - for ( c = open_paren_ptr + 1; *c; c++ ) { - if ( *c == '(' ) + for (c = open_paren_ptr + 1; *c; c++) { + if (*c == '(') num_parens++; - if ( *c == ')' && --num_parens == 0) + if (*c == ')' && --num_parens == 0) break; } - if ( num_parens ) { - fprintf( stderr, "ERROR: did not find closing parenthesis for function call in str: %s\n", orig_str ); + if (num_parens) { + fprintf(stderr, "ERROR: did not find closing parenthesis for function call in str: %s\n", orig_str); controlled_exit(EXIT_FAILURE); } close_paren_ptr = c; - /* if ( ciprefix( "v(", curr_ptr ) ) { - // look for any commas and change to ' ' - char *str_ptr = curr_ptr; - while ( *str_ptr != '\0' && *str_ptr != ')' ) { - if ( *str_ptr == ',' || *str_ptr == '(' ) *str_ptr = ' '; str_ptr++; } - if ( *str_ptr == ')' ) *str_ptr = ' '; - }*/ + /* + * if (ciprefix("v(", curr_ptr)) { + * // look for any commas and change to ' ' + * char *str_ptr = curr_ptr; + * while (*str_ptr != '\0' && *str_ptr != ')') { + * if (*str_ptr == ',' || *str_ptr == '(') + * *str_ptr = ' '; str_ptr++; } + * if (*str_ptr == ')') + * *str_ptr = ' '; + * } + */ /* get the parameters */ curr_ptr = open_paren_ptr + 1; - for (num_params=0; curr_ptr < close_paren_ptr; curr_ptr++) { + for (num_params = 0; curr_ptr < close_paren_ptr; curr_ptr++) { char *beg_parameter; int num_parens; - if( isspace(*curr_ptr) ) + if (isspace(*curr_ptr)) continue; beg_parameter = curr_ptr; num_parens = 0; - for(; curr_ptr < close_paren_ptr; curr_ptr++) { - if(*curr_ptr == '(') + for (; curr_ptr < close_paren_ptr; curr_ptr++) { + if (*curr_ptr == '(') num_parens++; - if(*curr_ptr == ')') + if (*curr_ptr == ')') num_parens--; - if(*curr_ptr == ',' && num_parens == 0) + if (*curr_ptr == ',' && num_parens == 0) break; } params[num_params++] = inp_expand_macro_in_str(copy_substring(beg_parameter, curr_ptr)); } - if ( num_parameters[i] != num_params ) { - fprintf( stderr, "ERROR: parameter mismatch for function call in str: %s\n", orig_str ); + if (num_parameters[i] != num_params) { + fprintf(stderr, "ERROR: parameter mismatch for function call in str: %s\n", orig_str); controlled_exit(EXIT_FAILURE); } - macro_str = inp_do_macro_param_replace( i, params ); + macro_str = inp_do_macro_param_replace(i, params); keep = *fcn_name; *fcn_name = '\0'; { size_t curr_str_len = curr_str ? strlen(curr_str) : 0; size_t len = strlen(str) + strlen(macro_str) + 3; curr_str = TREALLOC(char, curr_str, curr_str_len + len); - sprintf( curr_str + curr_str_len, "%s(%s)", str, macro_str ); + sprintf(curr_str + curr_str_len, "%s(%s)", str, macro_str); } *fcn_name = keep; search_ptr = str = close_paren_ptr + 1; } - if ( curr_str == NULL ) { + if (curr_str == NULL) { curr_str = orig_ptr; } else { - if ( str != NULL ) { + if (str != NULL) { size_t curr_str_len = strlen(curr_str); size_t len = strlen(str) + 1; curr_str = TREALLOC(char, curr_str, curr_str_len + len); - sprintf( curr_str + curr_str_len, "%s", str ); + sprintf(curr_str + curr_str_len, "%s", str); } tfree(orig_ptr); } tfree(orig_str); -// printf("%s: --> \"%s\"\n", __FUNCTION__, curr_str); + // printf("%s: --> \"%s\"\n", __FUNCTION__, curr_str); return curr_str; } + static void inp_expand_macros_in_func(void) { int i; - for ( i = 0; i < num_functions; i++ ) { - func_macro[i] = inp_expand_macro_in_str( func_macro[i] ); - } + for (i = 0; i < num_functions; i++) + func_macro[i] = inp_expand_macro_in_str(func_macro[i]); } + static void -inp_expand_macros_in_deck( struct line *deck ) +inp_expand_macros_in_deck(struct line *deck) { struct line *c = deck; int prev_num_functions = 0, i, j; - while ( c != NULL ) { - if ( *c->li_line == '*' ) { + while (c != NULL) { + if (*c->li_line == '*') { c = c->li_next; continue; } - if ( ciprefix( ".subckt", c->li_line ) ) { + if (ciprefix(".subckt", c->li_line)) { prev_num_functions = num_functions; - inp_grab_subckt_func( c ); - if ( prev_num_functions != num_functions ) inp_expand_macros_in_func(); + inp_grab_subckt_func(c); + if (prev_num_functions != num_functions) + inp_expand_macros_in_func(); } - if ( ciprefix( ".ends", c->li_line ) ) { - if ( prev_num_functions != num_functions ) { - for ( i = prev_num_functions; i < num_functions; i++ ) { - tfree( func_names[i] ); - tfree( func_macro[i] ); - for ( j = 0; j < num_parameters[i]; j++ ) tfree( func_params[i][j] ); + if (ciprefix(".ends", c->li_line)) { + if (prev_num_functions != num_functions) { + for (i = prev_num_functions; i < num_functions; i++) { + tfree(func_names[i]); + tfree(func_macro[i]); + for (j = 0; j < num_parameters[i]; j++) + tfree(func_params[i][j]); num_functions = prev_num_functions; } } } - if ( *c->li_line != '*' ) c->li_line = inp_expand_macro_in_str( c->li_line ); + if (*c->li_line != '*') + c->li_line = inp_expand_macro_in_str(c->li_line); c = c->li_next; } } + /* Put {} around tokens for handling in numparam. Searches for the next '=' in the line to become active. Several exceptions (eg. no 'set' or 'b' lines, no .cmodel lines, no lines between .control and .endc, no .option lines). Special handling of vectors with [] and complex values with < > - + h_vogt 20 April 2008 * For xspice and num_pram compatibility .cmodel added * .cmodel will be replaced by .model in inp_fix_param_values() @@ -2992,7 +3204,7 @@ inp_expand_macros_in_deck( struct line *deck ) * May be obsolete? */ static void -inp_fix_param_values( struct line *deck ) +inp_fix_param_values(struct line *deck) { struct line *c = deck; char *line, *beg_of_str, *end_of_str, *old_str, *equal_ptr, *new_str; @@ -3001,39 +3213,39 @@ inp_fix_param_values( struct line *deck ) wordlist *nwl; int parens; - while ( c != NULL ) { + while (c != NULL) { line = c->li_line; - if ( *line == '*' || (ciprefix( ".param", line ) && strstr( line, "{" )) ) { + if (*line == '*' || (ciprefix(".param", line) && strstr(line, "{"))) { c = c->li_next; continue; } - if ( ciprefix( ".control", line ) ) { + if (ciprefix(".control", line)) { control_section = TRUE; c = c->li_next; continue; } - if ( ciprefix( ".endc", line ) ) { + if (ciprefix(".endc", line)) { control_section = FALSE; c = c->li_next; continue; } - if ( control_section || ciprefix( ".option", line ) ) { + if (control_section || ciprefix(".option", line)) { c = c->li_next; /* no handling of params in "option" lines */ continue; } - if ( ciprefix( "set", line ) ) { + if (ciprefix("set", line)) { c = c->li_next; /* no handling of params in "set" lines */ continue; } - if ( *line == 'b' ) { + if (*line == 'b') { c = c->li_next; /* no handling of params in B source lines */ continue; } /* for xspice .cmodel: replace .cmodel with .model and skip entire line) */ - if ( ciprefix( ".cmodel", line ) ) { + if (ciprefix(".cmodel", line)) { *(++line) = 'm'; *(++line) = 'o'; *(++line) = 'd'; @@ -3045,51 +3257,58 @@ inp_fix_param_values( struct line *deck ) } /* exclude CIDER models */ - if ( ciprefix( ".model", line ) && ( strstr(line, "numos") || strstr(line, "numd") || strstr(line, "nbjt") || - strstr(line, "nbjt2") || strstr(line, "numd2") ) ) { + if (ciprefix(".model", line) && (strstr(line, "numos") || strstr(line, "numd") || + strstr(line, "nbjt") || strstr(line, "nbjt2") || + strstr(line, "numd2"))) { c = c->li_next; continue; } /* exclude CIDER devices with ic.file parameter */ - if ( strstr(line, "ic.file")) { + if (strstr(line, "ic.file")) { c = c->li_next; continue; } - while ((equal_ptr = strstr( line, "=" )) != NULL ) { + while ((equal_ptr = strstr(line, "=")) != NULL) { // special case: .MEASURE {DC|AC|TRAN} result FIND out_variable WHEN out_variable2=out_variable3 // no braces around out_variable3. out_variable3 may be v(...) or i(...) - if ( ciprefix( ".meas", line )) - if ((( *(equal_ptr+1) == 'v' ) || ( *(equal_ptr+1) == 'i' )) && ( *(equal_ptr+2) == '(' )) { + if (ciprefix(".meas", line)) + if (((*(equal_ptr+1) == 'v') || (*(equal_ptr+1) == 'i')) && + (*(equal_ptr+2) == '(')) + { // find closing ')' and skip token v(...) or i(...) - while (*equal_ptr != ')' && *(equal_ptr+1) != '\0') equal_ptr++; + while (*equal_ptr != ')' && *(equal_ptr+1) != '\0') + equal_ptr++; line = equal_ptr + 1; continue; } // skip over equality '==' - if ( *(equal_ptr+1) == '=' ) { + if (*(equal_ptr+1) == '=') { line += 2; continue; } // check for '!=', '<=', '>=' - if ( *(equal_ptr-1) == '!' || *(equal_ptr-1) == '<' || *(equal_ptr-1) == '>' ) { + if (*(equal_ptr-1) == '!' || *(equal_ptr-1) == '<' || *(equal_ptr-1) == '>') + { line += 1; continue; } beg_of_str = equal_ptr + 1; - while ( isspace(*beg_of_str) ) beg_of_str++; + while (isspace(*beg_of_str)) + beg_of_str++; /* all cases where no {} have to be put around selected token */ - if ( isdigit(*beg_of_str) - || *beg_of_str == '{' - || *beg_of_str == '.' - || *beg_of_str == '"' - || ( *beg_of_str == '-' && isdigit(*(beg_of_str+1)) ) - || ( *beg_of_str == '-' && (*(beg_of_str+1) == '.') && isdigit(*(beg_of_str+2)) ) - || ciprefix("true", beg_of_str) - || ciprefix("false", beg_of_str) ) { + if (isdigit(*beg_of_str) || + *beg_of_str == '{' || + *beg_of_str == '.' || + *beg_of_str == '"' || + (*beg_of_str == '-' && isdigit(*(beg_of_str+1))) || + (*beg_of_str == '-' && *(beg_of_str+1) == '.' && isdigit(*(beg_of_str+2))) || + ciprefix("true", beg_of_str) || + ciprefix("false", beg_of_str)) + { line = equal_ptr + 1; } else if (*beg_of_str == '[') { /* A vector following the '=' token: code to put curly brackets around all params @@ -3104,20 +3323,23 @@ inp_fix_param_values( struct line *deck ) nwl = NULL; for (;;) { natok = gettok(&vec_str); - if (!natok) break; + if (!natok) + break; buffer = TMALLOC(char, strlen(natok) + 4); - if ( isdigit(*natok) || *natok == '{' || *natok == '.' || - *natok == '"' || ( *natok == '-' && isdigit(*(natok+1)) ) || - ciprefix("true", natok) || ciprefix("false", natok) || - eq(natok, "<") || eq(natok, ">")) { + if (isdigit(*natok) || *natok == '{' || *natok == '.' || + *natok == '"' || (*natok == '-' && isdigit(*(natok+1))) || + ciprefix("true", natok) || ciprefix("false", natok) || + eq(natok, "<") || eq(natok, ">")) + { (void) sprintf(buffer, "%s", natok); /* A complex value found inside a vector [< x1 y1> ] */ /* < xx and yy > have been dealt with before */ /* */ } else if (strchr(natok, '>')) { - if (isdigit(*natok) || ( *natok == '-' && isdigit(*(natok+1))) ) { + if (isdigit(*natok) || (*natok == '-' && isdigit(*(natok+1)))) { (void) sprintf(buffer, "%s", natok); } else { whereisgt = strchr(natok, '>'); @@ -3148,7 +3370,7 @@ inp_fix_param_values( struct line *deck ) /* insert new vector into actual line */ *equal_ptr = '\0'; new_str = TMALLOC(char, strlen(c->li_line) + strlen(newvec) + strlen(end_of_str + 1) + 5); - sprintf( new_str, "%s=[%s] %s", c->li_line, newvec, end_of_str+1 ); + sprintf(new_str, "%s=[%s] %s", c->li_line, newvec, end_of_str+1); tfree(newvec); old_str = c->li_line; @@ -3168,12 +3390,14 @@ inp_fix_param_values( struct line *deck ) nwl = NULL; for (;;) { natok = gettok(&vec_str); - if (!natok) break; + if (!natok) + break; buffer = TMALLOC(char, strlen(natok) + 4); - if ( isdigit(*natok) || *natok == '{' || *natok == '.' || - *natok == '"' || ( *natok == '-' && isdigit(*(natok+1)) ) || - ciprefix("true", natok) || ciprefix("false", natok)) { + if (isdigit(*natok) || *natok == '{' || *natok == '.' || + *natok == '"' || (*natok == '-' && isdigit(*(natok+1))) || + ciprefix("true", natok) || ciprefix("false", natok)) + { (void) sprintf(buffer, "%s", natok); } else { (void) sprintf(buffer, "{%s}", natok); @@ -3189,7 +3413,7 @@ inp_fix_param_values( struct line *deck ) /* insert new complex value into actual line */ *equal_ptr = '\0'; new_str = TMALLOC(char, strlen(c->li_line) + strlen(newvec) + strlen(end_of_str + 1) + 5); - sprintf( new_str, "%s=<%s> %s", c->li_line, newvec, end_of_str+1 ); + sprintf(new_str, "%s=<%s> %s", c->li_line, newvec, end_of_str+1); tfree(newvec); old_str = c->li_line; @@ -3200,23 +3424,26 @@ inp_fix_param_values( struct line *deck ) /* put {} around token to be accepted as numparam */ end_of_str = beg_of_str; parens = 0; - while ( *end_of_str != '\0' && (!isspace(*end_of_str) || (parens > 0)) ) { - if ( *end_of_str == '(' ) parens++; - if ( *end_of_str == ')' ) parens--; + while (*end_of_str != '\0' && + (!isspace(*end_of_str) || (parens > 0))) + { + if (*end_of_str == '(') + parens++; + if (*end_of_str == ')') + parens--; end_of_str++; } *equal_ptr = '\0'; - if ( *end_of_str == '\0' ) { + if (*end_of_str == '\0') { new_str = TMALLOC(char, strlen(c->li_line) + strlen(beg_of_str) + 4); - sprintf( new_str, "%s={%s}", c->li_line, beg_of_str ); + sprintf(new_str, "%s={%s}", c->li_line, beg_of_str); } else { *end_of_str = '\0'; - new_str = TMALLOC(char, strlen(c->li_line) + strlen(beg_of_str) + strlen(end_of_str + 1) + 5); - sprintf( new_str, "%s={%s} %s", c->li_line, beg_of_str, end_of_str+1 ); + sprintf(new_str, "%s={%s} %s", c->li_line, beg_of_str, end_of_str+1); } old_str = c->li_line; c->li_line = new_str; @@ -3229,73 +3456,85 @@ inp_fix_param_values( struct line *deck ) } } + static char* -get_param_name( char *line ) +get_param_name(char *line) { char *name = NULL, *equal_ptr, *beg; char keep; - if (( equal_ptr = strstr( line, "=" ) ) != NULL ) { + if ((equal_ptr = strstr(line, "=")) != NULL) { equal_ptr--; - while ( isspace(*equal_ptr) ) equal_ptr--; + while (isspace(*equal_ptr)) + equal_ptr--; equal_ptr++; beg = equal_ptr-1; - while ( !isspace(*beg) && beg != line ) beg--; - if ( beg != line ) beg++; + while (!isspace(*beg) && beg != line) + beg--; + if (beg != line) + beg++; keep = *equal_ptr; *equal_ptr = '\0'; name = strdup(beg); *equal_ptr = keep; } else { - fprintf( stderr, "ERROR: could not find '=' on parameter line '%s'!\n", line ); + fprintf(stderr, "ERROR: could not find '=' on parameter line '%s'!\n", line); controlled_exit(EXIT_FAILURE); } return name; } + static char* -get_param_str( char *line ) +get_param_str(char *line) { char *equal_ptr; - if (( equal_ptr = strstr( line, "=" ) ) != NULL ) { + if ((equal_ptr = strstr(line, "=")) != NULL) { equal_ptr++; - while ( isspace(*equal_ptr) ) equal_ptr++; + while (isspace(*equal_ptr)) + equal_ptr++; return equal_ptr; } return line; } + static int -//inp_get_param_level( int param_num, char *depends_on[12000][100], char *param_names[12000], char *param_strs[12000], int total_params, int *level ) -inp_get_param_level( int param_num, char ***depends_on, char **param_names, char **param_strs, int total_params, int *level ) +//inp_get_param_level(int param_num, char *depends_on[12000][100], char *param_names[12000], char *param_strs[12000], int total_params, int *level) +inp_get_param_level(int param_num, char ***depends_on, char **param_names, char **param_strs, int total_params, int *level) { int index1 = 0, comp_level = 0, temp_level = 0; int index2 = 0; - if ( *(level+param_num) != -1 ) return *(level+param_num); + if (*(level+param_num) != -1) + return *(level+param_num); - while ( depends_on[param_num][index1] != NULL ) { + while (depends_on[param_num][index1] != NULL) { index2 = 0; - while ( index2 <= total_params && param_names[index2] != depends_on[param_num][index1] ) index2++; + while (index2 <= total_params && + param_names[index2] != depends_on[param_num][index1]) + index2++; - if ( index2 > total_params ) { - fprintf( stderr, "ERROR: unable to find dependency parameter for %s!\n", param_names[param_num] ); + if (index2 > total_params) { + fprintf(stderr, "ERROR: unable to find dependency parameter for %s!\n", param_names[param_num]); controlled_exit(EXIT_FAILURE); } - temp_level = inp_get_param_level( index2, depends_on, param_names, param_strs, total_params, level ); + temp_level = inp_get_param_level(index2, depends_on, param_names, param_strs, total_params, level); temp_level++; - if ( temp_level > comp_level ) comp_level = temp_level; + if (temp_level > comp_level) + comp_level = temp_level; index1++; } *(level+param_num) = comp_level; return comp_level; } + static int -get_number_terminals( char *c ) +get_number_terminals(char *c) { int i, j, k; char *name[12]; @@ -3332,11 +3571,12 @@ get_number_terminals( char *c ) case 'm': /* recognition of 4, 5, 6, or 7 nodes for SOI devices needed */ i = 0; /* find the first token with "off" or "=" in the line*/ - while ( (i < 20) && (*c != '\0') ) { + while ((i < 20) && (*c != '\0')) { char *inst = gettok_instance(&c); strncpy(nam_buf, inst, 32); txfree(inst); - if (strstr(nam_buf, "off") || strstr(nam_buf, "=")) break; + if (strstr(nam_buf, "off") || strstr(nam_buf, "=")) + break; i++; } return i-2; @@ -3344,41 +3584,48 @@ get_number_terminals( char *c ) case 'p': /* recognition of up to 100 cpl nodes */ i = j = 0; /* find the last token in the line*/ - while ( (i < 100) && (*c != '\0') ) { + while ((i < 100) && (*c != '\0')) { strncpy(nam_buf, gettok_instance(&c), 32); - if (strstr(nam_buf, "=")) j++; + if (strstr(nam_buf, "=")) + j++; i++; } - if (i == 100) return 0; - return i-j-2; + if (i == 100) + return 0; + return i - j - 2; break; case 'q': /* recognition of 3/4 terminal bjt's needed */ /* QXXXXXXX NC NB NE MNAME */ /* 12 tokens maximum */ i = j = 0; - while ( (i < 12) && (*c != '\0') ) { - char* comma; + while ((i < 12) && (*c != '\0')) { + char *comma; name[i] = gettok_instance(&c); - if (strstr(name[i], "off") || strstr(name[i], "=")) j++; + if (strstr(name[i], "off") || strstr(name[i], "=")) + j++; /* If we have IC=VBE, VCE instead of IC=VBE,VCE we need to inc j */ - if ((comma = strstr(name[i], ",")) != NULL && ( *(++comma) == '\0')) j++; + if ((comma = strstr(name[i], ",")) != NULL && (*(++comma) == '\0')) + j++; /* If we have IC=VBE , VCE ("," is a token) we need to inc j */ - if (eq(name[i], ",")) j++; + if (eq(name[i], ",")) + j++; i++; } i--; area_found = FALSE; for (k = i; k > i-j-1; k--) { bool only_digits = TRUE; - char* nametmp = name[k]; + char *nametmp = name[k]; /* MNAME has to contain at least one alpha character. AREA may be assumed if we have a token with only digits, and where the previous token does not end with a ',' */ while (*nametmp) { - if (isalpha(*nametmp) || (*nametmp == ',')) only_digits = FALSE; + if (isalpha(*nametmp) || (*nametmp == ',')) + only_digits = FALSE; nametmp++; } - if (only_digits && (strstr(name[k-1],",") == NULL)) area_found = TRUE; + if (only_digits && (strstr(name[k-1], ",") == NULL)) + area_found = TRUE; } if (area_found) { return i-j-2; @@ -3392,9 +3639,10 @@ get_number_terminals( char *c ) } } + /* sort parameters based on parameter dependencies */ static void -inp_sort_params( struct line *start_card, struct line *end_card, struct line *card_bf_start, struct line *s_c, struct line *e_c ) +inp_sort_params(struct line *start_card, struct line *end_card, struct line *card_bf_start, struct line *s_c, struct line *e_c) { char *param_name = NULL, *param_str = NULL, *param_ptr = NULL; int i, j, num_params = 0, ind = 0, max_level = 0, num_terminals = 0, ioff = 1; @@ -3418,14 +3666,14 @@ inp_sort_params( struct line *start_card, struct line *end_card, struct line *ca NG_IGNORE(end_card); - if ( start_card == NULL ) return; + if (start_card == NULL) + return; /* determine the number of lines with .param */ ptr = start_card; - while ( ptr != NULL ) { - if ( strstr( ptr->li_line, "=" ) ) { + while (ptr != NULL) { + if (strstr(ptr->li_line, "=")) num_params++; - } ptr = ptr->li_next; } @@ -3442,21 +3690,20 @@ inp_sort_params( struct line *start_card, struct line *end_card, struct line *ca /* rows */ depends_on = TMALLOC(char **, arr_size); /* columns */ - for (i = 0; i < arr_size; i++) { + for (i = 0; i < arr_size; i++) depends_on[i] = TMALLOC(char *, 100); - } ptr_array = TMALLOC(struct line *, arr_size); ptr_array_ordered = TMALLOC(struct line *, arr_size); ptr = start_card; - while ( ptr != NULL ) { + while (ptr != NULL) { // ignore .param lines without '=' - if ( strstr( ptr->li_line, "=" ) ) { + if (strstr(ptr->li_line, "=")) { depends_on[num_params][0] = NULL; level[num_params] = -1; - param_names[num_params] = get_param_name( ptr->li_line ); /* strdup in fcn */ - param_strs[num_params] = strdup( get_param_str( ptr->li_line ) ); + param_names[num_params] = get_param_name(ptr->li_line); /* strdup in fcn */ + param_strs[num_params] = strdup(get_param_str(ptr->li_line)); ptr_array[num_params++] = ptr; } @@ -3464,42 +3711,46 @@ inp_sort_params( struct line *start_card, struct line *end_card, struct line *ca } // look for duplicately defined parameters and mark earlier one to skip // param list is ordered as defined in netlist - for ( i = 0; i < num_params; i++ ) + for (i = 0; i < num_params; i++) param_skip[i] = 0; - for ( i = 0; i < num_params; i++ ) - for ( j = num_params-1; j >= 0; j-- ) { - if ( i != j && i < j && strcmp( param_names[i], param_names[j] ) == 0 ) { + + for (i = 0; i < num_params; i++) + for (j = num_params-1; j >= 0; j--) + if (i != j && i < j && strcmp(param_names[i], param_names[j]) == 0) { // skip earlier one in list param_skip[i] = 1; skipped++; } - } - for ( i = 0; i < num_params; i++ ) { - if ( param_skip[i] == 1 ) continue; + for (i = 0; i < num_params; i++) { + if (param_skip[i] == 1) + continue; param_name = param_names[i]; - for ( j = 0; j < num_params; j++ ) { - if ( j == i ) continue; + for (j = 0; j < num_params; j++) { + if (j == i) + continue; param_str = param_strs[j]; - while ((param_ptr = strstr( param_str, param_name ) ) != NULL ) { + while ((param_ptr = strstr(param_str, param_name)) != NULL) { ioff = (strstr(param_ptr, "}") != NULL ? 1 : 0); /* want prevent wrong memory access below */ /* looking for curly braces or other string limiter */ - if ( ( !isalnum( *(param_ptr-ioff) ) && *(param_ptr-ioff) != '_' && - !isalnum( *(param_ptr+strlen(param_name)) ) && *(param_ptr+strlen(param_name)) != '_' ) - || strcmp( param_ptr, param_name ) == 0) { /* this are cases without curly braces */ + if ((!isalnum(*(param_ptr-ioff)) && *(param_ptr-ioff) != '_' && + !isalnum(*(param_ptr+strlen(param_name))) && + *(param_ptr+strlen(param_name)) != '_') || + strcmp(param_ptr, param_name) == 0) + { /* this are cases without curly braces */ ind = 0; found_in_list = FALSE; - while ( depends_on[j][ind] != NULL ) { - if ( strcmp( param_name, depends_on[j][ind] ) == 0 ) { + while (depends_on[j][ind] != NULL) { + if (strcmp(param_name, depends_on[j][ind]) == 0) { found_in_list = TRUE; break; } ind++; } - if ( !found_in_list ) { + if (!found_in_list) { depends_on[j][ind++] = param_name; depends_on[j][ind] = NULL; } @@ -3510,67 +3761,71 @@ inp_sort_params( struct line *start_card, struct line *end_card, struct line *ca } } - for ( i = 0; i < num_params; i++ ) { - level[i] = inp_get_param_level( i, depends_on, param_names, param_strs, num_params, level ); - if ( level[i] > max_level ) max_level = level[i]; + for (i = 0; i < num_params; i++) { + level[i] = inp_get_param_level(i, depends_on, param_names, param_strs, num_params, level); + if (level[i] > max_level) + max_level = level[i]; } /* look for unquoted parameters and quote them */ ptr = s_c; in_control = FALSE; - while ( ptr != NULL && ptr != e_c ) { + while (ptr != NULL && ptr != e_c) { curr_line = ptr->li_line; - if ( ciprefix( ".control", curr_line ) ) { + if (ciprefix(".control", curr_line)) { in_control = TRUE; ptr = ptr->li_next; continue; } - if ( ciprefix( ".endc", curr_line ) ) { + if (ciprefix(".endc", curr_line)) { in_control = FALSE; ptr = ptr->li_next; continue; } - if ( in_control || curr_line[0] == '.' || curr_line[0] == '*' ) { + if (in_control || curr_line[0] == '.' || curr_line[0] == '*') { ptr = ptr->li_next; continue; } - num_terminals = get_number_terminals( curr_line ); + num_terminals = get_number_terminals(curr_line); - if ( num_terminals <= 0 ) { + if (num_terminals <= 0) { ptr = ptr->li_next; continue; } - for ( i = 0; i < num_params; i++ ) { + for (i = 0; i < num_params; i++) { str_ptr = curr_line; - for ( j = 0; j < num_terminals+1; j++ ) { - while ( !isspace(*str_ptr) && *str_ptr != '\0' ) str_ptr++; - while ( isspace(*str_ptr) && *str_ptr != '\0' ) str_ptr++; + for (j = 0; j < num_terminals+1; j++) { + while (!isspace(*str_ptr) && *str_ptr != '\0') + str_ptr++; + while (isspace(*str_ptr) && *str_ptr != '\0') + str_ptr++; } - while ((str_ptr = strstr( str_ptr, param_names[i] ) ) != NULL ) { + while ((str_ptr = strstr(str_ptr, param_names[i])) != NULL) { /* make sure actually have the parameter name */ char before = *(str_ptr-1); char after = *(str_ptr+strlen(param_names[i])); - if ( !( is_arith_char(before) || isspace(before) || (str_ptr-1) < curr_line ) || - !( is_arith_char(after) || isspace(after) || after == '\0' ) ) { + if (!(is_arith_char(before) || isspace(before) || (str_ptr-1) < curr_line) || + !(is_arith_char(after) || isspace(after) || after == '\0')) { str_ptr = str_ptr + 1; continue; } beg = str_ptr - 1; end = str_ptr + strlen(param_names[i]); - if ( ( isspace(*beg) || *beg == '=' ) && - ( isspace(*end) || *end == '\0' || *end == ')') ) { /* ')' added, any risks? h_vogt */ + if ((isspace(*beg) || *beg == '=') && + (isspace(*end) || *end == '\0' || *end == ')')) + { /* ')' added, any risks? h_vogt */ *str_ptr = '\0'; - if ( *end != '\0' ) { + if (*end != '\0') { new_str = TMALLOC(char, strlen(curr_line) + strlen(param_names[i]) + strlen(end) + 3); - sprintf( new_str, "%s{%s}%s", curr_line, param_names[i], end ); + sprintf(new_str, "%s{%s}%s", curr_line, param_names[i], end); } else { new_str = TMALLOC(char, strlen(curr_line) + strlen(param_names[i]) + 3); - sprintf( new_str, "%s{%s}", curr_line, param_names[i] ); + sprintf(new_str, "%s{%s}", curr_line, param_names[i]); } str_ptr = new_str + strlen(curr_line) + strlen(param_names[i]); @@ -3584,18 +3839,15 @@ inp_sort_params( struct line *start_card, struct line *end_card, struct line *ca } ind = 0; - for ( i = 0; i <= max_level; i++ ) - for ( j = num_params-1; j >= 0; j-- ) { - if ( level[j] == i ) { - if ( param_skip[j] == 0 ) { + for (i = 0; i <= max_level; i++) + for (j = num_params-1; j >= 0; j--) + if (level[j] == i) + if (param_skip[j] == 0) ptr_array_ordered[ind++] = ptr_array[j]; - } - } - } num_params -= skipped; - if ( ind != num_params ) { - fprintf( stderr, "ERROR: found wrong number of parameters during levelization ( %d instead of %d parameter s)!\n", ind, num_params ); + if (ind != num_params) { + fprintf(stderr, "ERROR: found wrong number of parameters during levelization ( %d instead of %d parameter s)!\n", ind, num_params); controlled_exit(EXIT_FAILURE); } @@ -3603,13 +3855,13 @@ inp_sort_params( struct line *start_card, struct line *end_card, struct line *ca ptr = card_bf_start->li_next; card_bf_start->li_next = ptr_array_ordered[0]; ptr_array_ordered[num_params-1]->li_next = ptr; - for ( i = 0; i < num_params-1; i++ ) + for (i = 0; i < num_params-1; i++) ptr_array_ordered[i]->li_next = ptr_array_ordered[i+1]; // clean up memory - for ( i = 0; i < num_params; i++ ) { - tfree( param_names[i] ); - tfree( param_strs[i] ); + for (i = 0; i < num_params; i++) { + tfree(param_names[i]); + tfree(param_strs[i]); } tfree(level); @@ -3626,8 +3878,9 @@ inp_sort_params( struct line *start_card, struct line *end_card, struct line *ca } + static void -inp_add_params_to_subckt( struct line *subckt_card ) +inp_add_params_to_subckt(struct line *subckt_card) { struct line *card = subckt_card->li_next; char *curr_line = card->li_line; @@ -3635,29 +3888,33 @@ inp_add_params_to_subckt( struct line *subckt_card ) char *new_line, *param_ptr, *subckt_name, *end_ptr; char keep; - while ( card != NULL && ciprefix( ".param", curr_line ) ) { - param_ptr = strstr( curr_line, " " ); - while ( isspace(*param_ptr) ) param_ptr++; + while (card != NULL && ciprefix(".param", curr_line)) { + param_ptr = strstr(curr_line, " "); + while (isspace(*param_ptr)) + param_ptr++; - if ( !strstr( subckt_line, "params:" ) ) { + if (!strstr(subckt_line, "params:")) { new_line = TMALLOC(char, strlen(subckt_line) + strlen("params: ") + strlen(param_ptr) + 2); - sprintf( new_line, "%s params: %s", subckt_line, param_ptr ); + sprintf(new_line, "%s params: %s", subckt_line, param_ptr); subckt_name = subckt_card->li_line; - while ( !isspace(*subckt_name) ) subckt_name++; - while ( isspace(*subckt_name) ) subckt_name++; + while (!isspace(*subckt_name)) + subckt_name++; + while (isspace(*subckt_name)) + subckt_name++; end_ptr = subckt_name; - while ( !isspace(*end_ptr) ) end_ptr++; + while (!isspace(*end_ptr)) + end_ptr++; keep = *end_ptr; *end_ptr = '\0'; subckt_w_params[num_subckt_w_params++] = strdup(subckt_name); *end_ptr = keep; } else { new_line = TMALLOC(char, strlen(subckt_line) + strlen(param_ptr) + 2); - sprintf( new_line, "%s %s", subckt_line, param_ptr ); + sprintf(new_line, "%s %s", subckt_line, param_ptr); } - tfree( subckt_line ); + tfree(subckt_line); subckt_card->li_line = subckt_line = new_line; *curr_line = '*'; @@ -3667,6 +3924,7 @@ inp_add_params_to_subckt( struct line *subckt_card ) } } + /* * process a sequence of decks * starting from a `.suckt' deck @@ -3692,31 +3950,31 @@ inp_reorder_params_subckt(struct line *subckt_card) struct line *c = subckt_card->li_next; /* move .param lines to beginning of deck */ - while ( c != NULL ) { + while (c != NULL) { char *curr_line = c->li_line; - if ( *curr_line == '*' ) { + if (*curr_line == '*') { c = c->li_next; continue; } - if ( ciprefix( ".subckt", curr_line ) ) { + if (ciprefix(".subckt", curr_line)) { prev_card = inp_reorder_params_subckt(c); c = prev_card->li_next; continue; } - if ( ciprefix( ".ends", curr_line ) ) { - if ( first_param_card ) { - inp_sort_params( first_param_card, last_param_card, subckt_card, subckt_card, c ); - inp_add_params_to_subckt( subckt_card ); + if (ciprefix(".ends", curr_line)) { + if (first_param_card) { + inp_sort_params(first_param_card, last_param_card, subckt_card, subckt_card, c); + inp_add_params_to_subckt(subckt_card); } return c; } - if ( ciprefix( ".param", curr_line ) ) { - if ( first_param_card ) + if (ciprefix(".param", curr_line)) { + if (first_param_card) last_param_card->li_next = c; else first_param_card = c; @@ -3738,8 +3996,9 @@ inp_reorder_params_subckt(struct line *subckt_card) return NULL; } + static void -inp_reorder_params( struct line *deck, struct line *list_head, struct line *end ) +inp_reorder_params(struct line *deck, struct line *list_head, struct line *end) { struct line *first_param_card = NULL; struct line *last_param_card = NULL; @@ -3748,29 +4007,29 @@ inp_reorder_params( struct line *deck, struct line *list_head, struct line *end struct line *c = deck; /* move .param lines to beginning of deck */ - while ( c != NULL ) { + while (c != NULL) { char *curr_line = c->li_line; - if ( *curr_line == '*' ) { + if (*curr_line == '*') { c = c->li_next; continue; } - if ( ciprefix( ".subckt", curr_line ) ) { + if (ciprefix(".subckt", curr_line)) { prev_card = inp_reorder_params_subckt(c); c = prev_card->li_next; continue; } /* check for an unexpected extra `.ends' deck */ - if ( ciprefix( ".ends", curr_line ) ) { - fprintf(stderr, "Error: Unexpected extra .ends in line:\n %s.\n", curr_line); + if (ciprefix(".ends", curr_line)) { + fprintf(stderr, "Error: Unexpected extra .ends in line:\n %s.\n", curr_line); controlled_exit(EXIT_FAILURE); } - if ( ciprefix( ".param", curr_line ) ) { - if ( first_param_card ) + if (ciprefix(".param", curr_line)) { + if (first_param_card) last_param_card->li_next = c; else first_param_card = c; @@ -3784,18 +4043,19 @@ inp_reorder_params( struct line *deck, struct line *list_head, struct line *end } prev_card = c; - c = c->li_next; + c = c->li_next; } - inp_sort_params( first_param_card, last_param_card, list_head, deck, end ); + inp_sort_params(first_param_card, last_param_card, list_head, deck, end); } + // iterate through deck and find lines with multiply defined parameters // // split line up into multiple lines and place those new lines immediately // afetr the current multi-param line in the deck static int -inp_split_multi_param_lines( struct line *deck, int line_num ) +inp_split_multi_param_lines(struct line *deck, int line_num) { struct line *card = deck, *param_end = NULL, *param_beg = NULL, *prev = NULL, *tmp_ptr; char *curr_line, *equal_ptr, *beg_param, *end_param, *new_line; @@ -3804,31 +4064,31 @@ inp_split_multi_param_lines( struct line *deck, int line_num ) bool get_expression = FALSE, get_paren_expression = FALSE; char keep; - while ( card != NULL ) { + while (card != NULL) { curr_line = card->li_line; - if ( *curr_line == '*' ) { + if (*curr_line == '*') { card = card->li_next; continue; } - if ( ciprefix( ".param", curr_line ) ) { + if (ciprefix(".param", curr_line)) { counter = 0; - while (( equal_ptr = strstr( curr_line, "=" ) ) != NULL ) { + while ((equal_ptr = strstr(curr_line, "=")) != NULL) { // check for equality '==' - if ( *(equal_ptr+1) == '=' ) { + if (*(equal_ptr+1) == '=') { curr_line = equal_ptr+2; continue; } // check for '!=', '<=', '>=' - if ( *(equal_ptr-1) == '!' || *(equal_ptr-1) == '<' || *(equal_ptr-1) == '>' ) { + if (*(equal_ptr-1) == '!' || *(equal_ptr-1) == '<' || *(equal_ptr-1) == '>') { curr_line = equal_ptr+1; continue; } counter++; curr_line = equal_ptr + 1; } - if ( counter <= 1 ) { + if (counter <= 1) { card = card->li_next; continue; } @@ -3836,42 +4096,49 @@ inp_split_multi_param_lines( struct line *deck, int line_num ) // need to split multi param line curr_line = card->li_line; counter = 0; - while ( curr_line < card->li_line+strlen(card->li_line) && ( equal_ptr = strstr( curr_line, "=" ) ) != NULL ) { + while (curr_line < card->li_line+strlen(card->li_line) && (equal_ptr = strstr(curr_line, "=")) != NULL) { // check for equality '==' - if ( *(equal_ptr+1) == '=' ) { + if (*(equal_ptr+1) == '=') { curr_line = equal_ptr+2; continue; } // check for '!=', '<=', '>=' - if ( *(equal_ptr-1) == '!' || *(equal_ptr-1) == '<' || *(equal_ptr-1) == '>' ) { + if (*(equal_ptr-1) == '!' || *(equal_ptr-1) == '<' || *(equal_ptr-1) == '>') { curr_line = equal_ptr+1; continue; } beg_param = equal_ptr - 1; end_param = equal_ptr + 1; - while ( isspace(*beg_param) ) beg_param--; - while ( !isspace(*beg_param) ) beg_param--; - while ( isspace(*end_param) ) end_param++; - while ( *end_param != '\0' && (!isspace(*end_param) || get_expression || get_paren_expression) ) { - if ( *end_param == '{' ) get_expression = TRUE; - if ( *end_param == '(' ) get_paren_expression = TRUE; - if ( *end_param == '}' ) get_expression = FALSE; - if ( *end_param == ')' ) get_paren_expression = FALSE; + while (isspace(*beg_param)) + beg_param--; + while (!isspace(*beg_param)) + beg_param--; + while (isspace(*end_param)) + end_param++; + while (*end_param != '\0' && (!isspace(*end_param) || get_expression || get_paren_expression)) { + if (*end_param == '{') + get_expression = TRUE; + if (*end_param == '(') + get_paren_expression = TRUE; + if (*end_param == '}') + get_expression = FALSE; + if (*end_param == ')') + get_paren_expression = FALSE; end_param++; } beg_param++; keep = *end_param; *end_param = '\0'; new_line = TMALLOC(char, strlen(".param ") + strlen(beg_param) + 1); - sprintf( new_line, ".param %s", beg_param ); + sprintf(new_line, ".param %s", beg_param); array[counter++] = new_line; *end_param = keep; curr_line = end_param; } tmp_ptr = card->li_next; - for ( i = 0; i < counter; i++ ) { - if ( param_end ) { + for (i = 0; i < counter; i++) { + if (param_end) { param_end->li_next = alloc(struct line); param_end = param_end->li_next; } else { @@ -3893,17 +4160,18 @@ inp_split_multi_param_lines( struct line *deck, int line_num ) card = param_end; param_beg = param_end = NULL; - } // if ( ciprefix( ".param", curr_line ) ) + } // if (ciprefix(".param", curr_line)) prev = card; card = card->li_next; - } // while ( card != NULL ) - if ( param_end ) { + } // while (card != NULL) + if (param_end) { prev->li_next = param_beg; prev = param_end; } return line_num; } + /* ps compatibility: ECOMP 3 0 TABLE {V(1,2)} = (-1 0V) (1, 10V) --> @@ -3913,7 +4181,7 @@ inp_split_multi_param_lines( struct line *deck, int line_num ) GD16 16 1 TABLE {V(16,1)} ((-100V,-1pV)(0,0)(1m,1u)(2m,1m)) --> GD16 16 1 int_16 int_1 1 - BGD16 int_16 int_1 V = pwl (v(16,1) , -100V , -1pV , 0 , 0 , 1m , 1u , 2m , 1m ) + BGD16 int_16 int_1 V = pwl (v(16,1) , -100V , -1pV , 0 , 0 , 1m , 1u , 2m , 1m) */ /* hs compatibility: @@ -3957,12 +4225,13 @@ inp_split_multi_param_lines( struct line *deck, int line_num ) Bxxx n1 n2 V = v(n-aux) * 1e-16 */ -static void inp_compat(struct line *deck) +static void +inp_compat(struct line *deck) { char *str_ptr, *cut_line, *title_tok, *node1, *node2; char *out_ptr, *exp_ptr, *beg_ptr, *end_ptr, *copy_ptr, *del_ptr; char *xline; - size_t xlen, i, pai=0, paui=0, ii; + size_t xlen, i, pai = 0, paui = 0, ii; char *ckt_array[100]; struct line *new_line, *tmp_ptr; @@ -3970,31 +4239,31 @@ static void inp_compat(struct line *deck) struct line *card; int skip_control = 0; - char *equation, *tc1_ptr=NULL, *tc2_ptr=NULL; - double tc1=0.0, tc2=0.0; + char *equation, *tc1_ptr = NULL, *tc2_ptr = NULL; + double tc1 = 0.0, tc2 = 0.0; for (card = deck; card; card = card->li_next) { char *curr_line = card->li_line; /* exclude any command inside .control ... .endc */ - if ( ciprefix(".control", curr_line) ) { + if (ciprefix(".control", curr_line)) { skip_control ++; continue; - } else if( ciprefix(".endc", curr_line) ) { + } else if (ciprefix(".endc", curr_line)) { skip_control --; continue; - } else if(skip_control > 0) { + } else if (skip_control > 0) { continue; } - if ( *curr_line == '*' ) + if (*curr_line == '*') continue; - if ( *curr_line == 'e' ) { + if (*curr_line == 'e') { /* Exxx n1 n2 VCVS n3 n4 gain --> Exxx n1 n2 n3 n4 gain remove vcvs */ - if ((str_ptr = strstr( curr_line, "vcvs" )) != NULL) { + if ((str_ptr = strstr(curr_line, "vcvs")) != NULL) { *str_ptr = ' '; *(str_ptr + 1) = ' '; *(str_ptr + 2) = ' '; @@ -4004,7 +4273,7 @@ static void inp_compat(struct line *deck) /* Exxx n1 n2 value={equation} --> Exxx n1 n2 vol={equation} */ - if ((str_ptr = strstr( curr_line, "value=" )) != NULL) { + if ((str_ptr = strstr(curr_line, "value=")) != NULL) { *str_ptr = ' '; *(str_ptr + 1) = ' '; *(str_ptr + 2) = 'v'; @@ -4016,7 +4285,7 @@ static void inp_compat(struct line *deck) Exxx n1 n2 int1 0 1 BExxx int1 0 V = pwl (expression, x0-(x2-x0)/2, y0, x0, y0, x1, y1, x2, y2, x2+(x2-x0)/2, y2) */ - if ((str_ptr = strstr( curr_line, "table" )) != NULL) { + if ((str_ptr = strstr(curr_line, "table")) != NULL) { char *expression, *firstno, *ffirstno, *secondno, *midline, *lastno, *lastlastno; double fnumber, lnumber, delta; int nerror; @@ -4033,9 +4302,9 @@ static void inp_compat(struct line *deck) title_tok, node1, node2, title_tok); // get the expression str_ptr = gettok(&cut_line); /* ignore 'table' */ - if (cieq(str_ptr, "table")) + if (cieq(str_ptr, "table")) { tfree(str_ptr); - else { + } else { fprintf(stderr, "Error: bad sytax in line %d\n %s\n", card->li_linenum_orig, card->li_line); controlled_exit(EXIT_BAD); @@ -4050,17 +4319,17 @@ static void inp_compat(struct line *deck) else tfree(str_ptr); /* remove '{' and '}' from expression */ - if ((str_ptr = strstr( expression, "{" )) != NULL) + if ((str_ptr = strstr(expression, "{")) != NULL) *str_ptr = ' '; - if ((str_ptr = strstr( expression, "}" )) != NULL) + if ((str_ptr = strstr(expression, "}")) != NULL) *str_ptr = ' '; /* cut_line may now have a '=', if yes, it will have '{' and '}' (braces around token after '=') */ - if ((str_ptr = strstr( cut_line, "=" )) != NULL) + if ((str_ptr = strstr(cut_line, "=")) != NULL) *str_ptr = ' '; - if ((str_ptr = strstr( cut_line, "{" )) != NULL) + if ((str_ptr = strstr(cut_line, "{")) != NULL) *str_ptr = ' '; - if ((str_ptr = strstr( cut_line, "}" )) != NULL) + if ((str_ptr = strstr(cut_line, "}")) != NULL) *str_ptr = ' '; /* get first two numbers to establish extrapolation */ str_ptr = cut_line; @@ -4076,14 +4345,14 @@ static void inp_compat(struct line *deck) midline = cut_line; cut_line = strrchr(str_ptr, '('); /* replace '(' with ',' and ')' with ' ' */ - for ( ; *str_ptr; str_ptr++) + for (; *str_ptr; str_ptr++) if (*str_ptr == '(') *str_ptr = ','; else if (*str_ptr == ')') *str_ptr = ' '; /* scan for last two numbers */ lastno = gettok_node(&cut_line); - lnumber = INPevaluate(&lastno, &nerror, FALSE); + lnumber = INPevaluate(&lastno, &nerror, FALSE); /* check for max-min and take half the difference for delta */ delta = (lnumber-fnumber)/2.; lastlastno = gettok_node(&cut_line); @@ -4097,13 +4366,13 @@ static void inp_compat(struct line *deck) strlen(lastlastno) + 50; ckt_array[1] = TMALLOC(char, xlen); sprintf(ckt_array[1], "b%s %s_int1 0 v = pwl(%s, %e, %s, %s, %s, %s, %e, %s)", - title_tok, title_tok, expression, fnumber-delta, secondno, firstno, secondno, + title_tok, title_tok, expression, fnumber-delta, secondno, firstno, secondno, midline, lnumber + delta, lastlastno); // insert new B source line immediately after current line tmp_ptr = card->li_next; - for ( i = 0; i < 2; i++ ) { - if ( param_end ) { + for (i = 0; i < 2; i++) { + if (param_end) { param_end->li_next = alloc(struct line); param_end = param_end->li_next; } else { @@ -4136,7 +4405,7 @@ static void inp_compat(struct line *deck) Exxx n1 n2 int1 0 1 BExxx int1 0 V = {equation} */ - if ((str_ptr = strstr( curr_line, "vol" )) != NULL) { + if ((str_ptr = strstr(curr_line, "vol")) != NULL) { cut_line = curr_line; /* title and nodes */ title_tok = gettok(&cut_line); @@ -4145,7 +4414,7 @@ static void inp_compat(struct line *deck) /* Find equation, starts with '{', till end of line */ str_ptr = strstr(cut_line, "{"); if (str_ptr == NULL) { - fprintf(stderr,"ERROR: mal formed E line: %s\n",curr_line); + fprintf(stderr, "ERROR: mal formed E line: %s\n", curr_line); controlled_exit(EXIT_FAILURE); } @@ -4164,8 +4433,8 @@ static void inp_compat(struct line *deck) // insert new B source line immediately after current line tmp_ptr = card->li_next; - for ( i = 0; i < 2; i++ ) { - if ( param_end ) { + for (i = 0; i < 2; i++) { + if (param_end) { param_end->li_next = alloc(struct line); param_end = param_end->li_next; } else { @@ -4188,10 +4457,10 @@ static void inp_compat(struct line *deck) param_beg = param_end = NULL; } - } else if ( *curr_line == 'g' ) { + } else if (*curr_line == 'g') { /* Gxxx n1 n2 VCCS n3 n4 tr --> Gxxx n1 n2 n3 n4 tr remove vccs */ - if ((str_ptr = strstr( curr_line, "vccs" )) != NULL) { + if ((str_ptr = strstr(curr_line, "vccs")) != NULL) { *str_ptr = ' '; *(str_ptr + 1) = ' '; *(str_ptr + 2) = ' '; @@ -4201,7 +4470,7 @@ static void inp_compat(struct line *deck) /* Gxxx n1 n2 value={equation} --> Gxxx n1 n2 cur={equation} */ - if ((str_ptr = strstr( curr_line, "value=" )) != NULL) { + if ((str_ptr = strstr(curr_line, "value=")) != NULL) { *str_ptr = ' '; *(str_ptr + 1) = ' '; *(str_ptr + 2) = 'c'; @@ -4212,9 +4481,9 @@ static void inp_compat(struct line *deck) /* Gxxx n1 n2 TABLE {expression} = (x0, y0) (x1, y1) (x2, y2) --> Gxxx n1 n2 int1 0 1 - BGxxx int1 0 V = pwl (expression, x0-(x2-x0)/2, y0, x0, y0, x1, y1, x2, y2, x2+(x2-x0)/2, y2) + BGxxx int1 0 V = pwl (expression, x0-(x2-x0)/2, y0, x0, y0, x1, y1, x2, y2, x2+(x2-x0)/2, y2) */ - if ((str_ptr = strstr( curr_line, "table" )) != NULL) { + if ((str_ptr = strstr(curr_line, "table")) != NULL) { char *expression, *firstno, *ffirstno, *secondno, *midline, *lastno, *lastlastno; double fnumber, lnumber, delta; int nerror; @@ -4231,9 +4500,9 @@ static void inp_compat(struct line *deck) title_tok, node1, node2, title_tok); // get the expression str_ptr = gettok(&cut_line); /* ignore 'table' */ - if (cieq(str_ptr, "table")) + if (cieq(str_ptr, "table")) { tfree(str_ptr); - else { + } else { fprintf(stderr, "Error: bad sytax in line %d\n %s\n", card->li_linenum_orig, card->li_line); controlled_exit(EXIT_BAD); @@ -4248,17 +4517,17 @@ static void inp_compat(struct line *deck) else tfree(str_ptr); /* remove '{' and '}' from expression */ - if ((str_ptr = strstr( expression, "{" )) != NULL) + if ((str_ptr = strstr(expression, "{")) != NULL) *str_ptr = ' '; - if ((str_ptr = strstr( expression, "}" )) != NULL) + if ((str_ptr = strstr(expression, "}")) != NULL) *str_ptr = ' '; /* cut_line may now have a '=', if yes, it will have '{' and '}' (braces around token after '=') */ - if ((str_ptr = strstr( cut_line, "=" )) != NULL) + if ((str_ptr = strstr(cut_line, "=")) != NULL) *str_ptr = ' '; - if ((str_ptr = strstr( cut_line, "{" )) != NULL) + if ((str_ptr = strstr(cut_line, "{")) != NULL) *str_ptr = ' '; - if ((str_ptr = strstr( cut_line, "}" )) != NULL) + if ((str_ptr = strstr(cut_line, "}")) != NULL) *str_ptr = ' '; /* get first two numbers to establish extrapolation */ str_ptr = cut_line; @@ -4274,14 +4543,14 @@ static void inp_compat(struct line *deck) midline = cut_line; cut_line = strrchr(str_ptr, '('); /* replace '(' with ',' and ')' with ' ' */ - for ( ; *str_ptr; str_ptr++) + for (; *str_ptr; str_ptr++) if (*str_ptr == '(') *str_ptr = ','; else if (*str_ptr == ')') *str_ptr = ' '; /* scan for last two numbers */ lastno = gettok_node(&cut_line); - lnumber = INPevaluate(&lastno, &nerror, FALSE); + lnumber = INPevaluate(&lastno, &nerror, FALSE); /* check for max-min and take half the difference for delta */ delta = (lnumber-fnumber)/2.; lastlastno = gettok_node(&cut_line); @@ -4296,13 +4565,13 @@ static void inp_compat(struct line *deck) strlen(lastlastno) + 50; ckt_array[1] = TMALLOC(char, xlen); sprintf(ckt_array[1], "b%s %s_int1 0 v = pwl(%s, %e, %s, %s, %s, %s, %e, %s)", - title_tok, title_tok, expression, fnumber-delta, secondno, firstno, secondno, + title_tok, title_tok, expression, fnumber-delta, secondno, firstno, secondno, midline, lnumber + delta, lastlastno); // insert new B source line immediately after current line tmp_ptr = card->li_next; - for ( i = 0; i < 2; i++ ) { - if ( param_end ) { + for (i = 0; i < 2; i++) { + if (param_end) { param_end->li_next = alloc(struct line); param_end = param_end->li_next; } else { @@ -4336,7 +4605,7 @@ static void inp_compat(struct line *deck) Gxxx n1 n2 int1 0 1 BGxxx int1 0 V = {equation} */ - if ((str_ptr = strstr( curr_line, "cur" )) != NULL) { + if ((str_ptr = strstr(curr_line, "cur")) != NULL) { cut_line = curr_line; /* title and nodes */ title_tok = gettok(&cut_line); @@ -4345,7 +4614,7 @@ static void inp_compat(struct line *deck) /* Find equation, starts with '{', till end of line */ str_ptr = strstr(cut_line, "{"); if (str_ptr == NULL) { - fprintf(stderr,"ERROR: mal formed G line: %s\n",curr_line); + fprintf(stderr, "ERROR: mal formed G line: %s\n", curr_line); controlled_exit(EXIT_FAILURE); } // Gxxx n1 n2 int1 0 1 @@ -4363,8 +4632,8 @@ static void inp_compat(struct line *deck) // insert new B source line immediately after current line tmp_ptr = card->li_next; - for ( i = 0; i < 2; i++ ) { - if ( param_end ) { + for (i = 0; i < 2; i++) { + if (param_end) { param_end->li_next = alloc(struct line); param_end = param_end->li_next; } else { @@ -4395,20 +4664,20 @@ static void inp_compat(struct line *deck) --> BRxxx pos neg I = V(pos, neg)/{equation} */ - else if ( *curr_line == 'r' ) { + else if (*curr_line == 'r') { cut_line = curr_line; /* make BRxxx pos neg I = V(pos, neg)/{equation}*/ title_tok = gettok(&cut_line); node1 = gettok(&cut_line); node2 = gettok(&cut_line); /* check only after skipping Rname and nodes, either may contain time (e.g. Rtime)*/ - if ((!strstr(cut_line, "v(")) && (!strstr(cut_line, "i(")) - && (!strstr(cut_line, "temper")) && (!strstr(cut_line, "hertz")) - && (!strstr(cut_line, "time"))) { + if ((!strstr(cut_line, "v(")) && (!strstr(cut_line, "i(")) && + (!strstr(cut_line, "temper")) && (!strstr(cut_line, "hertz")) && + (!strstr(cut_line, "time"))) { /* no handling in B-Source, so we have to prepare ternary fcn for numparam */ - if ( strstr( curr_line, "?" ) && strstr( curr_line, ":" ) ) - card->li_line = inp_fix_ternary_operator_str( curr_line, TRUE ); + if (strstr(curr_line, "?") && strstr(curr_line, ":")) + card->li_line = inp_fix_ternary_operator_str(curr_line, TRUE); tfree(title_tok); tfree(node1); tfree(node2); @@ -4418,7 +4687,7 @@ static void inp_compat(struct line *deck) /* Find equation, starts with '{', till end of line */ str_ptr = strstr(cut_line, "{"); if (str_ptr == NULL) { - fprintf(stderr,"ERROR: mal formed R line: %s\n", curr_line); + fprintf(stderr, "ERROR: mal formed R line: %s\n", curr_line); controlled_exit(EXIT_FAILURE); } equation = gettok_char(&str_ptr, '}', TRUE, TRUE); @@ -4488,19 +4757,20 @@ static void inp_compat(struct line *deck) Cxxx n-aux 0 1 Bxxx n2 n1 I = i(Exxx) * equation */ - else if ( *curr_line == 'c' ) { + else if (*curr_line == 'c') { cut_line = curr_line; title_tok = gettok(&cut_line); node1 = gettok(&cut_line); node2 = gettok(&cut_line); /* check only after skipping Cname and nodes, either may contain time (e.g. Ctime)*/ - if ((!strstr(cut_line, "v(")) && (!strstr(cut_line, "i(")) - && (!strstr(cut_line, "temper")) && (!strstr(cut_line, "hertz")) - && (!strstr(cut_line, "time"))) { + if ((!strstr(cut_line, "v(")) && (!strstr(cut_line, "i(")) && + (!strstr(cut_line, "temper")) && (!strstr(cut_line, "hertz")) && + (!strstr(cut_line, "time"))) + { /* no handling in B-Source, so we have to prepare ternary fcn for numparam */ - if ( strstr( curr_line, "?" ) && strstr( curr_line, ":" ) ) - card->li_line = inp_fix_ternary_operator_str( curr_line, TRUE ); + if (strstr(curr_line, "?") && strstr(curr_line, ":")) + card->li_line = inp_fix_ternary_operator_str(curr_line, TRUE); tfree(title_tok); tfree(node1); tfree(node2); @@ -4510,7 +4780,7 @@ static void inp_compat(struct line *deck) /* Find equation, starts with '{', till end of line */ str_ptr = strstr(cut_line, "{"); if (str_ptr == NULL) { - fprintf(stderr,"ERROR: mal formed C line: %s\n",curr_line); + fprintf(stderr, "ERROR: mal formed C line: %s\n", curr_line); controlled_exit(EXIT_FAILURE); } equation = gettok_char(&str_ptr, '}', TRUE, TRUE); @@ -4567,8 +4837,8 @@ static void inp_compat(struct line *deck) tc2_ptr = NULL; // insert new B source line immediately after current line tmp_ptr = card->li_next; - for ( i = 0; i < 3; i++ ) { - if ( param_end ) { + for (i = 0; i < 3; i++) { + if (param_end) { param_end->li_next = alloc(struct line); param_end = param_end->li_next; } else { @@ -4601,19 +4871,20 @@ static void inp_compat(struct line *deck) Lxxx n-aux 0 1 Bxxx n1 n2 V = v(n-aux) * equation */ - else if ( *curr_line == 'l' ) { + else if (*curr_line == 'l') { cut_line = curr_line; /* title and nodes */ title_tok = gettok(&cut_line); node1 = gettok(&cut_line); node2 = gettok(&cut_line); - if ((!strstr(cut_line, "v(")) && (!strstr(cut_line, "i(")) - && (!strstr(cut_line, "temper")) && (!strstr(cut_line, "hertz")) - && (!strstr(cut_line, "time"))) { + if ((!strstr(cut_line, "v(")) && (!strstr(cut_line, "i(")) && + (!strstr(cut_line, "temper")) && (!strstr(cut_line, "hertz")) && + (!strstr(cut_line, "time"))) + { /* no handling in B-Source, so we have to prepare ternary fcn for numparam */ - if ( strstr( curr_line, "?" ) && strstr( curr_line, ":" ) ) - card->li_line = inp_fix_ternary_operator_str( curr_line, TRUE ); + if (strstr(curr_line, "?") && strstr(curr_line, ":")) + card->li_line = inp_fix_ternary_operator_str(curr_line, TRUE); tfree(title_tok); tfree(node1); tfree(node2); @@ -4623,7 +4894,7 @@ static void inp_compat(struct line *deck) /* Find equation, starts with '{', till end of line */ str_ptr = strstr(cut_line, "{"); if (str_ptr == NULL) { - fprintf(stderr,"ERROR: mal formed L line: %s\n", curr_line); + fprintf(stderr, "ERROR: mal formed L line: %s\n", curr_line); controlled_exit(EXIT_FAILURE); } equation = gettok_char(&str_ptr, '}', TRUE, TRUE); @@ -4680,8 +4951,8 @@ static void inp_compat(struct line *deck) tc2_ptr = NULL; // insert new B source line immediately after current line tmp_ptr = card->li_next; - for ( i = 0; i < 3; i++ ) { - if ( param_end ) { + for (i = 0; i < 3; i++) { + if (param_end) { param_end->li_next = alloc(struct line); param_end = param_end->li_next; } else { @@ -4715,9 +4986,9 @@ static void inp_compat(struct line *deck) A vector out_variable may be replaced by par('expression') */ - else if ( *curr_line == '.' ) { + else if (*curr_line == '.') { // replace .probe by .save - if((str_ptr = strstr(curr_line, ".probe")) != NULL) + if ((str_ptr = strstr(curr_line, ".probe")) != NULL) memcpy(str_ptr, ".save ", 6); /* Various formats for measure statement: @@ -4760,18 +5031,19 @@ static void inp_compat(struct line *deck) We have to replace this by v(pa_xx) and generate a B source line. * ----------------------------------------------------------------- */ - if ( ciprefix(".meas", curr_line) ) { - if (strstr(curr_line, "par") == NULL) continue; + if (ciprefix(".meas", curr_line)) { + if (strstr(curr_line, "par") == NULL) + continue; cut_line = curr_line; // search for 'par' - while((str_ptr = strstr(cut_line, "par")) != NULL) { + while ((str_ptr = strstr(cut_line, "par")) != NULL) { if (pai > 99) { fprintf(stderr, "ERROR: No more than 99 'par' per input file\n"); controlled_exit(EXIT_FAILURE); } // we have ' par({ ... })', the right delimeter is a ' ' or '=' - if ( ciprefix(" par({", (str_ptr-1)) ) { + if (ciprefix(" par({", (str_ptr-1))) { // find expression beg_ptr = end_ptr = str_ptr + 5; while ((*end_ptr != ' ') && (*end_ptr != '=') && (*end_ptr != '\0')) @@ -4782,7 +5054,7 @@ static void inp_compat(struct line *deck) out_ptr = TMALLOC(char, 6); sprintf(out_ptr, "pa_%02d", (int)pai); // Bout_ptr out_ptr 0 V = v(expr_ptr) - xlen = 2*strlen(out_ptr) + strlen(exp_ptr )+ 15 - 2*3 + 1; + xlen = 2*strlen(out_ptr) + strlen(exp_ptr)+ 15 - 2*3 + 1; ckt_array[pai] = TMALLOC(char, xlen); sprintf(ckt_array[pai], "b%s %s 0 v = %s", out_ptr, out_ptr, exp_ptr); @@ -4805,7 +5077,7 @@ static void inp_compat(struct line *deck) tfree(out_ptr); } // or we have '={par({ ... })}', the right delimeter is a ' ' - else if ( ciprefix("={par({", (str_ptr-2)) ) { + else if (ciprefix("={par({", (str_ptr-2))) { // find expression beg_ptr = end_ptr = str_ptr + 5; while ((*end_ptr != ' ') && (*end_ptr != '\0')) @@ -4815,7 +5087,7 @@ static void inp_compat(struct line *deck) out_ptr = TMALLOC(char, 6); sprintf(out_ptr, "pa_%02d", (int)pai); // Bout_ptr out_ptr 0 V = v(expr_ptr) - xlen = 2*strlen(out_ptr) + strlen(exp_ptr )+ 15 - 2*3 + 1; + xlen = 2*strlen(out_ptr) + strlen(exp_ptr)+ 15 - 2*3 + 1; ckt_array[pai] = TMALLOC(char, xlen); sprintf(ckt_array[pai], "b%s %s 0 v = %s", out_ptr, out_ptr, exp_ptr); @@ -4837,22 +5109,22 @@ static void inp_compat(struct line *deck) tfree(del_ptr); tfree(exp_ptr); tfree(out_ptr); - } - // nothing to replace - else { + } else { + // nothing to replace cut_line = str_ptr + 1; continue; } } // while 'par' // no replacement done, go to next line - if (pai == paui) continue; + if (pai == paui) + continue; // remove white spaces card->li_line = inp_remove_ws(curr_line); // insert new B source line immediately after current line tmp_ptr = card->li_next; - for ( ii = paui; ii < pai; ii++ ) { - if ( param_end ) { + for (ii = paui; ii < pai; ii++) { + if (param_end) { param_end->li_next = alloc(struct line); param_end = param_end->li_next; } else { @@ -4874,19 +5146,23 @@ static void inp_compat(struct line *deck) param_beg = param_end = NULL; paui = pai; - } else if (( ciprefix(".save", curr_line) ) || ( ciprefix(".four", curr_line) ) - || ( ciprefix(".print", curr_line) ) || ( ciprefix(".plot", curr_line) )) { - if (strstr(curr_line, "par") == NULL) continue; + } else if ((ciprefix(".save", curr_line)) || + (ciprefix(".four", curr_line)) || + (ciprefix(".print", curr_line)) || + (ciprefix(".plot", curr_line))) + { + if (strstr(curr_line, "par") == NULL) + continue; cut_line = curr_line; // search for 'par' - while((str_ptr = strstr(cut_line, "par")) != NULL) { + while ((str_ptr = strstr(cut_line, "par")) != NULL) { if (pai > 99) { fprintf(stderr, "ERROR: No more than 99 'par' per input file!\n"); controlled_exit(EXIT_FAILURE); } // we have ' par({ ... })' - if ( ciprefix(" par({", (str_ptr-1)) ) { + if (ciprefix(" par({", (str_ptr-1))) { // find expression beg_ptr = end_ptr = str_ptr + 5; @@ -4898,7 +5174,7 @@ static void inp_compat(struct line *deck) out_ptr = TMALLOC(char, 6); sprintf(out_ptr, "pa_%02d", (int)pai); // Bout_ptr out_ptr 0 V = v(expr_ptr) - xlen = 2*strlen(out_ptr) + strlen(exp_ptr )+ 15 - 2*3 + 1; + xlen = 2*strlen(out_ptr) + strlen(exp_ptr)+ 15 - 2*3 + 1; ckt_array[pai] = TMALLOC(char, xlen); sprintf(ckt_array[pai], "b%s %s 0 v = %s", out_ptr, out_ptr, exp_ptr); @@ -4921,7 +5197,7 @@ static void inp_compat(struct line *deck) tfree(out_ptr); } // or we have '={par({ ... })}' - else if ( ciprefix("={par({", (str_ptr-2)) ) { + else if (ciprefix("={par({", (str_ptr-2))) { // find myoutput beg_ptr = end_ptr = str_ptr - 2; @@ -4935,7 +5211,7 @@ static void inp_compat(struct line *deck) end_ptr++; exp_ptr = copy_substring(beg_ptr, end_ptr-3); // Bout_ptr out_ptr 0 V = v(expr_ptr) - xlen = 2*strlen(out_ptr) + strlen(exp_ptr )+ 15 - 2*3 + 1; + xlen = 2*strlen(out_ptr) + strlen(exp_ptr)+ 15 - 2*3 + 1; ckt_array[pai] = TMALLOC(char, xlen); sprintf(ckt_array[pai], "b%s %s 0 v = %s", out_ptr, out_ptr, exp_ptr); @@ -4961,13 +5237,14 @@ static void inp_compat(struct line *deck) cut_line = str_ptr + 1; } // while 'par' // no replacement done, go to next line - if (pai == paui) continue; + if (pai == paui) + continue; // remove white spaces card->li_line = inp_remove_ws(curr_line); // insert new B source line immediately after current line tmp_ptr = card->li_next; - for ( ii = paui; ii < pai; ii++ ) { - if ( param_end ) { + for (ii = paui; ii < pai; ii++) { + if (param_end) { param_end->li_next = alloc(struct line); param_end = param_end->li_next; } else { @@ -4980,7 +5257,7 @@ static void inp_compat(struct line *deck) param_end->li_linenum = 0; } // comment out current variable capacitor line -// *(ckt_array[0]) = '*'; + // *(ckt_array[0]) = '*'; // insert new param lines immediately after current line tmp_ptr = card->li_next; card->li_next = param_beg; @@ -4990,23 +5267,26 @@ static void inp_compat(struct line *deck) param_beg = param_end = NULL; paui = pai; -// continue; + // continue; } // if .print etc. - } // if('.') + } // if ('.') } } + + /* lines for B sources: no parsing in numparam code, just replacement of parameters. Parsing done in B source parser. To achive this, do the following: Remove all '{' and '}' --> no parsing of equations in numparam Place '{' and '}' directly around all potential parameters, - thus skip function names like exp (search for exp( to detect fcn name), + thus skip function names like exp (search for exp(to detect fcn name), functions containing nodes like v(node), v(node1, node2), i(branch) and other keywords. --> Only parameter replacement in numparam */ -static void inp_bsource_compat(struct line *deck) +static void +inp_bsource_compat(struct line *deck) { char *equal_ptr, *str_ptr, *tmp_char, *new_str, *final_str; char actchar, prevchar = ' '; @@ -5022,17 +5302,17 @@ static void inp_bsource_compat(struct line *deck) char *curr_line = card->li_line; /* exclude any command inside .control ... .endc */ - if ( ciprefix(".control", curr_line) ) { + if (ciprefix(".control", curr_line)) { skip_control ++; continue; - } else if( ciprefix(".endc", curr_line) ) { + } else if (ciprefix(".endc", curr_line)) { skip_control --; continue; - } else if(skip_control > 0) { + } else if (skip_control > 0) { continue; } - if ( *curr_line == 'b' ) { + if (*curr_line == 'b') { /* remove white spaces of everything inside {}*/ card->li_line = inp_remove_ws(card->li_line); curr_line = card->li_line; @@ -5040,12 +5320,12 @@ static void inp_bsource_compat(struct line *deck) equal_ptr = strstr(curr_line, "="); /* check for errors */ if (equal_ptr == NULL) { - fprintf(stderr,"ERROR: mal formed B line: %s\n", curr_line); + fprintf(stderr, "ERROR: mal formed B line: %s\n", curr_line); controlled_exit(EXIT_FAILURE); } /* find the m={m} token and remove it */ - if((str_ptr = strstr(curr_line, "m={m}")) != NULL) - memcpy( str_ptr, " ", 5 ); + if ((str_ptr = strstr(curr_line, "m={m}")) != NULL) + memcpy(str_ptr, " ", 5); /* scan the line and remove all '{' and '}' */ str_ptr = curr_line; while (*str_ptr) { @@ -5058,12 +5338,14 @@ static void inp_bsource_compat(struct line *deck) while (*str_ptr != '\0') { while ((*str_ptr != '\0') && isspace(*str_ptr)) str_ptr++; - if (*str_ptr == '\0') break; + if (*str_ptr == '\0') + break; actchar = *str_ptr; wl_append_word(&wlist, &wl, NULL); - if ((actchar == ',') || (actchar == '(') || (actchar == ')') - || (actchar == '*') || (actchar == '/') || (actchar == '^') - || (actchar == '+') || (actchar == '?') || (actchar == ':')) { + if ((actchar == ',') || (actchar == '(') || (actchar == ')') || + (actchar == '*') || (actchar == '/') || (actchar == '^') || + (actchar == '+') || (actchar == '?') || (actchar == ':')) + { if ((actchar == '*') && (*(str_ptr+1) == '*')) { actchar = '^'; str_ptr++; @@ -5072,10 +5354,13 @@ static void inp_bsource_compat(struct line *deck) buf[1] = '\0'; wl->wl_word = copy(buf); str_ptr++; - if (actchar == ')') ustate = 0; - else ustate = 1; /* we have an operator */ - } else if ((actchar == '>') || (actchar == '<') - || (actchar == '!') || (actchar == '=') ) { + if (actchar == ')') + ustate = 0; + else + ustate = 1; /* we have an operator */ + } else if ((actchar == '>') || (actchar == '<') || + (actchar == '!') || (actchar == '=')) + { /* >=, <=, !=, ==, <>, ... */ char *beg = str_ptr++; if ((*str_ptr == '=') || (*str_ptr == '<') || (*str_ptr == '>')) @@ -5103,7 +5388,9 @@ static void inp_bsource_compat(struct line *deck) if (ustate == 2) { i = 1; buf[0] = '-'; - } else i = 0; + } else { + i = 0; + } if (((actchar == 'v') || (actchar == 'i')) && (*(str_ptr+1) == '(')) { while (*str_ptr != ')') { @@ -5116,9 +5403,12 @@ static void inp_bsource_compat(struct line *deck) wl->wl_word = copy(buf); str_ptr++; } else { - while (isalnum(*str_ptr) || (*str_ptr == '!') || (*str_ptr == '#') - || (*str_ptr == '$')|| (*str_ptr == '%')|| (*str_ptr == '_') - || (*str_ptr == '[')|| (*str_ptr == ']')) { + while (isalnum(*str_ptr) || + (*str_ptr == '!') || (*str_ptr == '#') || + (*str_ptr == '$') || (*str_ptr == '%') || + (*str_ptr == '_') || (*str_ptr == '[') || + (*str_ptr == ']')) + { buf[i] = *str_ptr; i++; str_ptr++; @@ -5126,9 +5416,11 @@ static void inp_bsource_compat(struct line *deck) buf[i] = '\0'; /* no parens {} around time, hertz, temper, the constants pi and e which are defined in inpptree.c, around pwl and temp. coeffs */ - if ((*str_ptr == '(') || cieq(buf, "hertz") || cieq(buf, "temper") - || cieq(buf, "time") || cieq(buf, "pi") || cieq(buf, "e") - || cieq(buf, "pwl")) { + if ((*str_ptr == '(') || + cieq(buf, "hertz") || cieq(buf, "temper") || + cieq(buf, "time") || cieq(buf, "pi") || + cieq(buf, "e") || cieq(buf, "pwl")) + { /* special handling of pwl lines: Put braces around tokens and around expressions, use ',' as separator like: @@ -5137,55 +5429,58 @@ static void inp_bsource_compat(struct line *deck) {x3+1},{y3}) */ /* - if (cieq(buf, "pwl")) { - // go past i(Vin) - i = 3; - while (*str_ptr != ')') { - buf[i] = *str_ptr; - i++; - str_ptr++; - } - buf[i] = *str_ptr; - i++; - str_ptr++; - // find first ',' - while (*str_ptr != ',') { - buf[i] = *str_ptr; - i++; - str_ptr++; - } - buf[i] = *str_ptr; - i++; - buf[i] = '{'; - i++; - str_ptr++; - while (*str_ptr != ')') { - if (*str_ptr == ',') { - buf[i] = '}'; - i++; - buf[i] = ','; - i++; - buf[i] = '{'; - i++; - str_ptr++; - } - else { - buf[i] = *str_ptr; - i++; - str_ptr++; - } - } - buf[i] = '}'; - i++; - buf[i] = *str_ptr; - i++; - buf[i] = '\0'; - str_ptr++; - } - */ + * if (cieq(buf, "pwl")) { + * // go past i(Vin) + * i = 3; + * while (*str_ptr != ')') { + * buf[i] = *str_ptr; + * i++; + * str_ptr++; + * } + * buf[i] = *str_ptr; + * i++; + * str_ptr++; + * // find first ',' + * while (*str_ptr != ',') { + * buf[i] = *str_ptr; + * i++; + * str_ptr++; + * } + * buf[i] = *str_ptr; + * i++; + * buf[i] = '{'; + * i++; + * str_ptr++; + * while (*str_ptr != ')') { + * if (*str_ptr == ',') { + * buf[i] = '}'; + * i++; + * buf[i] = ','; + * i++; + * buf[i] = '{'; + * i++; + * str_ptr++; + * } + * else { + * buf[i] = *str_ptr; + * i++; + * str_ptr++; + * } + * } + * buf[i] = '}'; + * i++; + * buf[i] = *str_ptr; + * i++; + * buf[i] = '\0'; + * str_ptr++; + * } + */ wl->wl_word = copy(buf); - } - else if (cieq(buf, "tc1") || cieq(buf, "tc2") || cieq(buf, "reciproctc")) { + + } else if (cieq(buf, "tc1") || cieq(buf, "tc2") || + cieq(buf, "reciproctc")) + { + while (isspace(*str_ptr)) str_ptr++; /* no {} around tc1 = or tc2 = , these are temp coeffs. */ @@ -5194,16 +5489,15 @@ static void inp_bsource_compat(struct line *deck) buf[i] = '\0'; str_ptr++; wl->wl_word = copy(buf); - } - else { + } else { xlen = strlen(buf); tmp_char = TMALLOC(char, xlen + 3); sprintf(tmp_char, "{%s}", buf); wl->wl_word = tmp_char; } - } - /* {} around all other tokens */ - else { + + } else { + /* {} around all other tokens */ xlen = strlen(buf); tmp_char = TMALLOC(char, xlen + 3); sprintf(tmp_char, "{%s}", buf); @@ -5218,11 +5512,11 @@ static void inp_bsource_compat(struct line *deck) /* unary -, change sign */ if (ustate == 2) dvalue *= -1; - sprintf(cvalue,"%18.10e", dvalue); + sprintf(cvalue, "%18.10e", dvalue); wl->wl_word = copy(cvalue); ustate = 0; /* we have a number */ /* skip the `unit', FIXME INPevaluate() should do this */ - while(isalpha(*str_ptr)) + while (isalpha(*str_ptr)) str_ptr++; } else { /* strange char */ printf("Preparing B line for numparam\nWhat is this?\n%s\n", str_ptr); @@ -5242,7 +5536,7 @@ static void inp_bsource_compat(struct line *deck) tmp_char = copy(curr_line); equal_ptr = strstr(tmp_char, "="); if (str_ptr == NULL) { - fprintf(stderr,"ERROR: mal formed B line: %s\n", curr_line); + fprintf(stderr, "ERROR: mal formed B line: %s\n", curr_line); controlled_exit(EXIT_FAILURE); } /* cut the tmp_char after the equal sign */ @@ -5281,7 +5575,8 @@ static void inp_bsource_compat(struct line *deck) * function will return the place from where to continue */ -static char *get_quoted_token(char *string, char **token) +static char * +get_quoted_token(char *string, char **token) { char *s = string; diff --git a/src/frontend/measure.c b/src/frontend/measure.c index 909480c7a..fd1ffa5fb 100644 --- a/src/frontend/measure.c +++ b/src/frontend/measure.c @@ -20,7 +20,8 @@ #include "com_commands.h" #include "com_display.h" -static wordlist *measure_parse_line( char *line ) ; + +static wordlist *measure_parse_line(char *line); static bool measure_valid[20000];/* TRUE: if measurement no. [xxx] has been done successfully (not used anywhere)*/ @@ -31,6 +32,7 @@ static bool measures_passed; /* TRUE: stop simulation (if option autostop is set extern bool ft_batchmode; extern bool rflag; + /* measure in interactive mode: meas command inside .control ... .endc loop or manually entered. meas has to be followed by the standard tokens (see measure_extract_variables()). @@ -42,12 +44,12 @@ com_meas(wordlist *wl) { /* wl: in, input line of meas command */ char *line_in, *outvar, newvec[1000]; - wordlist * wl_count, *wl_let; + wordlist *wl_count, *wl_let; char *vec_found, *token, *equal_ptr, newval[256]; wordlist *wl_index; struct dvec *d; - int err=0; + int err = 0; int fail; double result = 0; @@ -65,22 +67,22 @@ com_meas(wordlist *wl) treated in com_measure2.c. */ wl_index = wl; - while ( wl_index) { + while (wl_index) { token = wl_index->wl_word; /* find the vector vec_found, next token after each '=' sign. May be in the next wl_word */ - if ( *(token + strlen(token) - 1) == '=' ) { + if (*(token + strlen(token) - 1) == '=') { wl_index = wl_index->wl_next; vec_found = wl_index->wl_word; /* token may be already a value, maybe 'LAST', which we have to keep, or maybe a vector */ if (!cieq(vec_found, "LAST")) { - INPevaluate( &vec_found, &err, 1 ); + INPevaluate(&vec_found, &err, 1); /* if not a valid number */ if (err) { /* check if vec_found is a valid vector */ d = vec_get(vec_found); /* Only if we have a single valued vector, replacing - of the rigt hand side does make sense */ + of the rigt hand side does make sense */ if (d && (d->v_length == 1) && (d->v_numdims == 1)) { /* get its value */ sprintf(newval, "%e", d->v_realdata[0]); @@ -91,10 +93,10 @@ com_meas(wordlist *wl) } } /* may be inside the same wl_word */ - else if ( (equal_ptr = strstr( token, "=" )) != NULL ) { + else if ((equal_ptr = strstr(token, "=")) != NULL) { vec_found = equal_ptr + 1; if (!cieq(vec_found, "LAST")) { - INPevaluate( &vec_found, &err, 1 ); + INPevaluate(&vec_found, &err, 1); if (err) { d = vec_get(vec_found); /* Only if we have a single valued vector, replacing @@ -102,14 +104,14 @@ com_meas(wordlist *wl) if (d && (d->v_length == 1) && (d->v_numdims == 1)) { *equal_ptr = '\0'; sprintf(newval, "%s=%e", token, d->v_realdata[0]); -// memory leak with first part of vec_found ? + // memory leak with first part of vec_found ? tfree(token); wl_index->wl_word = copy(newval); } } } } else { - ;// nothing + ; // nothing } wl_index = wl_index->wl_next; } @@ -126,7 +128,7 @@ com_meas(wordlist *wl) } outvar = wl_count->wl_word; - fail = get_measure2(wl, &result, NULL, FALSE) ; + fail = get_measure2(wl, &result, NULL, FALSE); if (fail) { fprintf(stdout, " meas %s failed!\n\n", line_in); @@ -137,19 +139,21 @@ com_meas(wordlist *wl) wl_let = wl_cons(copy(newvec), NULL); com_let(wl_let); wl_free(wl_let); -// fprintf(stdout, "in: %s\n", line_in); + // fprintf(stdout, "in: %s\n", line_in); } static bool -chkAnalysisType( char *an_type ) +chkAnalysisType(char *an_type) { /* only support tran, dc, ac, sp analysis type for now */ - if ( strcmp( an_type, "tran" ) != 0 && strcmp( an_type, "ac" ) != 0 && - strcmp( an_type, "dc" ) != 0 && strcmp( an_type, "sp" ) != 0) + if (strcmp(an_type, "tran") != 0 && strcmp(an_type, "ac") != 0 && + strcmp(an_type, "dc") != 0 && strcmp(an_type, "sp") != 0) return FALSE; -// else if (ft_batchmode == TRUE) return FALSE; - else return TRUE; + // else if (ft_batchmode == TRUE) + // return FALSE; + else + return TRUE; } @@ -165,29 +169,31 @@ get_double_value( char *token = gettok(line); bool return_val = TRUE; char *equal_ptr, *junk; - int err=0; + int err = 0; - if ( name && ( strncmp( token, name, strlen(name) ) != 0 ) ) { - if ( just_chk_meas != TRUE ) fprintf( cp_err, "Error: syntax error for measure statement; expecting next field to be '%s'.\n", name ); + if (name && (strncmp(token, name, strlen(name)) != 0)) { + if (just_chk_meas != TRUE) fprintf(cp_err, "Error: syntax error for measure statement; expecting next field to be '%s'.\n", name); return_val = FALSE; } else { /* see if '=' is last char of current token -- implies we need to read value in next token */ - if ( *(token + strlen(token) - 1) == '=' ) { + if (*(token + strlen(token) - 1) == '=') { txfree(token); junk = token = gettok(line); - *value = INPevaluate( &junk, &err, 1 ); + *value = INPevaluate(&junk, &err, 1); } else { - if ( (equal_ptr = strstr( token, "=" )) != NULL ) { + if ((equal_ptr = strstr(token, "=")) != NULL) { equal_ptr += 1; - *value = INPevaluate( &equal_ptr, &err, 1 ); + *value = INPevaluate(&equal_ptr, &err, 1); } else { - if ( just_chk_meas != TRUE ) fprintf( cp_err, "Error: syntax error for measure statement; missing '='!\n" ); + if (just_chk_meas != TRUE) + fprintf(cp_err, "Error: syntax error for measure statement; missing '='!\n"); return_val = FALSE; } } - if ( err ) { - if ( just_chk_meas != TRUE ) fprintf( cp_err, "Error: Bad value.\n" ); + if (err) { + if (just_chk_meas != TRUE) + fprintf(cp_err, "Error: Bad value.\n"); return_val = FALSE; } } @@ -213,17 +219,17 @@ do_measure( struct line *meas_card, *meas_results = NULL, *end = NULL, *newcard; char *line, *an_name, *an_type, *resname, *meastype, *str_ptr, out_line[1000]; int idx = 0, ok = 0; - int fail; + int fail; double result = 0; bool first_time = TRUE; - wordlist *measure_word_list ; - int precision = measure_get_precision() ; + wordlist *measure_word_list; + int precision = measure_get_precision(); just_chk_meas = chk_only; - an_name = strdup( what ); /* analysis type, e.g. "tran" */ - strtolower( an_name ); - measure_word_list = NULL ; + an_name = strdup(what); /* analysis type, e.g. "tran" */ + strtolower(an_name); + measure_word_list = NULL; /* don't allow .meas if batchmode is set by -b and -r rawfile given */ if (ft_batchmode && rflag) { @@ -248,7 +254,7 @@ do_measure( */ /* first pass through .meas cards: evaluate everything except param|expr */ - for ( meas_card = ft_curckt->ci_meas; meas_card != NULL; meas_card = meas_card->li_next ) { + for (meas_card = ft_curckt->ci_meas; meas_card != NULL; meas_card = meas_card->li_next) { line = meas_card->li_line; txfree(gettok(&line)); /* discard .meas */ @@ -257,10 +263,10 @@ do_measure( resname = gettok(&line); meastype = gettok(&line); - if ( chkAnalysisType( an_type ) != TRUE ) { - if ( just_chk_meas != TRUE ) { - fprintf( cp_err, "Error: unrecognized analysis type '%s' for the following .meas statement on line %d:\n", an_type, meas_card->li_linenum ); - fprintf( cp_err, " %s\n", meas_card->li_line ); + if (chkAnalysisType(an_type) != TRUE) { + if (just_chk_meas != TRUE) { + fprintf(cp_err, "Error: unrecognized analysis type '%s' for the following .meas statement on line %d:\n", an_type, meas_card->li_linenum); + fprintf(cp_err, " %s\n", meas_card->li_line); } txfree(an_type); @@ -269,20 +275,21 @@ do_measure( continue; } /* print header before evaluating first .meas line */ - else if ( first_time ) { + else if (first_time) { first_time = FALSE; - if ( just_chk_meas != TRUE && strcmp( an_type, "tran" ) == 0 ) { - fprintf( stdout, " Transient Analysis\n\n" ); -// plot_cur = setcplot("tran"); + if (just_chk_meas != TRUE && strcmp(an_type, "tran") == 0) { + fprintf(stdout, " Transient Analysis\n\n"); + // plot_cur = setcplot("tran"); } } /* skip param|expr measurement types for now -- will be done after other measurements */ - if ( strncmp( meastype, "param", 5 ) == 0 || strncmp( meastype, "expr", 4 ) == 0 ) continue; + if (strncmp(meastype, "param", 5) == 0 || strncmp(meastype, "expr", 4) == 0) + continue; /* skip .meas line, if analysis type from line and name of analysis performed differ */ - if ( strcmp( an_name, an_type ) != 0 ) { + if (strcmp(an_name, an_type) != 0) { txfree(an_type); txfree(resname); txfree(meastype); @@ -291,22 +298,21 @@ do_measure( /* New way of processing measure statements using common code in fcn get_measure2() (com_measure2.c)*/ - out_line[0] = '\0' ; - measure_word_list = measure_parse_line( meas_card->li_line) ; - if( measure_word_list ) { - fail = get_measure2(measure_word_list,&result,out_line,chk_only) ; - if( fail ) { + out_line[0] = '\0'; + measure_word_list = measure_parse_line(meas_card->li_line); + if (measure_word_list) { + fail = get_measure2(measure_word_list, &result, out_line, chk_only); + if (fail) { measure_valid[idx++] = FALSE; measures_passed = FALSE; if (!chk_only) fprintf(stderr, " %s failed!\n\n", meas_card->li_line); } else { - if(!(just_chk_meas)) { - nupa_add_param( resname, result ); - } + if (!(just_chk_meas)) + nupa_add_param(resname, result); measure_valid[idx++] = TRUE; } - wl_free( measure_word_list ) ; + wl_free(measure_word_list); } else { measure_valid[idx++] = FALSE; measures_passed = FALSE; @@ -316,8 +322,9 @@ do_measure( newcard->li_line = strdup(out_line); newcard->li_next = NULL; - if ( meas_results == NULL ) meas_results = end = newcard; - else { + if (meas_results == NULL) { + meas_results = end = newcard; + } else { end->li_next = newcard; end = newcard; } @@ -327,8 +334,8 @@ do_measure( txfree(meastype); /* see if number of measurements exceeds fixed array size of 20,000 */ - if ( idx >= 20000 ) { - fprintf( stderr, "ERROR: number of measurements exceeds 20,000!\nAborting...\n" ); + if (idx >= 20000) { + fprintf(stderr, "ERROR: number of measurements exceeds 20,000!\nAborting...\n"); controlled_exit(EXIT_FAILURE); } @@ -337,7 +344,7 @@ do_measure( /* second pass through .meas cards: now do param|expr .meas statements */ newcard = meas_results; - for ( meas_card = ft_curckt->ci_meas; meas_card != NULL; meas_card = meas_card->li_next ) { + for (meas_card = ft_curckt->ci_meas; meas_card != NULL; meas_card = meas_card->li_next) { line = meas_card->li_line; txfree(gettok(&line)); /* discard .meas */ @@ -346,10 +353,10 @@ do_measure( resname = gettok(&line); meastype = gettok(&line); - if ( chkAnalysisType( an_type ) != TRUE ) { - if ( just_chk_meas != TRUE ) { - fprintf( cp_err, "Error: unrecognized analysis type '%s' for the following .meas statement on line %d:\n", an_type, meas_card->li_linenum ); - fprintf( cp_err, " %s\n", meas_card->li_line ); + if (chkAnalysisType(an_type) != TRUE) { + if (just_chk_meas != TRUE) { + fprintf(cp_err, "Error: unrecognized analysis type '%s' for the following .meas statement on line %d:\n", an_type, meas_card->li_linenum); + fprintf(cp_err, " %s\n", meas_card->li_line); } txfree(an_type); @@ -357,21 +364,22 @@ do_measure( txfree(meastype); continue; } - if ( strcmp( an_name, an_type ) != 0 ) { + if (strcmp(an_name, an_type) != 0) { txfree(an_type); txfree(resname); txfree(meastype); continue; } - if ( strncmp( meastype, "param", 5 ) != 0 && strncmp( meastype, "expr", 4 ) != 0 ) { + if (strncmp(meastype, "param", 5) != 0 && strncmp(meastype, "expr", 4) != 0) { - if ( just_chk_meas != TRUE ) fprintf( stdout, "%s", newcard->li_line ); + if (just_chk_meas != TRUE) + fprintf(stdout, "%s", newcard->li_line); end = newcard; newcard = newcard->li_next; - txfree( end->li_line ); - txfree( end ); + txfree(end->li_line); + txfree(end); txfree(an_type); txfree(resname); @@ -379,21 +387,25 @@ do_measure( continue; } - if ( just_chk_meas != TRUE ) fprintf( stdout, "%-20s=", resname ); + if (just_chk_meas != TRUE) + fprintf(stdout, "%-20s=", resname); - if ( just_chk_meas != TRUE ) { - ok = nupa_eval( meas_card->li_line, meas_card->li_linenum, meas_card->li_linenum_orig ); + if (just_chk_meas != TRUE) { + ok = nupa_eval(meas_card->li_line, meas_card->li_linenum, meas_card->li_linenum_orig); - if ( ok ) { - str_ptr = strstr( meas_card->li_line, meastype ); - if ( !get_double_value( &str_ptr, meastype, &result ) ) { - if ( just_chk_meas != TRUE ) fprintf( stdout, " failed\n" ); + if (ok) { + str_ptr = strstr(meas_card->li_line, meastype); + if (!get_double_value(&str_ptr, meastype, &result)) { + if (just_chk_meas != TRUE) + fprintf(stdout, " failed\n"); } else { - if ( just_chk_meas != TRUE ) fprintf( stdout, " %.*e\n", precision, result ); - nupa_add_param( resname, result ); + if (just_chk_meas != TRUE) + fprintf(stdout, " %.*e\n", precision, result); + nupa_add_param(resname, result); } } else { - if ( just_chk_meas != TRUE ) fprintf( stdout, " failed\n" ); + if (just_chk_meas != TRUE) + fprintf(stdout, " failed\n"); } } txfree(an_type); @@ -401,11 +413,12 @@ do_measure( txfree(meastype); } - if ( just_chk_meas != TRUE ) fprintf( stdout, "\n" ); + if (just_chk_meas != TRUE) + fprintf(stdout, "\n"); txfree(an_name); - fflush( stdout ); + fflush(stdout); //nupa_list_params(); } @@ -418,55 +431,57 @@ do_measure( set to FALSE during calling do_measure. 'what' is set to "tran".*/ bool -check_autostop( char* what ) +check_autostop(char* what) { bool flag = FALSE; measures_passed = TRUE; - if ( cp_getvar( "autostop", CP_BOOL, NULL) ) { - do_measure( what, TRUE ); + if (cp_getvar("autostop", CP_BOOL, NULL)) { + do_measure(what, TRUE); - if ( measures_passed == TRUE ) flag = TRUE; + if (measures_passed == TRUE) + flag = TRUE; } return flag; } -/* parses the .meas line into a wordlist (without leading .meas) */ -static wordlist *measure_parse_line( char *line ) -{ - size_t len ; /* length of string */ - wordlist *wl ; /* build a word list - head of list */ - wordlist *new_item ; /* single item of a list */ - char *item ; /* parsed item */ - char *long_str ; /* concatenated string */ - char *extra_item ; /* extra item */ - wl = NULL ; - (void) gettok(&line) ; +/* parses the .meas line into a wordlist (without leading .meas) */ +static wordlist * +measure_parse_line(char *line) +{ + size_t len; /* length of string */ + wordlist *wl; /* build a word list - head of list */ + wordlist *new_item; /* single item of a list */ + char *item; /* parsed item */ + char *long_str; /* concatenated string */ + char *extra_item; /* extra item */ + + wl = NULL; + (void) gettok(&line); do { - item = gettok(&line) ; - if(!(item)) { - break ; - } - len = strlen(item) ; - if( item[len-1] == '=' ) { + item = gettok(&line); + if (!(item)) + break; + + len = strlen(item); + if (item[len-1] == '=') { /* We can't end on an equal append the next piece */ - extra_item = gettok(&line) ; - if(!(extra_item)) { - break ; - } - len += strlen( extra_item ) + 2 ; - long_str = TMALLOC(char, len) ; - sprintf( long_str, "%s%s", item, extra_item ) ; - txfree( item ) ; - txfree( extra_item ) ; - item = long_str ; + extra_item = gettok(&line); + if (!(extra_item)) + break; + + len += strlen(extra_item) + 2; + long_str = TMALLOC(char, len); + sprintf(long_str, "%s%s", item, extra_item); + txfree(item); + txfree(extra_item); + item = long_str; } new_item = wl_cons(item, NULL); - wl = wl_append(wl, new_item) ; - } while( line && *line ) ; + wl = wl_append(wl, new_item); + } while (line && *line); - return(wl) ; - -} /* end measure_parse_line() */ + return (wl); +} diff --git a/src/frontend/misccoms.c b/src/frontend/misccoms.c index aede25d06..7454b279b 100644 --- a/src/frontend/misccoms.c +++ b/src/frontend/misccoms.c @@ -49,7 +49,7 @@ com_quit(wordlist *wl) /* Make sure the guy really wants to quit. */ if (!ft_nutmeg) - if(!noask && !confirm_quit()) + if (!noask && !confirm_quit()) return; /* start to clean up the mess */ @@ -65,7 +65,7 @@ com_quit(wordlist *wl) if (!ft_nutmeg) { struct circ *cc; for (cc = ft_circuits; cc; cc = cc->ci_next) - if(SIMinfo.deleteCircuit) + if (SIMinfo.deleteCircuit) SIMinfo.deleteCircuit(cc->ci_ckt); } #endif @@ -167,7 +167,7 @@ com_version(wordlist *wl) fprintf(cp_out, "** Creation Date: %s\n", Spice_Build_Date); fprintf(cp_out, "******\n"); - } else if (!strncasecmp(s, "-f", 2)) { + } else if (!strncasecmp(s, "-f", 2)) { fprintf(cp_out, "******\n" @@ -307,5 +307,5 @@ confirm_quit(void) *buf = 'y'; } - return((*buf == 'y') || (*buf == 'Y') || (*buf == '\n')); + return ((*buf == 'y') || (*buf == 'Y') || (*buf == '\n')); } diff --git a/src/frontend/newcoms.c b/src/frontend/newcoms.c index 3c6d984fc..2e806a671 100644 --- a/src/frontend/newcoms.c +++ b/src/frontend/newcoms.c @@ -15,200 +15,205 @@ Copyright 1992 Regents of the University of California. All rights reserved. #include "newcoms.h" #include "quote.h" + /* - * reshape v(1) vxx#branch [10] - * reshape v(1) vxx#branch [10,4] - * reshape v(1) [,4] + * reshape v(1) vxx#branch [10] + * reshape v(1) vxx#branch [10,4] + * reshape v(1) [,4] */ void com_reshape(wordlist *wl) { - wordlist *w, *w2, *wlast, *wsave; - char *p; - struct dvec *dv, *d; - int numdims; - int *dims; - int local_dims[MAXDIMS]; - int state; - int empty; - int err; - int missing, nprod, prod; - char *vname; - int i; + wordlist *w, *w2, *wlast, *wsave; + char *p; + struct dvec *dv, *d; + int numdims; + int *dims; + int local_dims[MAXDIMS]; + int state; + int empty; + int err; + int missing, nprod, prod; + char *vname; + int i; do { - if (!wl) - return; + if (!wl) + return; - /* find the first '[' */ + /* find the first '[' */ - p = NULL; - for (w = wl; w; w = w->wl_next) { - if ((p = strchr(w->wl_word, '[')) != NULL) - break; - } + p = NULL; + for (w = wl; w; w = w->wl_next) { + if ((p = strchr(w->wl_word, '[')) != NULL) + break; + } - if (p && *p) { - if (p != w->wl_word) - w = w->wl_next; - wlast = w; - *p++ = 0; - } else - wlast = NULL; + if (p && *p) { + if (p != w->wl_word) + w = w->wl_next; + wlast = w; + *p++ = 0; + } else { + wlast = NULL; + } - /* get the dimensions */ - dims = local_dims; - numdims = 0; - state = 0; - empty = -1; - err = 0; - wsave = NULL; - do { + /* get the dimensions */ + dims = local_dims; + numdims = 0; + state = 0; + empty = -1; + err = 0; + wsave = NULL; + do { - if (!p || !*p) { - if (!wlast) - break; - p = wlast->wl_word; - if (state == 2) - wsave = wlast; - else - wsave = NULL; - wlast = wlast->wl_next; - } + if (!p || !*p) { + if (!wlast) + break; + p = wlast->wl_word; + if (state == 2) + wsave = wlast; + else + wsave = NULL; + wlast = wlast->wl_next; + } - while (*p && isspace(*p)) - p++; + while (*p && isspace(*p)) + p++; - switch (state) { - case 0: /* p just at or before a number */ + switch (state) { + case 0: /* p just at or before a number */ - if (numdims >= MAXDIMS) { - if (numdims == MAXDIMS) - printf("Maximum of %d dimensions possible\n", MAXDIMS); - numdims += 1; - } else if (!isdigit(*p)) { - if (empty > -1) { - printf("dimensions underspecified at dimension %d\n", - numdims++); - err = 1; - } else { - empty = numdims; - dims[numdims++] = 1; - } - } else { - dims[numdims++] = atoi(p); - while (isdigit(*p)) - p++; - } - state = 1; - break; + if (numdims >= MAXDIMS) { + if (numdims == MAXDIMS) + printf("Maximum of %d dimensions possible\n", MAXDIMS); + numdims += 1; + } else if (!isdigit(*p)) { + if (empty > -1) { + printf("dimensions underspecified at dimension %d\n", + numdims++); + err = 1; + } else { + empty = numdims; + dims[numdims++] = 1; + } + } else { + dims[numdims++] = atoi(p); + while (isdigit(*p)) + p++; + } + state = 1; + break; - case 1: /* p after a number, looking for ',' or ']' */ - if (*p == ']') { - p++; - state = 2; - } else if (*p == ',') { - p++; - state = 0; - } else if (isdigit(*p)) { - state = 0; - break; - } else if (!isspace(*p)) - /* error */ - state = 4; - break; + case 1: /* p after a number, looking for ',' or ']' */ + if (*p == ']') { + p++; + state = 2; + } else if (*p == ',') { + p++; + state = 0; + } else if (isdigit(*p)) { + state = 0; + break; + } else if (!isspace(*p)) { + /* error */ + state = 4; + } + break; - case 2: /* p after a ']', either at the end or looking for '[' */ - if (*p == '[') { - p++; - state = 0; - } else { - state = 3; - } - } + case 2: /* p after a ']', either at the end or looking for '[' */ + if (*p == '[') { + p++; + state = 0; + } else { + state = 3; + } + } - while (*p && isspace(*p)) - p++; + while (*p && isspace(*p)) + p++; - } while (state < 3); + } while (state < 3); - if (state == 2) { - wlast = wsave; - } else if ((state == 4 || state < 2) && ((state != 0 || p) && *p)) { - printf("syntax error specifying dimensions\n"); - return; - } + if (state == 2) { + wlast = wsave; + } else if ((state == 4 || state < 2) && ((state != 0 || p) && *p)) { + printf("syntax error specifying dimensions\n"); + return; + } - if (numdims > MAXDIMS) - continue; - if (err) - continue; + if (numdims > MAXDIMS) + continue; + if (err) + continue; - /* Copy dimensions from the first item if none are explicitly given */ - if (!numdims) { - /* Copy from the first */ - vname = cp_unquote(wl->wl_word); - dv = vec_get(vname); - if (!dv) { - printf("'%s' dimensions vector not found\n", vname); - return; - } - numdims = dv->v_numdims; - dims = dv->v_dims; - wl = wl->wl_next; - empty = -1; /* just in case */ - } + /* Copy dimensions from the first item if none are explicitly given */ + if (!numdims) { + /* Copy from the first */ + vname = cp_unquote(wl->wl_word); + dv = vec_get(vname); + if (!dv) { + printf("'%s' dimensions vector not found\n", vname); + return; + } + numdims = dv->v_numdims; + dims = dv->v_dims; + wl = wl->wl_next; + empty = -1; /* just in case */ + } - prod = 1; - for (i = 0; i < numdims; i++) - prod *= dims[i]; + prod = 1; + for (i = 0; i < numdims; i++) + prod *= dims[i]; - /* resize each vector */ - for (w2 = wl; w2 && w2 != w; w2 = w2->wl_next) { - vname = cp_unquote(w2->wl_word); + /* resize each vector */ + for (w2 = wl; w2 && w2 != w; w2 = w2->wl_next) { + vname = cp_unquote(w2->wl_word); - dv = vec_get(vname); - if (!dv) { - printf("'%s' vector not found\n", vname); - continue; - } + dv = vec_get(vname); + if (!dv) { + printf("'%s' vector not found\n", vname); + continue; + } - /* The name may expand to several vectors */ - for (d = dv; d; d = d->v_link2) { - nprod = 1; - for (i = 0; i < d->v_numdims; i++) - nprod *= d->v_dims[i]; - if (nprod != d->v_length) { - printf("dimensions of \"%s\" were inconsistent\n", - d->v_name); - nprod = d->v_length; - } + /* The name may expand to several vectors */ + for (d = dv; d; d = d->v_link2) { + nprod = 1; + for (i = 0; i < d->v_numdims; i++) + nprod *= d->v_dims[i]; + if (nprod != d->v_length) { + printf("dimensions of \"%s\" were inconsistent\n", + d->v_name); + nprod = d->v_length; + } - missing = nprod / prod; - if (missing * prod != nprod) { - printf("dimensions don't fit \"%s\" (total size = %d)\n", - d->v_name, nprod); - continue; - } + missing = nprod / prod; + if (missing * prod != nprod) { + printf("dimensions don't fit \"%s\" (total size = %d)\n", + d->v_name, nprod); + continue; + } - if (missing > 1 && empty < 0) { - /* last dimension unspecified */ - d->v_numdims = numdims + 1; - d->v_dims[numdims] = missing; - } else - d->v_numdims = numdims; + if (missing > 1 && empty < 0) { + /* last dimension unspecified */ + d->v_numdims = numdims + 1; + d->v_dims[numdims] = missing; + } else { + d->v_numdims = numdims; + } - /* fill in dimensions */ - for (i = 0; i < numdims; i++) { - if (i == empty) - d->v_dims[i] = missing; - else - d->v_dims[i] = dims[i]; - } - } - if (vname) - tfree(vname); - } + /* fill in dimensions */ + for (i = 0; i < numdims; i++) { + if (i == empty) + d->v_dims[i] = missing; + else + d->v_dims[i] = dims[i]; + } + } + + if (vname) + tfree(vname); + } } while ((wl = wlast) != NULL); } diff --git a/src/frontend/numparam/general.h b/src/frontend/numparam/general.h index bf05cc053..7c90e5c64 100644 --- a/src/frontend/numparam/general.h +++ b/src/frontend/numparam/general.h @@ -1,8 +1,8 @@ /* general.h */ /* include beforehand the following: -#include // NULL FILE fopen feof fgets fclose fputs fputc gets -#include +#include // NULL FILE fopen feof fgets fclose fputs fputc gets +#include the function code is in 'mystring.c' . */ #include "ngspice/dstring.h" @@ -12,26 +12,26 @@ typedef char string[258]; -void sfix( SPICE_DSTRINGPTR dstr_p, int len) ; -char * pscopy( SPICE_DSTRINGPTR s, char * a, int i,int j); -char * pscopy_up( SPICE_DSTRINGPTR s, char * a, int i,int j); -bool scopyd( SPICE_DSTRINGPTR a, SPICE_DSTRINGPTR b); -bool scopys( SPICE_DSTRINGPTR a, char *b); -bool scopy_up( SPICE_DSTRINGPTR a, char *str) ; -bool scopy_lower( SPICE_DSTRINGPTR a, char *str) ; -bool ccopy( SPICE_DSTRINGPTR a, char c); -bool sadd( SPICE_DSTRINGPTR s, char * t); -bool nadd( SPICE_DSTRINGPTR s, long n); -bool cadd( SPICE_DSTRINGPTR s, char c); -bool naddll( SPICE_DSTRINGPTR s, long long n); -bool cins( SPICE_DSTRINGPTR s, char c); -bool sins( SPICE_DSTRINGPTR s, char * t); -int cpos( char c, char *s); -int spos_( char * sub, char * s); -bool ci_prefix( register char *p, register char *s ); -int length(char * s); -bool steq(char * s, char * t); -bool stne(char * s, char * t); +void sfix(SPICE_DSTRINGPTR dstr_p, int len); +char *pscopy(SPICE_DSTRINGPTR s, char *a, int i, int j); +char *pscopy_up(SPICE_DSTRINGPTR s, char *a, int i, int j); +bool scopyd(SPICE_DSTRINGPTR a, SPICE_DSTRINGPTR b); +bool scopys(SPICE_DSTRINGPTR a, char *b); +bool scopy_up(SPICE_DSTRINGPTR a, char *str); +bool scopy_lower(SPICE_DSTRINGPTR a, char *str); +bool ccopy(SPICE_DSTRINGPTR a, char c); +bool sadd(SPICE_DSTRINGPTR s, char *t); +bool nadd(SPICE_DSTRINGPTR s, long n); +bool cadd(SPICE_DSTRINGPTR s, char c); +bool naddll(SPICE_DSTRINGPTR s, long long n); +bool cins(SPICE_DSTRINGPTR s, char c); +bool sins(SPICE_DSTRINGPTR s, char *t); +int cpos(char c, char *s); +int spos_(char *sub, char *s); +bool ci_prefix(register char *p, register char *s); +int length(char *s); +bool steq(char *s, char *t); +bool stne(char *s, char *t); void stri(long n, SPICE_DSTRINGPTR s); char upcase(char c); @@ -39,18 +39,18 @@ char lowcase(char c); bool alfa(char c); bool num(char c); bool alfanum(char c); -char * stupcase( char * s); +char *stupcase(char *s); /***** primitive input-output ***/ -void rs( SPICE_DSTRINGPTR s); +void rs(SPICE_DSTRINGPTR s); char rc(void); -int freadstr(FILE * f, SPICE_DSTRINGPTR dstr_p); +int freadstr(FILE *f, SPICE_DSTRINGPTR dstr_p); long np_round(double d); // sjb to avoid clash with round() in math.h long np_trunc(double x); // sjb to avoid clash with trunc() in math.h double absf(double x); /* abs */ -long absi( long i); +long absi(long i); -void * new(size_t sz); -void dispose(void * p); +void *new(size_t sz); +void dispose(void *p); diff --git a/src/frontend/numparam/mystring.c b/src/frontend/numparam/mystring.c index 4c004be7d..d246e45ab 100644 --- a/src/frontend/numparam/mystring.c +++ b/src/frontend/numparam/mystring.c @@ -21,33 +21,35 @@ #include "ngspice/fteext.h" /* controlled_exit() */ + /***** primitive input-output ***/ bool -ci_prefix (register char *p, register char *s) +ci_prefix(register char *p, register char *s) { - while (*p) - { - if ((isupper (*p) ? tolower (*p) : *p) != - (isupper (*s) ? tolower (*s) : *s)) + while (*p) { + if ((isupper(*p) ? tolower(*p) : *p) != + (isupper(*s) ? tolower(*s) : *s)) return (0); p++; s++; } + return (1); } + void -rs ( SPICE_DSTRINGPTR dstr_p) +rs(SPICE_DSTRINGPTR dstr_p) { /* basic line input, limit= 80 chars */ char c; - spice_dstring_reinit(dstr_p) ; + spice_dstring_reinit(dstr_p); do { - c = (char) fgetc (stdin); - cadd (dstr_p, c); + c = (char) fgetc(stdin); + cadd(dstr_p, c); } while (!((c == '\r') || (c == '\n'))); } @@ -71,7 +73,7 @@ rs ( SPICE_DSTRINGPTR dstr_p) */ void -sfix ( SPICE_DSTRINGPTR dstr_p, int len) +sfix(SPICE_DSTRINGPTR dstr_p, int len) /* suppose s is allocated and filled with non-zero stuff */ { /* This function will now eliminate the max field. The length of @@ -80,90 +82,94 @@ sfix ( SPICE_DSTRINGPTR dstr_p, int len) * null characters will be present in the string leading up to the * NULL so this will make it a valid string. */ int j; - char *s ; + char *s; - spice_dstring_setlength( dstr_p, len ) ; - s = spice_dstring_value( dstr_p ) ; - for (j = 0; j < len; j++) /* eliminate null characters ! */ + spice_dstring_setlength(dstr_p, len); + s = spice_dstring_value(dstr_p); + for (j = 0; j < len; j++) /* eliminate null characters ! */ if (s[j] == 0) s[j] = 1; - } + int -length (char *s) +length(char *s) { return (int) strlen(s); } + /* ----------------------------------------------------------------- * Function: add string t to dynamic string dstr_p. * ----------------------------------------------------------------- */ bool -sadd ( SPICE_DSTRINGPTR dstr_p, char *t) +sadd(SPICE_DSTRINGPTR dstr_p, char *t) { - spice_dstring_append( dstr_p, t, -1 ) ; - return 1 ; + spice_dstring_append(dstr_p, t, -1); + return 1; } + /* ----------------------------------------------------------------- * Function: add character c to dynamic string dstr_p. * ----------------------------------------------------------------- */ bool -cadd ( SPICE_DSTRINGPTR dstr_p, char c) +cadd(SPICE_DSTRINGPTR dstr_p, char c) { - char tmp_str[2] ; - tmp_str[0] = c ; - tmp_str[1] = '\0' ; - spice_dstring_append( dstr_p, tmp_str, -1 ) ; - return 1 ; + char tmp_str[2]; + tmp_str[0] = c; + tmp_str[1] = '\0'; + spice_dstring_append(dstr_p, tmp_str, -1); + return 1; } + /* ----------------------------------------------------------------- * Function: insert character c at front of dynamic string dstr_p * ----------------------------------------------------------------- */ bool -cins ( SPICE_DSTRINGPTR dstr_p, char c) +cins(SPICE_DSTRINGPTR dstr_p, char c) { - int i ; - int ls ; - char *s_p ; + int i; + int ls; + char *s_p; - ls = spice_dstring_length(dstr_p) ; - spice_dstring_setlength(dstr_p,ls+2) ; /* make sure we have space for char + EOS */ - s_p = spice_dstring_value(dstr_p) ; + ls = spice_dstring_length(dstr_p); + spice_dstring_setlength(dstr_p, ls+2); /* make sure we have space for char + EOS */ + s_p = spice_dstring_value(dstr_p); for (i = ls + 1; i >= 0; i--) s_p[i + 1] = s_p[i]; s_p[0] = c; - return 1 ; + return 1; } + /* ----------------------------------------------------------------- * Function: insert string t at front of dynamic string dstr_p * ----------------------------------------------------------------- */ bool -sins ( SPICE_DSTRINGPTR dstr_p, char *t) +sins(SPICE_DSTRINGPTR dstr_p, char *t) { - int i ; - int ls ; - int lt ; - char *s_p ; + int i; + int ls; + int lt; + char *s_p; - ls = spice_dstring_length(dstr_p) ; - lt = length (t) ; - spice_dstring_setlength(dstr_p,ls+lt+1) ; /* make sure we have space for string + EOS */ - s_p = spice_dstring_value(dstr_p) ; + ls = spice_dstring_length(dstr_p); + lt = length(t); + spice_dstring_setlength(dstr_p, ls+lt+1); /* make sure we have space for string + EOS */ + s_p = spice_dstring_value(dstr_p); for (i = ls + 1; i >= 0; i--) s_p[i + lt] = s_p[i]; for (i = 0; i < lt; i++) s_p[i] = t[i]; - return 1 ; - + return 1; } + int -cpos (char c, char *s) +cpos(char c, char *s) /* return position of c in s, or 0 if not found. * BUG, Pascal inherited: first char is at 1, not 0 ! * No longer! Now position is C-based to make life easier. @@ -174,13 +180,14 @@ cpos (char c, char *s) i++; if (s[i] == c) - return i ; + return i; else - return -1 ; + return -1; } + char -upcase (char c) +upcase(char c) { if ((c >= 'a') && (c <= 'z')) return (char) (c + 'A' - 'a'); @@ -188,256 +195,265 @@ upcase (char c) return c; } + /* ----------------------------------------------------------------- * Create copy of the dynamic string. Dynamic strings are always NULL * terminated. * ----------------------------------------------------------------- */ bool -scopyd(SPICE_DSTRINGPTR s, SPICE_DSTRINGPTR t) /* returns success flag */ +scopyd(SPICE_DSTRINGPTR s, SPICE_DSTRINGPTR t) /* returns success flag */ { - spice_dstring_reinit( s ) ; - spice_dstring_append( s, spice_dstring_value(t), -1 ) ; - return 1 ; /* Dstrings expand to any length */ + spice_dstring_reinit(s); + spice_dstring_append(s, spice_dstring_value(t), -1); + return 1; /* Dstrings expand to any length */ } + /* ----------------------------------------------------------------- * Create copy of the string in the dynamic string. Dynamic strings * are always NULLterminated. * ----------------------------------------------------------------- */ bool -scopys(SPICE_DSTRINGPTR s, char *t) /* returns success flag */ +scopys(SPICE_DSTRINGPTR s, char *t) /* returns success flag */ { - spice_dstring_reinit( s ) ; - spice_dstring_append( s, t, -1 ) ; - return 1 ; /* Dstrings expand to any length */ + spice_dstring_reinit(s); + spice_dstring_append(s, t, -1); + return 1; /* Dstrings expand to any length */ } + /* ----------------------------------------------------------------- * Create an upper case copy of a string and store it in a dynamic string. * Dynamic strings are always NULL * terminated. * ----------------------------------------------------------------- */ bool -scopy_up (SPICE_DSTRINGPTR dstr_p, char *str) /* returns success flag */ +scopy_up(SPICE_DSTRINGPTR dstr_p, char *str) /* returns success flag */ { - char up[2] ; /* short string */ - char *ptr ; /* position in string */ + char up[2]; /* short string */ + char *ptr; /* position in string */ - spice_dstring_reinit( dstr_p ) ; - up[1] = '\0' ; - for( ptr = str ; ptr && *ptr ; ptr++ ) - { - up[0] = upcase ( *ptr ); - spice_dstring_append( dstr_p, up, 1 ) ; + spice_dstring_reinit(dstr_p); + up[1] = '\0'; + for (ptr = str; ptr && *ptr; ptr++) { + up[0] = upcase(*ptr); + spice_dstring_append(dstr_p, up, 1); } - return 1 ; /* Dstrings expand to any length */ + return 1; /* Dstrings expand to any length */ } + /* ----------------------------------------------------------------- * Create a lower case copy of a string and store it in a dynamic string. * Dynamic strings are always NULL * terminated. * ----------------------------------------------------------------- */ bool -scopy_lower (SPICE_DSTRINGPTR dstr_p, char *str) /* returns success flag */ +scopy_lower(SPICE_DSTRINGPTR dstr_p, char *str) /* returns success flag */ { - char low[2] ; /* short string */ - char *ptr ; /* position in string */ + char low[2]; /* short string */ + char *ptr; /* position in string */ - spice_dstring_reinit( dstr_p ) ; - low[1] = '\0' ; - for( ptr = str ; ptr && *ptr ; ptr++ ) - { - low[0] = lowcase ( *ptr ); - spice_dstring_append( dstr_p, low, 1 ) ; + spice_dstring_reinit(dstr_p); + low[1] = '\0'; + for (ptr = str; ptr && *ptr; ptr++) { + low[0] = lowcase(*ptr); + spice_dstring_append(dstr_p, low, 1); } - return 1 ; /* Dstrings expand to any length */ + return 1; /* Dstrings expand to any length */ } + bool -ccopy ( SPICE_DSTRINGPTR dstr_p, char c) /* returns success flag */ +ccopy(SPICE_DSTRINGPTR dstr_p, char c) /* returns success flag */ { - char *s_p ; /* current string */ + char *s_p; /* current string */ - sfix ( dstr_p, 1); - s_p = spice_dstring_value(dstr_p) ; - s_p[0] = c ; - return 1 ; + sfix(dstr_p, 1); + s_p = spice_dstring_value(dstr_p); + s_p[0] = c; + return 1; } + char * -pscopy (SPICE_DSTRINGPTR dstr_p, char *t, int start, int leng) +pscopy(SPICE_DSTRINGPTR dstr_p, char *t, int start, int leng) /* partial string copy, with C-based start - Because we now have a 0 based * start and string may copy outselves, we may need to restore the first * character of the original dstring because resetting string will wipe * out first character. */ { - int i; /* counter */ - int stop ; /* stop value */ - char *s_p ; /* value of dynamic string */ + int i; /* counter */ + int stop; /* stop value */ + char *s_p; /* value of dynamic string */ - stop = length(t) ; + stop = length(t); - if (start < stop) /* nothing! */ - { - if ((start + leng - 1) > stop) - { -// leng = stop - start + 1; - leng = stop - start ; + if (start < stop) { /* nothing! */ + + if ((start + leng - 1) > stop) { + // leng = stop - start + 1; + leng = stop - start; } - _spice_dstring_setlength(dstr_p,leng) ; - s_p = spice_dstring_value(dstr_p) ; + + _spice_dstring_setlength(dstr_p, leng); + s_p = spice_dstring_value(dstr_p); + for (i = 0; i < leng; i++) s_p[i] = t[start + i]; - s_p[leng] = '\0' ; + + s_p[leng] = '\0'; + + } else { + + s_p = spice_dstring_reinit(dstr_p); + } - else - { - s_p = spice_dstring_reinit(dstr_p) ; - } - return s_p ; + + return s_p; } + char * -pscopy_up (SPICE_DSTRINGPTR dstr_p, char *t, int start, int leng) +pscopy_up(SPICE_DSTRINGPTR dstr_p, char *t, int start, int leng) /* partial string copy to upper case, with C convention for start. */ { - int i; /* counter */ - int stop ; /* stop value */ - char *s_p ; /* value of dynamic string */ + int i; /* counter */ + int stop; /* stop value */ + char *s_p; /* value of dynamic string */ - stop = length(t) ; + stop = length(t); - if (start < stop) /* nothing! */ - { - if ((start + leng - 1) > stop) - { -// leng = stop - start + 1; - leng = stop - start ; + if (start < stop) { /* nothing! */ + + if ((start + leng - 1) > stop) { + // leng = stop - start + 1; + leng = stop - start; } - _spice_dstring_setlength(dstr_p,leng) ; - s_p = spice_dstring_value(dstr_p) ; + + _spice_dstring_setlength(dstr_p, leng); + s_p = spice_dstring_value(dstr_p); + for (i = 0; i < leng; i++) - s_p[i] = upcase ( t[start + i] ) ; - s_p[leng] = '\0' ; + s_p[i] = upcase(t[start + i]); + + s_p[leng] = '\0'; + + } else { + + s_p = spice_dstring_reinit(dstr_p); + } - else - { - s_p = spice_dstring_reinit(dstr_p) ; - } - return s_p ; + + return s_p; } + bool -nadd ( SPICE_DSTRINGPTR dstr_p, long n) +nadd(SPICE_DSTRINGPTR dstr_p, long n) /* append a decimal integer to a string */ { int d[25]; - int j, k ; - char sg; /* the sign */ - char load_str[2] ; /* used to load dstring */ + int j, k; + char sg; /* the sign */ + char load_str[2]; /* used to load dstring */ k = 0; - if (n < 0) - { + if (n < 0) { n = -n; sg = '-'; - } - else + } else { sg = '+'; + } - while (n > 0) - { + while (n > 0) { d[k] = n % 10; k++; n = n / 10; } - if (k == 0) - cadd (dstr_p, '0'); - else - { - load_str[1] = '\0' ; - if (sg == '-') - { - load_str[0] = sg ; - spice_dstring_append( dstr_p, load_str, 1 ) ; + if (k == 0) { + cadd(dstr_p, '0'); + } else { + load_str[1] = '\0'; + if (sg == '-') { + load_str[0] = sg; + spice_dstring_append(dstr_p, load_str, 1); } - for (j = k - 1; j >= 0; j--) - { + for (j = k - 1; j >= 0; j--) { load_str[0] = (char) ('0' + d[j]); - spice_dstring_append( dstr_p, load_str, 1 ) ; + spice_dstring_append(dstr_p, load_str, 1); } } - return 1 ; + return 1; } + bool -naddll (SPICE_DSTRINGPTR dstr_p, long long n) +naddll(SPICE_DSTRINGPTR dstr_p, long long n) /* append a decimal integer (but a long long) to a string */ { int d[25]; - int j, k ; - char sg; /* the sign */ - char load_str[2] ; /* used to load dstring */ + int j, k; + char sg; /* the sign */ + char load_str[2]; /* used to load dstring */ k = 0; - if (n < 0) - { + if (n < 0) { n = -n; sg = '-'; - } - else + } else { sg = '+'; + } - while (n > 0) - { + while (n > 0) { d[k] = (int) (n % 10); k++; n = n / 10; } - if (k == 0) - cadd (dstr_p, '0'); - else - { - load_str[1] = '\0' ; - if (sg == '-') - { - load_str[0] = sg ; - spice_dstring_append( dstr_p, load_str, 1 ) ; + if (k == 0) { + cadd(dstr_p, '0'); + } else { + load_str[1] = '\0'; + if (sg == '-') { + load_str[0] = sg; + spice_dstring_append(dstr_p, load_str, 1); } - for (j = k - 1; j >= 0; j--) - { + for (j = k - 1; j >= 0; j--) { load_str[0] = (char) ('0' + d[j]); - spice_dstring_append( dstr_p, load_str, 1 ) ; + spice_dstring_append(dstr_p, load_str, 1); } } - return 1 ; + return 1; } + void -stri (long n, SPICE_DSTRINGPTR dstr_p) +stri(long n, SPICE_DSTRINGPTR dstr_p) /* convert integer to string */ { - spice_dstring_reinit( dstr_p ) ; - nadd (dstr_p, n) ; + spice_dstring_reinit(dstr_p); + nadd(dstr_p, n); } -bool -steq (char *a, char *b) /* string a==b test */ -{ - return strcmp (a, b) == 0; -} bool -stne (char *s, char *t) +steq(char *a, char *b) /* string a==b test */ { - return strcmp (s, t) != 0; + return strcmp(a, b) == 0; } + +bool +stne(char *s, char *t) +{ + return strcmp(s, t) != 0; +} + + char -lowcase (char c) +lowcase(char c) { if ((c >= 'A') && (c <= 'Z')) return (char) (c - 'A' + 'a'); @@ -445,93 +461,102 @@ lowcase (char c) return c; } -bool -alfa (char c) -{ - return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) || c == '_' - || c == '[' || c == ']'; -} bool -num (char c) +alfa(char c) +{ + return + ((c >= 'a') && (c <= 'z')) || + ((c >= 'A') && (c <= 'Z')) || + c == '_' || c == '[' || c == ']'; +} + + +bool +num(char c) { return (c >= '0') && (c <= '9'); } + bool -alfanum (char c) +alfanum(char c) { - return alfa (c) || ((c >= '0') && (c <= '9')); + return alfa(c) || ((c >= '0') && (c <= '9')); } + int -freadstr (FILE * f, SPICE_DSTRINGPTR dstr_p) +freadstr(FILE * f, SPICE_DSTRINGPTR dstr_p) /* read a line from a file. was BUG: long lines truncated without warning, ctrl chars are dumped. Bug no more as we can only run out of memory. Removed max argument. */ { char c; - char str_load[2] ; - int len = 0 ; + char str_load[2]; + int len = 0; + + str_load[0] = '\0'; + str_load[1] = '\0'; + spice_dstring_reinit(dstr_p); - str_load[0] = '\0' ; - str_load[1] = '\0' ; - spice_dstring_reinit(dstr_p) ; do { - c = (char) fgetc (f); /* tab is the only control char accepted */ - if (((c >= ' ') || (c < 0) || (c == '\t'))) - { + c = (char) fgetc(f); /* tab is the only control char accepted */ + if (((c >= ' ') || (c < 0) || (c == '\t'))) { str_load[0] = c; - spice_dstring_append( dstr_p, str_load, 1 ) ; + spice_dstring_append(dstr_p, str_load, 1); } } - while (!feof (f) && (c != '\n')); + while (!feof(f) && (c != '\n')); - - return len ; + return len; } + char * -stupcase (char *s) +stupcase(char *s) { int i = 0; - while (s[i] != '\0') - { - s[i] = upcase (s[i]); + while (s[i] != '\0') { + s[i] = upcase(s[i]); i++; } return s; } + /***** pointer tricks: app won't use naked malloc(), free() ****/ void -dispose (void *p) +dispose(void *p) { if (p != NULL) - free (p); + free(p); } + void * -new (size_t sz) +new(size_t sz) { - void *p = tmalloc (sz); - if (p == NULL) - { /* fatal error */ - printf (" new() failure. Program halted.\n"); + void *p = tmalloc(sz); + + if (p == NULL) { /* fatal error */ + printf(" new() failure. Program halted.\n"); controlled_exit(EXIT_FAILURE); } + return p; } + /***** elementary math *******/ double -absf (double x) +absf(double x) { if (x < 0.0) return -x; @@ -539,8 +564,9 @@ absf (double x) return x; } + long -absi (long i) +absi(long i) { if (i >= 0) return (i); @@ -548,6 +574,7 @@ absi (long i) return (-i); } + int spos_(char *sub, char *s) /* equivalent to Turbo Pascal pos(). @@ -556,42 +583,46 @@ spos_(char *sub, char *s) { char *ptr; - if ((ptr = strstr (s, sub)) != NULL) - return (int) (strlen (s) - strlen (ptr)); + if ((ptr = strstr(s, sub)) != NULL) + return (int) (strlen(s) - strlen(ptr)); else - return -1 ; - + return -1; } #ifndef HAVE_LIBM long -np_round (double x) +np_round(double x) /* using , it would be simpler: floor(x+0.5), see below */ { double u; long z; int n; // Str (40, s); - SPICE_DSTRING s ; - spice_dstring_init(&s) ; + SPICE_DSTRING s; + + spice_dstring_init(&s); u = 2e9; + if (x > u) x = u; else if (x < -u) x = -u; - n = sprintf (s, "%-12.0f", x); + n = sprintf(s, "%-12.0f", x); s[n] = 0; - sscanf (s, "%ld", &z); + sscanf(s, "%ld", &z); + return z; } + long -np_trunc (double x) +np_trunc(double x) { - long n = np_round (x); + long n = np_round(x); + if ((n > x) && (x >= 0.0)) n--; else if ((n < x) && (x < 0.0)) @@ -600,21 +631,24 @@ np_trunc (double x) return n; } + #else /* use floor() and ceil() */ -long -np_round (double r) -{ - return (long) floor (r + 0.5); -} long -np_trunc (double r) +np_round(double r) +{ + return (long) floor(r + 0.5); +} + + +long +np_trunc(double r) { if (r >= 0.0) - return (long) floor (r); + return (long) floor(r); else - return (long) ceil (r); + return (long) ceil(r); } #endif diff --git a/src/frontend/numparam/numpaif.h b/src/frontend/numparam/numpaif.h index 9743910a2..e53adc09c 100644 --- a/src/frontend/numparam/numpaif.h +++ b/src/frontend/numparam/numpaif.h @@ -1,6 +1,6 @@ /* * numpaif.h - * external interface to spice frontend subckt.c + * external interface to spice frontend subckt.c */ #ifndef NUMPAIF_H @@ -11,7 +11,7 @@ #define NUPASUBDONE 2 #define NUPAEVALDONE 3 -extern char * nupa_copy(char *s, int linenum); +extern char *nupa_copy(char *s, int linenum); extern int nupa_eval(char *s, int linenum, int orig_linenum); extern int nupa_signal(int sig, char *info); extern void nupa_scan(char * s, int linenum, int is_subckt); @@ -23,4 +23,4 @@ extern void nupa_copy_inst_dico(void); extern int dynMaxckt; /* number of lines in deck after expansion */ -#endif /* NUMPAIF_H */ +#endif diff --git a/src/frontend/numparam/numparam.h b/src/frontend/numparam/numparam.h index 3218b97b8..85d9c99a2 100644 --- a/src/frontend/numparam/numparam.h +++ b/src/frontend/numparam/numparam.h @@ -1,5 +1,5 @@ /* - * numparam.h + * numparam.h */ /*** interface to spice frontend subckt.c ***/ @@ -12,62 +12,68 @@ #define ln(x) log(x) #define trunc(x) floor(x) -typedef enum {Nodekey='#'} _nNodekey; /* Introduces node symbol */ -typedef enum {Intro='&'} _nIntro; /* Introduces preprocessor tokens */ -typedef enum {Comment='*'} _nComment; /* Spice Comment lines*/ -typedef enum {Psp='{'} _nPsp; /* Ps expression */ -typedef enum {Defd=15} _nDefd; /* serial numb. of 'defined' keyword. The others are not used (yet) */ +typedef enum {Nodekey = '#'} _nNodekey; /* Introduces node symbol */ +typedef enum {Intro = '&'} _nIntro; /* Introduces preprocessor tokens */ +typedef enum {Comment = '*'} _nComment; /* Spice Comment lines */ +typedef enum {Psp = '{'} _nPsp; /* Ps expression */ +typedef enum {Defd = 15} _nDefd; /* serial numb. of 'defined' keyword. + The others are not used (yet) */ + +typedef char *auxtable; /* dummy */ -typedef char * auxtable; /* dummy */ /* ----------------------------------------------------------------- * I believe the entry should be a union of type but I need more info. * ----------------------------------------------------------------- */ + typedef struct _tentry { - char tp; /* type: I)nt R)eal S)tring F)unction M)acro P)ointer */ - char *symbol ; - int level; /* subckt nesting level */ - double vl; /* float value if defined */ - int ivl; /*int value or string buffer index*/ - char * sbbase; /* string buffer base address if any */ - struct _tentry *pointer ; /* pointer chain */ + char tp; /* type: I)nt R)eal S)tring F)unction M)acro P)ointer */ + char *symbol; + int level; /* subckt nesting level */ + double vl; /* float value if defined */ + int ivl; /* int value or string buffer index */ + char *sbbase; /* string buffer base address if any */ + struct _tentry *pointer; /* pointer chain */ } entry; + typedef struct _tfumas { /*function,macro,string*/ - unsigned start /*,stop*/ ; /*buffer index or location */ + unsigned start; /*,stop*/ /* buffer index or location */ } fumas; -typedef struct _ttdico { -/* the input scanner data structure */ - SPICE_DSTRING srcfile; /* last piece of source file name */ - SPICE_DSTRING option; /* one-character translator options */ - SPICE_DSTRING lookup_buf ; /* useful temp buffer for quick symbol lookup */ - int srcline; - int oldline; - int errcount; - int symbol_stack_alloc ; /* stack allocation */ - int stack_depth ; /* current depth of the symbol stack */ - NGHASHPTR global_symbols ; /* hash table of globally defined symbols for quick lookup */ - NGHASHPTR *local_symbols ; /* stack of locally defined symbols */ - NGHASHPTR inst_symbols ; /* instance qualified symbols - after a pop */ - char **inst_name ; /* name of subcircuit */ - fumas fms[101]; - int nfms; /* number of functions & macros */ - auxtable nodetab; - char **dynrefptr; - char *dyncategory; - int hs_compatibility; /* allow extra keywords */ + +typedef struct _ttdico { /* the input scanner data structure */ + SPICE_DSTRING srcfile; /* last piece of source file name */ + SPICE_DSTRING option; /* one-character translator options */ + SPICE_DSTRING lookup_buf; /* useful temp buffer for quick symbol lookup */ + int srcline; + int oldline; + int errcount; + int symbol_stack_alloc; /* stack allocation */ + int stack_depth; /* current depth of the symbol stack */ + NGHASHPTR global_symbols; /* hash table of globally defined symbols + for quick lookup */ + NGHASHPTR *local_symbols; /* stack of locally defined symbols */ + NGHASHPTR inst_symbols; /* instance qualified symbols - after a pop */ + char **inst_name; /* name of subcircuit */ + fumas fms[101]; + int nfms; /* number of functions & macros */ + auxtable nodetab; + char **dynrefptr; + char *dyncategory; + int hs_compatibility; /* allow extra keywords */ } tdico; -void initdico(tdico * dico); -int donedico(tdico * dico); -void dico_free_entry( entry *entry_p ) ; -bool defsubckt( tdico *dico, char * s, int w, char categ); -int findsubckt( tdico *dico, char * s, SPICE_DSTRINGPTR subname); -bool nupa_substitute( tdico *dico, char * s, char * r, bool err); -bool nupa_assignment( tdico *dico, char * s, char mode); -bool nupa_subcktcall( tdico *dico, char * s, char * x, bool err); -void nupa_subcktexit( tdico *dico); -tdico * nupa_fetchinstance(void); -char getidtype( tdico *d, char * s); -entry *attrib( tdico *d, NGHASHPTR htable, char * t, char op ); + +void initdico(tdico *dico); +int donedico(tdico *dico); +void dico_free_entry(entry *entry_p); +bool defsubckt(tdico *dico, char *s, int w, char categ); +int findsubckt(tdico *dico, char *s, SPICE_DSTRINGPTR subname); +bool nupa_substitute(tdico *dico, char *s, char *r, bool err); +bool nupa_assignment(tdico *dico, char *s, char mode); +bool nupa_subcktcall(tdico *dico, char *s, char *x, bool err); +void nupa_subcktexit(tdico *dico); +tdico *nupa_fetchinstance(void); +char getidtype(tdico *d, char *s); +entry *attrib(tdico *d, NGHASHPTR htable, char *t, char op); diff --git a/src/frontend/numparam/spicenum.c b/src/frontend/numparam/spicenum.c index c7631fe2b..58f488414 100644 --- a/src/frontend/numparam/spicenum.c +++ b/src/frontend/numparam/spicenum.c @@ -29,6 +29,7 @@ Todo: #include "ngspice/fteext.h" /* controlled_exit() */ + void dump_symbols(tdico *dico_p); char *nupa_inst_name; @@ -44,20 +45,20 @@ extern int dynmaxline; /* inpcom.c:1529 */ /* the nupa_signal arguments sent from Spice: - sig=1: Start of the subckt expansion. - sig=2: Stop of the subckt expansion. - sig=3: Stop of the evaluation phase. - sig=0: Start of a deck copy operation + sig=1: Start of the subckt expansion. + sig=2: Stop of the subckt expansion. + sig=3: Stop of the evaluation phase. + sig=0: Start of a deck copy operation - After sig=1 until sig=2, nupa_copy does no transformations. - At sig=2, we prepare for nupa_eval loop. - After sig=3, we assume the initial state (clean). + After sig=1 until sig=2, nupa_copy does no transformations. + At sig=2, we prepare for nupa_eval loop. + After sig=3, we assume the initial state (clean). - In Clean state, a lot of deckcopy operations come in and we - overwrite any line pointers, or we start a new set after each sig=0 ? - Anyway, we neutralize all & and .param lines (category[] array!) - and we substitute all {} &() and &id placeholders by dummy identifiers. - those look like numparm__XXXXXXXX (8 hexadecimal digits) + In Clean state, a lot of deckcopy operations come in and we + overwrite any line pointers, or we start a new set after each sig=0 ? + Anyway, we neutralize all & and .param lines (category[] array!) + and we substitute all {} &() and &id placeholders by dummy identifiers. + those look like numparm__XXXXXXXX (8 hexadecimal digits) */ /********** string handling ***********/ @@ -66,132 +67,136 @@ static long placeholder = 0; static void -stripsomespace (SPICE_DSTRINGPTR dstr_p, unsigned char incontrol) +stripsomespace(SPICE_DSTRINGPTR dstr_p, unsigned char incontrol) { /* if s starts with one of some markers, strip leading space */ int i, ls; - char *sstr ; /* string contained in s */ - SPICE_DSTRING markers ; + char *sstr; /* string contained in s */ + SPICE_DSTRING markers; - spice_dstring_init( &markers ) ; - scopys( &markers, "*.&+#$") ; + spice_dstring_init(&markers); + scopys(&markers, "*.&+#$"); if (!incontrol) - sadd ( &markers, "xX"); + sadd(&markers, "xX"); + + sstr = spice_dstring_value(dstr_p); + ls = spice_dstring_length(dstr_p); - sstr = spice_dstring_value(dstr_p) ; - ls = spice_dstring_length (dstr_p); i = 0; while ((i < ls) && (sstr[i] <= ' ')) i++; - if ((i > 0) && (i < ls) && (cpos (sstr[i], spice_dstring_value(&markers)) >= 0)) - pscopy (dstr_p, sstr, i, ls); - + if ((i > 0) && (i < ls) && (cpos(sstr[i], spice_dstring_value(&markers)) >= 0)) + pscopy(dstr_p, sstr, i, ls); } + static int -stripbraces (SPICE_DSTRINGPTR dstr_p) +stripbraces(SPICE_DSTRINGPTR dstr_p) /* puts the funny placeholders. returns the number of {...} substitutions */ { int n, i, nest, ls, j; - char *s ; /* value of dynamic string */ - char *t_p ; /* value of t dynamic string */ - SPICE_DSTRING tstr ; /* temporary dynamic string */ + char *s; /* value of dynamic string */ + char *t_p; /* value of t dynamic string */ + SPICE_DSTRING tstr; /* temporary dynamic string */ n = 0; - spice_dstring_init( &tstr ) ; - s = spice_dstring_value( dstr_p ) ; - ls = spice_dstring_length (dstr_p); + spice_dstring_init(&tstr); + s = spice_dstring_value(dstr_p); + ls = spice_dstring_length(dstr_p); i = 0; - while (i < ls) - { - if (s[i] == '{') - { + while (i < ls) { + + if (s[i] == '{') { + /* something to strip */ j = i + 1; nest = 1; n++; - while ((nest > 0) && (j < ls)) - { + while ((nest > 0) && (j < ls)) { if (s[j] == '{') nest++; else if (s[j] == '}') nest--; j++; } - pscopy (&tstr, s, 0, i); + + pscopy(&tstr, s, 0, i); placeholder++; - t_p = spice_dstring_value(&tstr) ; + t_p = spice_dstring_value(&tstr); if (t_p[i - 1] > ' ') - cadd (&tstr, ' '); + cadd(&tstr, ' '); - cadd ( &tstr, ' '); + cadd(&tstr, ' '); { char buf[17+1]; sprintf(buf, "numparm__%08lx", placeholder); - sadd( &tstr, buf ); + sadd(&tstr, buf); } - cadd ( &tstr, ' '); + cadd(&tstr, ' '); if (s[j] >= ' ') - cadd ( &tstr, ' '); + cadd(&tstr, ' '); + + i = spice_dstring_length(&tstr); + pscopy(dstr_p, s, j, ls); + sadd(&tstr, s); + scopyd(dstr_p, &tstr); + s = spice_dstring_value(dstr_p); + ls = spice_dstring_length(dstr_p); + + } else { - i = spice_dstring_length (&tstr); - pscopy (dstr_p, s, j, ls); - sadd ( &tstr, s); - scopyd ( dstr_p, &tstr); - s = spice_dstring_value( dstr_p ) ; - ls = spice_dstring_length( dstr_p ) ; - } - else i++; + } } + dynsubst = placeholder; spice_dstring_free(&tstr); + return n; } + static int -findsubname (tdico * dico, SPICE_DSTRINGPTR dstr_p) +findsubname(tdico *dico, SPICE_DSTRINGPTR dstr_p) /* truncate the parameterized subckt call to regular old Spice */ /* scan a string from the end, skipping non-idents and {expressions} */ /* then truncate s after the last subckt(?) identifier */ { - SPICE_DSTRING name ; /* extract a name */ - char *s ; /* current dstring */ + SPICE_DSTRING name; /* extract a name */ + char *s; /* current dstring */ int h, j, k, nest, ls; - int found ; + int found; + h = 0; - ls = spice_dstring_length (dstr_p) ; - s = spice_dstring_value (dstr_p) ; - k = ls - 1 ; /* now a C - string */ + ls = spice_dstring_length(dstr_p); + s = spice_dstring_value(dstr_p); + k = ls - 1; /* now a C - string */ found = 0; - spice_dstring_init( &name ) ; + spice_dstring_init(&name); + + while ((k >= 0) && (!found)) { - while ((k >= 0) && (!found)) - { /* skip space, then non-space */ while ((k >= 0) && (s[k] <= ' ')) k--; - h = k + 1; /* at h: space */ - while ((k >= 0) && (s[k] > ' ')) - { + h = k + 1; /* at h: space */ + while ((k >= 0) && (s[k] > ' ')) { - if (s[k] == '}') - { + if (s[k] == '}') { nest = 1; k--; - while ((nest > 0) && (k >= 0)) - { + while ((nest > 0) && (k >= 0)) { if (s[k] == '{') nest--; else if (s[k] == '}') @@ -199,95 +204,88 @@ findsubname (tdico * dico, SPICE_DSTRINGPTR dstr_p) k--; } - h = k + 1; /* h points to '{' */ ; - } - else + h = k + 1; /* h points to '{' */ + + } else { k--; + } } - found = (k >= 0) && alfanum (s[k + 1]); /* suppose an identifier */ - if (found) - { + found = (k >= 0) && alfanum(s[k + 1]); /* suppose an identifier */ + if (found) { /* check for known subckt name */ - spice_dstring_reinit( &name ) ; + spice_dstring_reinit(&name); j = k + 1; - while (alfanum (s[j])) - { - cadd ( &name, upcase (s[j])); + while (alfanum(s[j])) { + cadd(&name, upcase(s[j])); j++; } - found = (getidtype (dico, spice_dstring_value(&name) ) == 'U'); + found = (getidtype(dico, spice_dstring_value(&name)) == 'U'); } } + if (found && (h < ls)) - pscopy (dstr_p, s, 0, h); + pscopy(dstr_p, s, 0, h); return h; } + static void -modernizeex (SPICE_DSTRINGPTR dstr_p) +modernizeex(SPICE_DSTRINGPTR dstr_p) /* old style expressions &(..) and &id --> new style with braces. */ { int i, state, ls; char c, d; - char *s ; /* current string */ - SPICE_DSTRING t ; /* temporary dyna string */ + char *s; /* current string */ + SPICE_DSTRING t; /* temporary dyna string */ i = 0; state = 0; - ls = spice_dstring_length (dstr_p); - s = spice_dstring_value( dstr_p ) ; - spice_dstring_init( &t ) ; + ls = spice_dstring_length(dstr_p); + s = spice_dstring_value(dstr_p); + spice_dstring_init(&t); - - while (i < ls) - { + while (i < ls) { c = s[i]; d = s[i + 1]; - if ((!state) && (c == Intro) && (i > 0)) - { - if (d == '(') - { + if ((!state) && (c == Intro) && (i > 0)) { + if (d == '(') { state = 1; i++; c = '{'; - } - else if (alfa (d)) - { - cadd (&t, '{'); + } else if (alfa(d)) { + cadd(&t, '{'); i++; - while (alfanum (s[i])) - { - cadd (&t, s[i]); + while (alfanum(s[i])) { + cadd(&t, s[i]); i++; } c = '}'; i--; } - } - else if (state) - { + } else if (state) { if (c == '(') state++; else if (c == ')') state--; - if (!state) /* replace--) by terminator */ + if (!state) /* replace--) by terminator */ c = '}'; - } - cadd (&t, c); + cadd(&t, c); i++; } - scopyd (dstr_p, &t); - spice_dstring_free(&t) ; + + scopyd(dstr_p, &t); + spice_dstring_free(&t); } + static char -transform (tdico * dico, SPICE_DSTRINGPTR dstr_p, unsigned char nostripping, - SPICE_DSTRINGPTR u_p) +transform(tdico *dico, SPICE_DSTRINGPTR dstr_p, unsigned char nostripping, + SPICE_DSTRINGPTR u_p) /* line s is categorized and crippled down to basic Spice * returns in u control word following dot, if any * @@ -313,88 +311,77 @@ transform (tdico * dico, SPICE_DSTRINGPTR dstr_p, unsigned char nostripping, */ { int k, a, n; - char *s ; /* dstring value of dstr_p */ - char *t ; /* dstring value of tstr */ + char *s; /* dstring value of dstr_p */ + char *t; /* dstring value of tstr */ char category; - SPICE_DSTRING tstr ; /* temporary string */ + SPICE_DSTRING tstr; /* temporary string */ - spice_dstring_init(&tstr) ; - spice_dstring_reinit(u_p) ; - stripsomespace (dstr_p, nostripping); - modernizeex (dstr_p); /* required for stripbraces count */ + spice_dstring_init(&tstr); + spice_dstring_reinit(u_p); + stripsomespace(dstr_p, nostripping); + modernizeex(dstr_p); /* required for stripbraces count */ - s = spice_dstring_value(dstr_p) ; - if (s[0] == '.') - { + s = spice_dstring_value(dstr_p); + + if (s[0] == '.') { /* check PS parameter format */ - scopy_up (&tstr, spice_dstring_value(dstr_p) ) ; + scopy_up(&tstr, spice_dstring_value(dstr_p)); k = 1; - t = spice_dstring_value(&tstr) ; - while (t[k] > ' ') - { - cadd (u_p, t[k]); + t = spice_dstring_value(&tstr); + while (t[k] > ' ') { + cadd(u_p, t[k]); k++; } - if (ci_prefix (".PARAM", t) == 1) - { + if (ci_prefix(".PARAM", t) == 1) { /* comment it out */ - /*s[0]='*'; */ + /* s[0] = '*'; */ category = 'P'; - } - else if (ci_prefix (".SUBCKT", t) == 1) - { + } else if (ci_prefix(".SUBCKT", t) == 1) { /* split off any "params" tail */ - a = spos_ ("PARAMS:", t); + a = spos_("PARAMS:", t); if (a >= 0) - pscopy (dstr_p, s, 0, a ); + pscopy(dstr_p, s, 0, a); category = 'S'; - } - else if (ci_prefix (".CONTROL", t) == 1) + } else if (ci_prefix(".CONTROL", t) == 1) { category = 'C'; - else if (ci_prefix (".ENDC", t) == 1) + } else if (ci_prefix(".ENDC", t) == 1) { category = 'E'; - else if (ci_prefix (".ENDS", t) == 1) + } else if (ci_prefix(".ENDS", t) == 1) { category = 'U'; - else - { + } else { category = '.'; - n = stripbraces (dstr_p); + n = stripbraces(dstr_p); if (n > 0) - category = 'B'; /* priority category ! */ + category = 'B'; /* priority category ! */ } - } - else if (s[0] == Intro) - { + } else if (s[0] == Intro) { /* private style preprocessor line */ s[0] = '*'; category = 'P'; - } - else if (upcase (s[0]) == 'X') - { + } else if (upcase(s[0]) == 'X') { /* strip actual parameters */ - findsubname (dico, dstr_p) ;/* i= index following last identifier in s */ + findsubname(dico, dstr_p); /* i= index following last identifier in s */ category = 'X'; - } - else if (s[0] == '+') /* continuation line */ + } else if (s[0] == '+') { /* continuation line */ category = '+'; - else if (cpos (s[0], "*$#") < 0) - { + } else if (cpos(s[0], "*$#") < 0) { /* not a comment line! */ - n = stripbraces (dstr_p); + n = stripbraces(dstr_p); if (n > 0) - category = 'B'; /* line that uses braces */ + category = 'B'; /* line that uses braces */ else - category = ' '; /* ordinary code line */ - } - else + category = ' '; /* ordinary code line */ + } else { category = '*'; + } - spice_dstring_free(&tstr) ; + spice_dstring_free(&tstr); return category; } + /************ core of numparam **************/ /* some day, all these nasty globals will go into the tdico structure @@ -403,215 +390,219 @@ transform (tdico * dico, SPICE_DSTRINGPTR dstr_p, unsigned char nostripping, they are statics within this file for easier reading of the code. */ -static int linecountS = 0; /* global: number of lines received via nupa_copy */ -static int evalcountS = 0; /* number of lines through nupa_eval() */ -static int nblogS = 0; /* serial number of (debug) logfile */ -static unsigned char inexpansionS = 0; /* flag subckt expansion phase */ -static unsigned char incontrolS = 0; /* flag control code sections */ -static unsigned char dologfileS = 0; /* for debugging */ +static int linecountS = 0; /* global: number of lines received via nupa_copy */ +static int evalcountS = 0; /* number of lines through nupa_eval() */ +static int nblogS = 0; /* serial number of (debug) logfile */ +static unsigned char inexpansionS = 0; /* flag subckt expansion phase */ +static unsigned char incontrolS = 0; /* flag control code sections */ +static unsigned char dologfileS = 0; /* for debugging */ static unsigned char firstsignalS = 1; static FILE *logfileS = NULL; static tdico *dicoS = NULL; + /* already part of dico : */ /* - Open ouput to a log file. - takes no action if logging is disabled. - Open the log if not already open. + Open ouput to a log file. + takes no action if logging is disabled. + Open the log if not already open. */ static void -putlogfile (char c, int num, char *t) +putlogfile(char c, int num, char *t) { - SPICE_DSTRING fname ; /* file name */ - SPICE_DSTRING u ; /* temp dynamic variable */ + SPICE_DSTRING fname; /* file name */ + SPICE_DSTRING u; /* temp dynamic variable */ - spice_dstring_init( &fname ) ; - spice_dstring_init( &u ) ; - if (dologfileS) - { - if ((logfileS == NULL)) - { - scopys(&fname, "logfile.") ; + spice_dstring_init(&fname); + spice_dstring_init(&u); + + if (dologfileS) { + + if ((logfileS == NULL)) { + scopys(&fname, "logfile."); nblogS++; - nadd (&fname, nblogS) ; - logfileS = fopen ( spice_dstring_value(&fname), "w"); + nadd(&fname, nblogS); + logfileS = fopen(spice_dstring_value(&fname), "w"); } - if ((logfileS != NULL)) - { - cadd (&u, c); - nadd (&u, num); - cadd (&u, ':'); - cadd (&u, ' '); - sadd (&u, t); - cadd (&u, '\n'); - fputs ( spice_dstring_value(&u), logfileS); + if ((logfileS != NULL)) { + cadd(&u, c); + nadd(&u, num); + cadd(&u, ':'); + cadd(&u, ' '); + sadd(&u, t); + cadd(&u, '\n'); + fputs(spice_dstring_value(&u), logfileS); } + } - spice_dstring_free(&u) ; - spice_dstring_free(&fname) ; + + spice_dstring_free(&u); + spice_dstring_free(&fname); } + static void -nupa_init (char *srcfile) +nupa_init(char *srcfile) { int i; + /* init the symbol table and so on, before the first nupa_copy. */ evalcountS = 0; linecountS = 0; incontrolS = 0; placeholder = 0; - dicoS = (tdico *)new(sizeof(tdico)); - initdico (dicoS); + dicoS = (tdico *) new(sizeof(tdico)); + initdico(dicoS); dicoS->dynrefptr = TMALLOC(char*, dynmaxline + 1); dicoS->dyncategory = TMALLOC(char, dynmaxline + 1); - for (i = 0; i <= dynmaxline; i++) - { + for (i = 0; i <= dynmaxline; i++) { dicoS->dynrefptr[i] = NULL; dicoS->dyncategory[i] = '?'; } if (srcfile != NULL) - scopys(&dicoS->srcfile, srcfile ) ; + scopys(&dicoS->srcfile, srcfile); } + static void -nupa_done (void) +nupa_done(void) { /* int i; not needed so far, see below */ - char *reply ; /* user reply */ - SPICE_DSTRING rep ; /* dynamic report */ + char *reply; /* user reply */ + SPICE_DSTRING rep; /* dynamic report */ int dictsize, nerrors; - spice_dstring_init(&rep) ; - if (logfileS != NULL) - { - fclose (logfileS); + spice_dstring_init(&rep); + + if (logfileS != NULL) { + fclose(logfileS); logfileS = NULL; } + nerrors = dicoS->errcount; - dictsize = donedico (dicoS); + dictsize = donedico(dicoS); + /* We cannot remove dico here because numparam is usedby - the .measure statement, which is invoked only after the - simulation has finished */ + the .measure statement, which is invoked only after the + simulation has finished */ /* - for (i = dynmaxline ; i >= 0; i--) { - dispose (dico->dynrefptr[i]); - } - dispose (dico->dynrefptr); - dispose (dico->dyncategory); - dispose (dico->dyndat); - dispose (dico); - dico = NULL; - dispose (inst_dico->dyndat); - dispose (inst_dico); - inst_dico = NULL; + * for (i = dynmaxline; i >= 0; i--) { + * dispose(dico->dynrefptr[i]); + * } + * dispose(dico->dynrefptr); + * dispose(dico->dyncategory); + * dispose(dico->dyndat); + * dispose(dico); + * dico = NULL; + * dispose(inst_dico->dyndat); + * dispose(inst_dico); + * inst_dico = NULL; */ - if (nerrors) - { + + if (nerrors) { /* debug: ask if spice run really wanted */ - sadd (&rep, " Copies="); - nadd (&rep, linecountS); - sadd (&rep, " Evals="); - nadd (&rep, evalcountS); - sadd (&rep, " Placeholders="); - nadd (&rep, placeholder); - sadd (&rep, " Symbols="); - nadd (&rep, dictsize); - sadd (&rep, " Errors="); - nadd (&rep, nerrors); - cadd (&rep, '\n'); - printf ( "%s", spice_dstring_value(&rep) ) ; - printf ("Numparam expansion errors: Run Spice anyway? y/n ?\n"); - spice_dstring_reinit(&rep) ; - rs (&rep); - reply = spice_dstring_value(&rep) ; - if (upcase (reply[0]) != 'Y') + sadd(&rep, " Copies="); + nadd(&rep, linecountS); + sadd(&rep, " Evals="); + nadd(&rep, evalcountS); + sadd(&rep, " Placeholders="); + nadd(&rep, placeholder); + sadd(&rep, " Symbols="); + nadd(&rep, dictsize); + sadd(&rep, " Errors="); + nadd(&rep, nerrors); + cadd(&rep, '\n'); + printf("%s", spice_dstring_value(&rep)); + printf("Numparam expansion errors: Run Spice anyway? y/n ?\n"); + spice_dstring_reinit(&rep); + rs(&rep); + reply = spice_dstring_value(&rep); + if (upcase(reply[0]) != 'Y') controlled_exit(EXIT_FAILURE); } linecountS = 0; evalcountS = 0; placeholder = 0; - /* release symbol table data */ ; + /* release symbol table data */ } + /* SJB - Scan the line for subcircuits */ void -nupa_scan (char *s, int linenum, int is_subckt) +nupa_scan(char *s, int linenum, int is_subckt) { - if (is_subckt) - defsubckt (dicoS, s, linenum, 'U'); + defsubckt(dicoS, s, linenum, 'U'); else - defsubckt (dicoS, s, linenum, 'O'); - + defsubckt(dicoS, s, linenum, 'O'); } + /* ----------------------------------------------------------------- * Dump the contents of a symbol table. * ----------------------------------------------------------------- */ static void -dump_symbol_table( tdico *dico_p, NGHASHPTR htable_p, FILE * cp_out) +dump_symbol_table(tdico *dico_p, NGHASHPTR htable_p, FILE *cp_out) { - char *name; /* current symbol */ - entry *entry_p ; /* current entry */ - NGHASHITER iter ; /* hash iterator - thread safe */ + char *name; /* current symbol */ + entry *entry_p; /* current entry */ + NGHASHITER iter; /* hash iterator - thread safe */ - NGHASH_FIRST(&iter) ; - for (entry_p = (entry *) nghash_enumerateRE( htable_p,&iter) ; - entry_p ; - entry_p = (entry *) nghash_enumerateRE( htable_p,&iter)) + NGHASH_FIRST(&iter); + for (entry_p = (entry *) nghash_enumerateRE(htable_p, &iter); + entry_p; + entry_p = (entry *) nghash_enumerateRE(htable_p, &iter)) { - if (entry_p->tp == 'R') - { - spice_dstring_reinit( & dico_p->lookup_buf ) ; - scopy_lower( & dico_p->lookup_buf, entry_p->symbol ) ; - name = spice_dstring_value( & dico_p->lookup_buf ) ; - fprintf (cp_out, " ---> %s = %g\n", name, entry_p->vl) ; - spice_dstring_free( & dico_p->lookup_buf ) ; + if (entry_p->tp == 'R') { + spice_dstring_reinit(& dico_p->lookup_buf); + scopy_lower(& dico_p->lookup_buf, entry_p->symbol); + name = spice_dstring_value(& dico_p->lookup_buf); + fprintf(cp_out, " ---> %s = %g\n", name, entry_p->vl); + spice_dstring_free(& dico_p->lookup_buf); } } -} /* end dump_symbol_table() */ +} /* ----------------------------------------------------------------- * Dump the contents of the symbol table. * ----------------------------------------------------------------- */ void -nupa_list_params (FILE * cp_out) +nupa_list_params(FILE *cp_out) { - int depth ; /* nested subcircit depth */ - tdico *dico_p ; /* local copy for speed */ - NGHASHPTR htable_p ; /* current hash table */ + int depth; /* nested subcircit depth */ + tdico *dico_p; /* local copy for speed */ + NGHASHPTR htable_p; /* current hash table */ - dico_p = dicoS ; - fprintf (cp_out, "\n\n"); + dico_p = dicoS; + fprintf(cp_out, "\n\n"); /* ----------------------------------------------------------------- * Print out the locally defined symbols from highest to lowest priority. * If there are no parameters, the hash table will not be allocated as * we use lazy allocation to save memory. * ----------------------------------------------------------------- */ - for( depth = dico_p->stack_depth ; depth > 0 ; depth-- ) - { - htable_p = dico_p->local_symbols[depth] ; - if( htable_p ) - { - fprintf (cp_out, " local symbol definitions for:%s\n", dico_p->inst_name[depth]) ; - dump_symbol_table( dico_p, htable_p, cp_out ) ; + for (depth = dico_p->stack_depth; depth > 0; depth--) { + htable_p = dico_p->local_symbols[depth]; + if (htable_p) { + fprintf(cp_out, " local symbol definitions for:%s\n", dico_p->inst_name[depth]); + dump_symbol_table(dico_p, htable_p, cp_out); } } /* ----------------------------------------------------------------- * Finally dump the global symbols. * ----------------------------------------------------------------- */ - fprintf (cp_out, " global symbol definitions:\n") ; - dump_symbol_table( dico_p, dico_p->global_symbols, cp_out ) ; + fprintf(cp_out, " global symbol definitions:\n"); + dump_symbol_table(dico_p, dico_p->global_symbols, cp_out); } + /* ----------------------------------------------------------------- * Lookup a parameter value in the symbol tables. This involves * multiple lookups in various hash tables in order to get the scope @@ -621,230 +612,216 @@ nupa_list_params (FILE * cp_out) * table. * ----------------------------------------------------------------- */ double -nupa_get_param (char *param_name, int *found) +nupa_get_param(char *param_name, int *found) { - int depth ; /* nested subcircit depth */ - char *up_name; /* current parameter upper case */ - entry *entry_p ; /* current entry */ - tdico *dico_p ; /* local copy for speed */ - NGHASHPTR htable_p ; /* current hash table */ - double result = 0; /* parameter value */ + int depth; /* nested subcircit depth */ + char *up_name; /* current parameter upper case */ + entry *entry_p; /* current entry */ + tdico *dico_p; /* local copy for speed */ + NGHASHPTR htable_p; /* current hash table */ + double result = 0; /* parameter value */ - dico_p = dicoS ; - spice_dstring_reinit( & dico_p->lookup_buf ) ; - scopy_up( & dico_p->lookup_buf, param_name ) ; - up_name = spice_dstring_value( & dico_p->lookup_buf ) ; + dico_p = dicoS; + spice_dstring_reinit(& dico_p->lookup_buf); + scopy_up(& dico_p->lookup_buf, param_name); + up_name = spice_dstring_value(& dico_p->lookup_buf); *found = 0; - for( depth = dico_p->stack_depth ; depth > 0 ; depth-- ) - { - htable_p = dico_p->local_symbols[depth] ; - if( htable_p ) - { - entry_p = (entry *) nghash_find( htable_p, up_name ) ; - if( entry_p ) - { - result = entry_p->vl ; + for (depth = dico_p->stack_depth; depth > 0; depth--) { + htable_p = dico_p->local_symbols[depth]; + if (htable_p) { + entry_p = (entry *) nghash_find(htable_p, up_name); + if (entry_p) { + result = entry_p->vl; *found = 1; - break ; + break; } } } - if(!(*found)) - { + if (!(*found)) { /* No luck. Try the global table. */ - entry_p = (entry *) nghash_find( dico_p->global_symbols, up_name ) ; - if( entry_p ) - { - result = entry_p->vl ; + entry_p = (entry *) nghash_find(dico_p->global_symbols, up_name); + if (entry_p) { + result = entry_p->vl; *found = 1; } } - spice_dstring_free( & dico_p->lookup_buf ) ; + spice_dstring_free(& dico_p->lookup_buf); return result; } -void -nupa_add_param (char *param_name, double value) -{ - char *up_name; /* current parameter upper case */ - entry *entry_p ; /* current entry */ - tdico *dico_p ; /* local copy for speed */ - NGHASHPTR htable_p ; /* hash table of interest */ - dico_p = dicoS ; +void +nupa_add_param(char *param_name, double value) +{ + char *up_name; /* current parameter upper case */ + entry *entry_p; /* current entry */ + tdico *dico_p; /* local copy for speed */ + NGHASHPTR htable_p; /* hash table of interest */ + + dico_p = dicoS; /* ----------------------------------------------------------------- * We use a dynamic string here because most of the time we will * be using short names and no memory allocation will occur. * ----------------------------------------------------------------- */ - spice_dstring_reinit( & dico_p->lookup_buf ) ; - scopy_up( & dico_p->lookup_buf, param_name ) ; - up_name = spice_dstring_value( & dico_p->lookup_buf ) ; + spice_dstring_reinit(& dico_p->lookup_buf); + scopy_up(& dico_p->lookup_buf, param_name); + up_name = spice_dstring_value(& dico_p->lookup_buf); - if( dico_p->stack_depth > 0 ) - { + if (dico_p->stack_depth > 0) { /* can't be lazy anymore */ - if(!(dico_p->local_symbols[dico_p->stack_depth])) - { - dico_p->local_symbols[dico_p->stack_depth] = nghash_init( NGHASH_MIN_SIZE ) ; - } - htable_p = dico_p->local_symbols[dico_p->stack_depth] ; - } - else - { + if (!(dico_p->local_symbols[dico_p->stack_depth])) + dico_p->local_symbols[dico_p->stack_depth] = nghash_init(NGHASH_MIN_SIZE); + htable_p = dico_p->local_symbols[dico_p->stack_depth]; + } else { /* global symbol */ - htable_p = dico_p->global_symbols ; + htable_p = dico_p->global_symbols; } - entry_p = attrib ( dico_p, htable_p, up_name, 'N'); - if( entry_p ) - { + entry_p = attrib(dico_p, htable_p, up_name, 'N'); + if (entry_p) { entry_p->vl = value; entry_p->tp = 'R'; entry_p->ivl = 0; entry_p->sbbase = NULL; } - spice_dstring_free( & dico_p->lookup_buf ) ; + + spice_dstring_free(& dico_p->lookup_buf); } + void -nupa_add_inst_param (char *param_name, double value) +nupa_add_inst_param(char *param_name, double value) { - char *up_name; /* current parameter upper case */ - entry *entry_p ; /* current entry */ - tdico *dico_p ; /* local copy for speed */ + char *up_name; /* current parameter upper case */ + entry *entry_p; /* current entry */ + tdico *dico_p; /* local copy for speed */ - dico_p = dicoS ; - spice_dstring_reinit( & dico_p->lookup_buf ) ; - scopy_up( & dico_p->lookup_buf, param_name ) ; - up_name = spice_dstring_value( & dico_p->lookup_buf ) ; + dico_p = dicoS; + spice_dstring_reinit(& dico_p->lookup_buf); + scopy_up(& dico_p->lookup_buf, param_name); + up_name = spice_dstring_value(& dico_p->lookup_buf); - if(!(dico_p->inst_symbols)) - { - dico_p->inst_symbols = nghash_init( NGHASH_MIN_SIZE ) ; - } + if (!(dico_p->inst_symbols)) + dico_p->inst_symbols = nghash_init(NGHASH_MIN_SIZE); - entry_p = attrib ( dico_p, dico_p->inst_symbols, up_name, 'N'); - if( entry_p ) - { + entry_p = attrib(dico_p, dico_p->inst_symbols, up_name, 'N'); + if (entry_p) { entry_p->vl = value; entry_p->tp = 'R'; entry_p->ivl = 0; entry_p->sbbase = NULL; } - spice_dstring_free( & dico_p->lookup_buf ) ; + + spice_dstring_free(& dico_p->lookup_buf); } + /* ----------------------------------------------------------------- * This function copies any definitions in the inst_symbols hash * table which are qualified symbols and makes them available at * the global level. Afterwards, the inst_symbols table is freed. * ----------------------------------------------------------------- */ void -nupa_copy_inst_dico (void) +nupa_copy_inst_dico(void) { - entry *entry_p ; /* current entry */ - tdico *dico_p ; /* local copy for speed */ - NGHASHITER iter ; /* hash iterator - thread safe */ + entry *entry_p; /* current entry */ + tdico *dico_p; /* local copy for speed */ + NGHASHITER iter; /* hash iterator - thread safe */ - dico_p = dicoS ; - if( dico_p->inst_symbols ) - { + dico_p = dicoS; + if (dico_p->inst_symbols) { /* We we perform this operation we should be in global scope */ - if( dico_p->stack_depth > 0 ) + if (dico_p->stack_depth > 0) + fprintf(stderr, "stack depth should be zero.\n"); + + NGHASH_FIRST(&iter); + for (entry_p = (entry *) nghash_enumerateRE(dico_p->inst_symbols, &iter); + entry_p; + entry_p = (entry *) nghash_enumerateRE(dico_p->inst_symbols, &iter)) { - fprintf( stderr, "stack depth should be zero.\n" ) ; - } - NGHASH_FIRST(&iter) ; - for (entry_p = (entry *) nghash_enumerateRE(dico_p->inst_symbols,&iter ) ; - entry_p ; - entry_p = (entry *) nghash_enumerateRE(dico_p->inst_symbols,&iter)) - { - nupa_add_param ( entry_p->symbol, entry_p->vl) ; - dico_free_entry( entry_p ) ; + nupa_add_param(entry_p->symbol, entry_p->vl); + dico_free_entry(entry_p); } - nghash_free( dico_p->inst_symbols, NULL, NULL ) ; - dico_p->inst_symbols = NULL ; + nghash_free(dico_p->inst_symbols, NULL, NULL); + dico_p->inst_symbols = NULL; } } + char * -nupa_copy (char *s, int linenum) +nupa_copy(char *s, int linenum) /* returns a copy (not quite) of s in freshly allocated memory. linenum, for info only, is the source line number. origin pointer s is kept, memory is freed later in nupa_done. - must abort all Spice if malloc() fails. - :{ called for the first time sequentially for all spice deck lines. - :{ then called again for all X invocation lines, top-down for - subckts defined at the outer level, but bottom-up for local - subcircuit expansion, but has no effect in that phase. - we steal a copy of the source line pointer. - - comment-out a .param or & line - - substitute placeholders for all {..} --> 10-digit numeric values. + must abort all Spice if malloc() fails. + :{ called for the first time sequentially for all spice deck lines. + :{ then called again for all X invocation lines, top-down for + subckts defined at the outer level, but bottom-up for local + subcircuit expansion, but has no effect in that phase. + we steal a copy of the source line pointer. + - comment-out a .param or & line + - substitute placeholders for all {..} --> 10-digit numeric values. */ { char *t; int ls; char c, d; - SPICE_DSTRING u ; - SPICE_DSTRING keywd ; + SPICE_DSTRING u; + SPICE_DSTRING keywd; - spice_dstring_init(&u) ; - spice_dstring_init(&keywd) ; - ls = length (s); + spice_dstring_init(&u); + spice_dstring_init(&keywd); + ls = length(s); while ((ls > 0) && (s[ls - 1] <= ' ')) ls--; - pscopy (&u, s, 0, ls); /* strip trailing space, CrLf and so on */ + pscopy(&u, s, 0, ls); /* strip trailing space, CrLf and so on */ dicoS->srcline = linenum; - if ((!inexpansionS) && (linenum >= 0) && (linenum <= dynmaxline)) - { + if ((!inexpansionS) && (linenum >= 0) && (linenum <= dynmaxline)) { linecountS++; dicoS->dynrefptr[linenum] = s; - c = transform (dicoS, &u, incontrolS, &keywd); + c = transform(dicoS, &u, incontrolS, &keywd); if (c == 'C') incontrolS = 1; else if (c == 'E') incontrolS = 0; if (incontrolS) - c = 'C'; /* force it */ + c = 'C'; /* force it */ - d = dicoS->dyncategory[linenum]; /* warning if already some strategic line! */ + d = dicoS->dyncategory[linenum]; /* warning if already some strategic line! */ if ((d == 'P') || (d == 'S') || (d == 'X')) - fprintf (stderr, - " Numparam warning: overwriting P,S or X line (linenum == %d).\n", - linenum); + fprintf(stderr, + " Numparam warning: overwriting P,S or X line (linenum == %d).\n", + linenum); dicoS->dyncategory[linenum] = c; - } /* keep a local copy and mangle the string */ + } /* keep a local copy and mangle the string */ - ls = spice_dstring_length (&u); - t = strdup ( spice_dstring_value(&u) ); + ls = spice_dstring_length(&u); + t = strdup(spice_dstring_value(&u)); - if (t == NULL) - { - fputs ("Fatal: String malloc crash in nupa_copy()\n", stderr); + if (t == NULL) { + fputs("Fatal: String malloc crash in nupa_copy()\n", stderr); controlled_exit(EXIT_FAILURE); - } - else - { + } else { if (!inexpansionS) - { - putlogfile (dicoS->dyncategory[linenum], linenum, t); - } + putlogfile(dicoS->dyncategory[linenum], linenum, t); } - spice_dstring_free(&u) ; + + spice_dstring_free(&u); return t; } + int -nupa_eval (char *s, int linenum, int orig_linenum) +nupa_eval(char *s, int linenum, int orig_linenum) /* s points to a partially transformed line. compute variables if linenum points to a & or .param line. if ( the original is an X line, compute actual params.; @@ -852,105 +829,106 @@ nupa_eval (char *s, int linenum, int orig_linenum) All the X lines are preserved (commented out) in the expanded circuit. */ { - int idef; /* subckt definition line */ + int idef; /* subckt definition line */ char c, keep, *ptr; - SPICE_DSTRING subname ; /* dynamic string for subcircuit name */ + SPICE_DSTRING subname; /* dynamic string for subcircuit name */ bool err = 1; - spice_dstring_init(&subname) ; + spice_dstring_init(&subname); dicoS->srcline = linenum; dicoS->oldline = orig_linenum; + c = dicoS->dyncategory[linenum]; + #ifdef TRACE_NUMPARAMS - fprintf (stderr, "** SJB - in nupa_eval()\n"); - fprintf (stderr, "** SJB - processing line %3d: %s\n", linenum, s); - fprintf (stderr, "** SJB - category '%c'\n", c); -#endif /* TRACE_NUMPARAMS */ - if (c == 'P') /* evaluate parameters */ - { -// err = nupa_substitute (dico, dico->dynrefptr[linenum], s, 0); - nupa_assignment (dicoS, dicoS->dynrefptr[linenum], 'N'); - } - else if (c == 'B') /* substitute braces line */ - err = nupa_substitute (dicoS, dicoS->dynrefptr[linenum], s, 0); - else if (c == 'X') - { + fprintf(stderr, "** SJB - in nupa_eval()\n"); + fprintf(stderr, "** SJB - processing line %3d: %s\n", linenum, s); + fprintf(stderr, "** SJB - category '%c'\n", c); +#endif + + if (c == 'P') { /* evaluate parameters */ + // err = nupa_substitute(dico, dico->dynrefptr[linenum], s, 0); + nupa_assignment(dicoS, dicoS->dynrefptr[linenum], 'N'); + } else if (c == 'B') { /* substitute braces line */ + err = nupa_substitute(dicoS, dicoS->dynrefptr[linenum], s, 0); + } else if (c == 'X') { /* compute args of subcircuit, if required */ ptr = s; - while (!isspace (*ptr)) + while (!isspace(*ptr)) ptr++; keep = *ptr; *ptr = '\0'; - nupa_inst_name = strdup (s); + nupa_inst_name = strdup(s); *nupa_inst_name = 'x'; *ptr = keep; strtoupper(nupa_inst_name); - idef = findsubckt (dicoS, s, &subname); + idef = findsubckt(dicoS, s, &subname); if (idef > 0) - nupa_subcktcall (dicoS, dicoS->dynrefptr[idef], dicoS->dynrefptr[linenum], 0); + nupa_subcktcall(dicoS, dicoS->dynrefptr[idef], dicoS->dynrefptr[linenum], 0); else - putlogfile ('?', linenum, " illegal subckt call."); + putlogfile('?', linenum, " illegal subckt call."); + } else if (c == 'U') { /* release local symbols = parameters */ + nupa_subcktexit(dicoS); } - else if (c == 'U') /* release local symbols = parameters */ - nupa_subcktexit (dicoS); - putlogfile ('e', linenum, s); + putlogfile('e', linenum, s); evalcountS++; + #ifdef TRACE_NUMPARAMS - fprintf (stderr, "** SJB - leaving nupa_eval(): %s %d\n", s, err); - printf ("** SJB - --> %s\n", s); - printf ("** SJB - leaving nupa_eval()\n\n"); -#endif /* TRACE_NUMPARAMS */ + fprintf(stderr, "** SJB - leaving nupa_eval(): %s %d\n", s, err); + printf("** SJB - --> %s\n", s); + printf("** SJB - leaving nupa_eval()\n\n"); +#endif + if (err) return 0; else return 1; } + int -nupa_signal (int sig, char *info) +nupa_signal(int sig, char *info) /* warning: deckcopy may come inside a recursion ! substart no! */ /* info is context-dependent string data */ { - putlogfile ('!', sig, " Nupa Signal"); - if (sig == NUPADECKCOPY) - { - if (firstsignalS) - { - nupa_init (info); + putlogfile('!', sig, " Nupa Signal"); + + if (sig == NUPADECKCOPY) { + if (firstsignalS) { + nupa_init(info); firstsignalS = 0; } - } - else if (sig == NUPASUBSTART) + } else if (sig == NUPASUBSTART) { inexpansionS = 1; - else if (sig == NUPASUBDONE) - { + } else if (sig == NUPASUBDONE) { inexpansionS = 0; nupa_inst_name = NULL; - } - else if (sig == NUPAEVALDONE) - { - nupa_done (); + } else if (sig == NUPAEVALDONE) { + nupa_done(); firstsignalS = 1; } + return 1; } + #ifdef USING_NUPATEST /* This is use only by the nupatest program */ tdico * -nupa_fetchinstance (void) +nupa_fetchinstance(void) { return dico; } -#endif /* USING_NUPATEST */ +#endif -void dump_symbols( tdico *dico_p ) + +void dump_symbols(tdico *dico_p) { NG_IGNORE(dico_p); - fprintf (stderr, "Symbol table\n"); - nupa_list_params ( stderr ) ; + fprintf(stderr, "Symbol table\n"); + nupa_list_params(stderr); } diff --git a/src/frontend/numparam/xpressn.c b/src/frontend/numparam/xpressn.c index ce9cd0068..97de0cc42 100644 --- a/src/frontend/numparam/xpressn.c +++ b/src/frontend/numparam/xpressn.c @@ -1,8 +1,8 @@ -/* xpressn.c Copyright (C) 2002 Georg Post +/* xpressn.c Copyright (C) 2002 Georg Post This file is part of Numparam, see: readme.txt Free software under the terms of the GNU Lesser General Public License - */ +*/ #include /* for function message() only. */ #include @@ -16,6 +16,7 @@ #include "../frontend/variable.h" #include "ngspice/compatmode.h" + /* random numbers in /maths/misc/randnumb.c */ extern double gauss0(void); extern double drand(void); @@ -23,18 +24,19 @@ extern double drand(void); /************ keywords ************/ /* SJB - 150 chars is ample for this - see initkeys() */ -static SPICE_DSTRING keyS ; /* all my keywords */ -static SPICE_DSTRING fmathS ; /* all math functions */ +static SPICE_DSTRING keyS; /* all my keywords */ +static SPICE_DSTRING fmathS; /* all math functions */ -extern char *nupa_inst_name; /* see spicenum.c */ -extern long dynsubst; /* see inpcom.c */ +extern char *nupa_inst_name; /* see spicenum.c */ +extern long dynsubst; /* see inpcom.c */ #define MAX_STRING_INSERT 17 /* max. string length to be inserted and replaced */ #define ACT_CHARACTS 17 /* actual string length to be inserted and replaced */ #define EXP_LENGTH 5 + static double -ternary_fcn (int conditional, double if_value, double else_value) +ternary_fcn(int conditional, double if_value, double else_value) { if (conditional) return if_value; @@ -44,54 +46,60 @@ ternary_fcn (int conditional, double if_value, double else_value) static double -agauss (double nominal_val, double abs_variation, double sigma) +agauss(double nominal_val, double abs_variation, double sigma) { double stdvar; - stdvar=abs_variation/sigma; - return (nominal_val+stdvar*gauss0()); -} - -static double -gauss (double nominal_val, double rel_variation, double sigma) -{ - double stdvar; - stdvar=nominal_val * rel_variation / sigma; + stdvar = abs_variation / sigma; return (nominal_val + stdvar * gauss0()); } + static double -unif (double nominal_val, double rel_variation) +gauss(double nominal_val, double rel_variation, double sigma) +{ + double stdvar; + stdvar = nominal_val * rel_variation / sigma; + return (nominal_val + stdvar * gauss0()); +} + + +static double +unif(double nominal_val, double rel_variation) { return (nominal_val + nominal_val * rel_variation * drand()); } + static double -aunif (double nominal_val, double abs_variation) +aunif(double nominal_val, double abs_variation) { return (nominal_val + abs_variation * drand()); } + static double -limit (double nominal_val, double abs_variation) +limit(double nominal_val, double abs_variation) { return (nominal_val + (drand() > 0 ? abs_variation : -1. * abs_variation)); } + static void -initkeys (void) +initkeys(void) /* the list of reserved words */ { - spice_dstring_init(&keyS) ; - scopy_up (&keyS, - "and or not div mod if else end while macro funct defined" - " include for to downto is var"); - scopy_up (&fmathS, - "sqr sqrt sin cos exp ln arctan abs pow pwr max min int log sinh cosh" - " tanh ternary_fcn v agauss sgn gauss unif aunif limit ceil floor"); + spice_dstring_init(&keyS); + scopy_up(&keyS, + "and or not div mod if else end while macro funct defined" + " include for to downto is var"); + scopy_up(&fmathS, + "sqr sqrt sin cos exp ln arctan abs pow pwr max min int log sinh cosh" + " tanh ternary_fcn v agauss sgn gauss unif aunif limit ceil floor"); } + static double -mathfunction (int f, double z, double x) +mathfunction(int f, double z, double x) /* the list of built-in functions. Patch 'fmath', here and near line 888 to get more ...*/ { double y; @@ -101,303 +109,301 @@ mathfunction (int f, double z, double x) y = x * x; break; case 2: - y = sqrt (x); + y = sqrt(x); break; case 3: - y = sin (x); + y = sin(x); break; case 4: - y = cos (x); + y = cos(x); break; case 5: - y = exp (x); + y = exp(x); break; case 6: - y = ln (x); + y = ln(x); break; case 7: - y = atan (x); + y = atan(x); break; case 8: - y = fabs (x); + y = fabs(x); break; case 9: - y = pow (z, x); + y = pow(z, x); break; case 10: - y = exp (x * ln (fabs (z))); + y = exp(x * ln(fabs(z))); break; case 11: - y = MAX (x, z); + y = MAX(x, z); break; case 12: - y = MIN (x, z); + y = MIN(x, z); break; case 13: - y = trunc (x); + y = trunc(x); break; case 14: - y = log (x); + y = log(x); break; case 15: - y = sinh (x); + y = sinh(x); break; case 16: - y = cosh (x); + y = cosh(x); break; case 17: - y=sinh(x)/cosh(x); + y = sinh(x)/cosh(x); break; case 21: /* sgn */ - if (x>0) y=1.; - else if (x == 0) y=0.; - else y = -1.; + if (x > 0) + y = 1.; + else if (x == 0) + y = 0.; + else + y = -1.; break; case 26: - y=ceil(x); + y = ceil(x); break; case 27: - y=floor(x); + y = floor(x); break; default: y = x; break; } + return y; } #ifdef __GNUC__ -static bool message(tdico * dic, const char *fmt, ...) +static bool message(tdico *dic, const char *fmt, ...) __attribute__ ((format (__printf__, 2, 3))); #endif static bool -message(tdico * dic, const char *fmt, ...) +message(tdico *dic, const char *fmt, ...) { va_list ap; - char *srcfile = spice_dstring_value( &(dic->srcfile) ) ; + char *srcfile = spice_dstring_value(&(dic->srcfile)); if (srcfile && *srcfile) fprintf(stderr, "%s:", srcfile); if (dic->srcline >= 0) fprintf - ( stderr, - "Original line no.: %d, new internal line no.: %d:\n", - dic->oldline, - dic->srcline - ); + (stderr, + "Original line no.: %d, new internal line no.: %d:\n", + dic->oldline, dic->srcline); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); - fprintf(stderr,"\n"); + fprintf(stderr, "\n"); dic->errcount++; - return 1 /* error! */ ; + return 1; /* error! */ } /************ the input text symbol table (dictionary) *************/ void -initdico (tdico * dico) +initdico(tdico *dico) { - int asize ; /* default allocation size */ + int asize; /* default allocation size */ COMPATMODE_T compat_mode; - spice_dstring_init( &(dico->option) ) ; - spice_dstring_init( &(dico->srcfile) ) ; + spice_dstring_init(&(dico->option)); + spice_dstring_init(&(dico->srcfile)); dico->srcline = -1; dico->errcount = 0; - dico->global_symbols = nghash_init( NGHASH_MIN_SIZE ) ; - nghash_unique( dico->global_symbols, TRUE ) ; /* no rewrite of global symbols */ - spice_dstring_init( &(dico->lookup_buf) ) ; + dico->global_symbols = nghash_init(NGHASH_MIN_SIZE); + nghash_unique(dico->global_symbols, TRUE); /* no rewrite of global symbols */ + spice_dstring_init(&(dico->lookup_buf)); - dico->stack_depth = 0 ; /* top of the stack */ - asize = dico->symbol_stack_alloc = 10 ;/* expected stack depth - no longer limited */ - asize++ ; /* account for zero */ - dico->local_symbols = TMALLOC(NGHASHPTR, asize) ; - dico->inst_name = TMALLOC(char*, asize) ; - dico->inst_symbols = NULL ; /* instance qualified are lazily allocated */ + dico->stack_depth = 0; /* top of the stack */ + asize = dico->symbol_stack_alloc = 10;/* expected stack depth - no longer limited */ + asize++; /* account for zero */ + dico->local_symbols = TMALLOC(NGHASHPTR, asize); + dico->inst_name = TMALLOC(char*, asize); + dico->inst_symbols = NULL; /* instance qualified are lazily allocated */ - initkeys (); + initkeys(); - compat_mode = ngspice_compat_mode() ; + compat_mode = ngspice_compat_mode(); - if( compat_mode == COMPATMODE_HS ) - dico->hs_compatibility = 1 ; + if (compat_mode == COMPATMODE_HS) + dico->hs_compatibility = 1; else - dico->hs_compatibility = 0 ; + dico->hs_compatibility = 0; } -void dico_free_entry( entry *entry_p ) + +void +dico_free_entry(entry *entry_p) { - if( entry_p->symbol ) - txfree(entry_p->symbol ) ; + if (entry_p->symbol) + txfree(entry_p->symbol); - txfree(entry_p) ; -} /* end dico_free_entry() */ + txfree(entry_p); +} -/* local semantics for parameters inside a subckt */ -/* arguments as wll as .param expressions */ +/* local semantics for parameters inside a subckt */ +/* arguments as wll as .param expressions */ /* to do: scope semantics ? "params:" and all new symbols should have local scope inside subcircuits. redefinition of old symbols gives a warning message. */ -typedef enum {Push='u'} _nPush; -typedef enum {Pop='o'} _nPop; +typedef enum {Push = 'u'} _nPush; +typedef enum {Pop = 'o'} _nPop; + static void -dicostack (tdico * dico, char op) +dicostack(tdico *dico, char op) /* push or pop operation for nested subcircuit locals */ { - int asize ; /* allocation size */ - char *inst_name ; /* name of subcircuit instance */ - char *param_p ; /* qualified inst parameter name */ - entry *entry_p ; /* current entry */ - NGHASHPTR htable_p ; /* current hash table */ - NGHASHITER iter ; /* hash iterator - thread safe */ + int asize; /* allocation size */ + char *inst_name; /* name of subcircuit instance */ + char *param_p; /* qualified inst parameter name */ + entry *entry_p; /* current entry */ + NGHASHPTR htable_p; /* current hash table */ + NGHASHITER iter; /* hash iterator - thread safe */ - if (op == Push) - { + if (op == Push) { dico->stack_depth++; - if ( dico->stack_depth > dico->symbol_stack_alloc ) - { + if (dico->stack_depth > dico->symbol_stack_alloc) { /* Just double the stack alloc */ - dico->symbol_stack_alloc *= 2 ; - asize = dico->symbol_stack_alloc + 1 ; /* account for zero */ - dico->local_symbols = TREALLOC(NGHASHPTR, dico->local_symbols, asize) ; - dico->inst_name = TREALLOC(char*, dico->inst_name, asize) ; + dico->symbol_stack_alloc *= 2; + asize = dico->symbol_stack_alloc + 1; /* account for zero */ + dico->local_symbols = TREALLOC(NGHASHPTR, dico->local_symbols, asize); + dico->inst_name = TREALLOC(char*, dico->inst_name, asize); } /* lazy allocation - don't allocate space if we can help it */ - dico->local_symbols[dico->stack_depth] = NULL ; - dico->inst_name[dico->stack_depth] = nupa_inst_name ; - } - else if (op == Pop) - { - if (dico->stack_depth > 0) - { + dico->local_symbols[dico->stack_depth] = NULL; + dico->inst_name[dico->stack_depth] = nupa_inst_name; + } else if (op == Pop) { + if (dico->stack_depth > 0) { /* ----------------------------------------------------------------- * Keep instance parameters around by transferring current local * scope variables to an instance qualified hash table. * ----------------------------------------------------------------- */ - inst_name = dico->inst_name[dico->stack_depth] ; - htable_p = dico->local_symbols[dico->stack_depth] ; - if( htable_p ) - { - SPICE_DSTRING param_name ; /* build a qualified name */ - spice_dstring_init(¶m_name) ; + inst_name = dico->inst_name[dico->stack_depth]; + htable_p = dico->local_symbols[dico->stack_depth]; + if (htable_p) { + SPICE_DSTRING param_name; /* build a qualified name */ + spice_dstring_init(¶m_name); - NGHASH_FIRST(&iter) ; - for (entry_p = (entry *) nghash_enumerateRE( htable_p,&iter ) ; - entry_p ; - entry_p = (entry *) nghash_enumerateRE( htable_p,&iter)) + NGHASH_FIRST(&iter); + for (entry_p = (entry *) nghash_enumerateRE(htable_p, &iter); + entry_p; + entry_p = (entry *) nghash_enumerateRE(htable_p, &iter)) { - spice_dstring_reinit(¶m_name) ; - param_p = spice_dstring_print( ¶m_name, "%s.%s", - inst_name, - entry_p->symbol ) ; - nupa_add_inst_param (param_p, entry_p->vl); - dico_free_entry( entry_p ) ; + spice_dstring_reinit(¶m_name); + param_p = spice_dstring_print(¶m_name, "%s.%s", + inst_name, entry_p->symbol); + nupa_add_inst_param(param_p, entry_p->vl); + dico_free_entry(entry_p); } - nghash_free( htable_p, NULL, NULL ) ; - spice_dstring_free(¶m_name) ; + nghash_free(htable_p, NULL, NULL); + spice_dstring_free(¶m_name); } - tfree (inst_name); + tfree(inst_name); - dico->inst_name[dico->stack_depth] = NULL ; - dico->local_symbols[dico->stack_depth] = NULL ; + dico->inst_name[dico->stack_depth] = NULL; + dico->local_symbols[dico->stack_depth] = NULL; dico->stack_depth--; - } - else - { - message (dico, " Subckt Stack underflow."); + + } else { + message(dico, " Subckt Stack underflow."); } } } + int -donedico (tdico * dico) +donedico(tdico *dico) { - int sze = nghash_get_size( dico->global_symbols ) ; + int sze = nghash_get_size(dico->global_symbols); return sze; } + /* ----------------------------------------------------------------- * Now entryb works on the given hash table hierarchy. First * look thru the stack of local symbols and then look at the global * symbols in that order. * ----------------------------------------------------------------- */ static entry * -entrynb ( tdico *d, char *s) +entrynb(tdico *d, char *s) { - int depth ; /* stack depth */ - entry *entry_p ; /* search hash table */ - NGHASHPTR htable_p ; /* hash table */ + int depth; /* stack depth */ + entry *entry_p; /* search hash table */ + NGHASHPTR htable_p; /* hash table */ /* look at the current scope and then backup the stack */ - for( depth = d->stack_depth ; depth > 0 ; depth-- ) - { - htable_p = d->local_symbols[depth] ; - if( htable_p ) - { - entry_p = (entry *) nghash_find( htable_p, s ) ; - if( entry_p ) - return( entry_p ) ; + for (depth = d->stack_depth; depth > 0; depth--) { + htable_p = d->local_symbols[depth]; + if (htable_p) { + entry_p = (entry *) nghash_find(htable_p, s); + if (entry_p) + return (entry_p); } } + /* No local symbols - try the global table */ - entry_p = (entry *) nghash_find( d->global_symbols, s ) ; - return( entry_p ) ; - -} /* end entrynb() */ - -char -getidtype (tdico * d, char *s) -/* test if identifier s is known. Answer its type, or '?' if not in table */ -{ - entry *entry_p ; /* hash table entry */ - char itp = '?'; /* assume unknown */ - - entry_p = entrynb( d, s ) ; - if( entry_p ) - itp = entry_p->tp ; - - return (itp) ; + entry_p = (entry *) nghash_find(d->global_symbols, s); + return (entry_p); } + +char +getidtype(tdico *d, char *s) +/* test if identifier s is known. Answer its type, or '?' if not in table */ +{ + entry *entry_p; /* hash table entry */ + char itp = '?'; /* assume unknown */ + + entry_p = entrynb(d, s); + if (entry_p) + itp = entry_p->tp; + + return (itp); +} + + static double -fetchnumentry (tdico * dico, char *t, bool *perr) +fetchnumentry(tdico *dico, char *t, bool *perr) { bool err = *perr; double u; - entry *entry_p ; /* hash table entry */ + entry *entry_p; /* hash table entry */ - entry_p = entrynb (dico, t); /* no keyword */ - /*dbg -- if ( k<=0 ) { printf("Dico num lookup fails.") ;} */ + entry_p = entrynb(dico, t); /* no keyword */ + /*dbg -- if (k <= 0) { printf("Dico num lookup fails."); } */ - while ( entry_p && (entry_p->tp == 'P') ) - entry_p = entry_p->pointer ; + while (entry_p && (entry_p->tp == 'P')) + entry_p = entry_p->pointer; - if ( entry_p ) + if (entry_p) if (entry_p->tp != 'R') - entry_p = NULL ; + entry_p = NULL; - if ( entry_p ) - u = entry_p->vl ; - else - { - err = message (dico, "Undefined number [%s]", t); + if (entry_p) { + u = entry_p->vl; + } else { + err = message(dico, "Undefined number [%s]", t); u = 0.0; } @@ -406,167 +412,172 @@ fetchnumentry (tdico * dico, char *t, bool *perr) return u; } + /******* writing dictionary entries *********/ entry * -attrib (tdico *dico_p, NGHASHPTR htable_p, char *t, char op) +attrib(tdico *dico_p, NGHASHPTR htable_p, char *t, char op) { /* seek or attribute dico entry number for string t. Option op='N' : force a new entry, if tos>level and old is valid. */ - entry *entry_p ; /* symbol table entry */ + entry *entry_p; /* symbol table entry */ - entry_p = (entry *) nghash_find( htable_p, t ) ; - if ( entry_p && (op == 'N') - && ( entry_p->level < dico_p->stack_depth) && ( entry_p->tp != '?')) + entry_p = (entry *) nghash_find(htable_p, t); + if (entry_p && (op == 'N') && + (entry_p->level < dico_p->stack_depth) && (entry_p->tp != '?')) { - entry_p = NULL ; + entry_p = NULL; } - if (!entry_p) - { - entry_p = TMALLOC(entry, 1) ; - entry_p->symbol = strdup( t ) ; - entry_p->tp = '?'; /* signal Unknown */ - entry_p->level = dico_p->stack_depth ; - nghash_insert( htable_p, t, entry_p ) ; + if (!entry_p) { + entry_p = TMALLOC(entry, 1); + entry_p->symbol = strdup(t); + entry_p->tp = '?'; /* signal Unknown */ + entry_p->level = dico_p->stack_depth; + nghash_insert(htable_p, t, entry_p); } - return entry_p ; + + return entry_p; } + static bool -define (tdico * dico, - char *t, /* identifier to define */ - char op, /* option */ - char tpe, /* type marker */ - double z, /* float value if any */ - int w, /* integer value if any */ - entry *pval, /* pointer value if any */ - char *base) /* string pointer if any */ +define(tdico *dico, + char *t, /* identifier to define */ + char op, /* option */ + char tpe, /* type marker */ + double z, /* float value if any */ + int w, /* integer value if any */ + entry *pval, /* pointer value if any */ + char *base) /* string pointer if any */ { /*define t as real or integer, opcode= 'N' impose a new item under local conditions. check for pointers, too, in full macrolanguage version: - Call with 'N','P',0.0, ksymbol ... for VAR parameter passing. + Call with 'N','P',0.0, ksymbol ... for VAR parameter passing. Overwrite warning, beware: During 1st pass (macro definition), - we already make symbol entries which are dummy globals ! - we mark each id with its subckt level, and warn if write at higher one. + we already make symbol entries which are dummy globals ! + we mark each id with its subckt level, and warn if write at higher one. */ char c; bool err, warn; - entry *entry_p ; /* spice table entry */ - NGHASHPTR htable_p ; /* hash table */ + entry *entry_p; /* spice table entry */ + NGHASHPTR htable_p; /* hash table */ NG_IGNORE(pval); - if( dico->stack_depth > 0 ) - { + if (dico->stack_depth > 0) { /* can't be lazy anymore */ - if(!(dico->local_symbols[dico->stack_depth])) - dico->local_symbols[dico->stack_depth] = nghash_init( NGHASH_MIN_SIZE ) ; + if (!(dico->local_symbols[dico->stack_depth])) + dico->local_symbols[dico->stack_depth] = nghash_init(NGHASH_MIN_SIZE); - htable_p = dico->local_symbols[dico->stack_depth] ; - } - else - { + htable_p = dico->local_symbols[dico->stack_depth]; + } else { /* global symbol */ - htable_p = dico->global_symbols ; + htable_p = dico->global_symbols; } - entry_p = attrib (dico, htable_p, t, op); + + entry_p = attrib(dico, htable_p, t, op); err = 0; - if (!entry_p) - err = message (dico, " Symbol table overflow"); - else - { - if ( entry_p->tp == 'P') - entry_p = entry_p->pointer ; /* pointer indirection */ + + if (!entry_p) { + + err = message(dico, " Symbol table overflow"); + + } else { + + if (entry_p->tp == 'P') + entry_p = entry_p->pointer; /* pointer indirection */ if (entry_p) - c = entry_p->tp ; + c = entry_p->tp; else c = ' '; - if ((c == 'R') || (c == 'S') || (c == '?')) - { + if ((c == 'R') || (c == 'S') || (c == '?')) { + entry_p->vl = z; entry_p->tp = tpe; - entry_p->ivl = w ; - entry_p->sbbase = base ; - /* if ( (c !='?') && (i<= dico->stack[dico->tos]) ) { */ + entry_p->ivl = w; + entry_p->sbbase = base; + /* if ((c != '?') && (i <= dico->stack[dico->tos])) { */ if (c == '?') - entry_p->level = dico->stack_depth ; /* promote! */ + entry_p->level = dico->stack_depth; /* promote! */ - if ( entry_p->level < dico->stack_depth) - { - /* warn about re-write to a global scope! */ - warn = message (dico, "%s:%d overwritten.", t, entry_p->level); - } - } - else - { + /* warn about re-write to a global scope! */ + if (entry_p->level < dico->stack_depth) + warn = message(dico, "%s:%d overwritten.", t, entry_p->level); + + } else { /* suppress error message, resulting from multiple definition of - symbols (devices) in .model lines with same name, but in different subcircuits. - Subcircuit expansion is o.k., we have to deal with this numparam - behaviour later. (H. Vogt 090426) + symbols (devices) in .model lines with same name, but in different subcircuits. + Subcircuit expansion is o.k., we have to deal with this numparam + behaviour later. (H. Vogt 090426) */ - if(0) - message (dico, "%s: cannot redefine", t); + if (0) + message(dico, "%s: cannot redefine", t); } } + return err; } + bool -defsubckt (tdico * dico, char *s, int w, char categ) +defsubckt(tdico *dico, char *s, int w, char categ) /* called on 1st pass of spice source code, to enter subcircuit (categ=U) and model (categ=O) names */ { bool err; int i, j, ls; - ls = length (s); + + ls = length(s); i = 0; while ((i < ls) && (s[i] != '.')) - i++; /* skip 1st dotword */ + i++; /* skip 1st dotword */ while ((i < ls) && (s[i] > ' ')) i++; while ((i < ls) && (s[i] <= ' ')) - i++; /* skip blank */ + i++; /* skip blank */ j = i; while ((j < ls) && (s[j] > ' ')) j++; - if (j > i) - { - SPICE_DSTRING ustr ; /* temp user string */ - spice_dstring_init(&ustr) ; - pscopy_up ( &ustr, s, i, j - i) ; - err = define (dico, spice_dstring_value(&ustr), ' ', categ, 0.0, w, NULL, NULL); - spice_dstring_free(&ustr) ; + if (j > i) { + SPICE_DSTRING ustr; /* temp user string */ + spice_dstring_init(&ustr); + pscopy_up(&ustr, s, i, j - i); + err = define(dico, spice_dstring_value(&ustr), ' ', categ, 0.0, w, NULL, NULL); + spice_dstring_free(&ustr); + } else { + err = message(dico, "Subcircuit or Model without name."); } - else - err = message (dico, "Subcircuit or Model without name."); return err; } + int -findsubckt (tdico * dico, char *s, SPICE_DSTRINGPTR subname) +findsubckt(tdico *dico, char *s, SPICE_DSTRINGPTR subname) /* input: s is a subcircuit invocation line. returns 0 if not found, else the stored definition line number value and the name in string subname */ { - entry *entry_p ; /* symbol table entry */ - SPICE_DSTRING ustr ; /* u= subckt name is last token in string s */ + entry *entry_p; /* symbol table entry */ + SPICE_DSTRING ustr; /* u= subckt name is last token in string s */ int j, k; - int line ; /* stored line number */ - spice_dstring_init(&ustr) ; - k = length (s); + int line; /* stored line number */ + + spice_dstring_init(&ustr); + + k = length(s); while ((k >= 0) && (s[k] <= ' ')) k--; @@ -576,28 +587,26 @@ findsubckt (tdico * dico, char *s, SPICE_DSTRINGPTR subname) while ((k >= 0) && (s[k] > ' ')) k--; - pscopy_up ( &ustr, s, k + 1, j - k) ; - entry_p = entrynb (dico, spice_dstring_value(&ustr) ) ; + pscopy_up(&ustr, s, k + 1, j - k); + entry_p = entrynb(dico, spice_dstring_value(&ustr)); - if (entry_p && (entry_p->tp == 'U')) - { + if (entry_p && (entry_p->tp == 'U')) { line = entry_p->ivl; - scopyd ( subname, &ustr ) ; - } - else - { + scopyd(subname, &ustr); + } else { line = 0; spice_dstring_reinit(subname); - message (dico, "Cannot find subcircuit."); + message(dico, "Cannot find subcircuit."); } - return line ; + return line; } -#if 0 /* unused, from the full macro language... */ + +#if 0 /* unused, from the full macro language... */ static int -deffuma ( /* define function or macro entry. */ - tdico * dico, char *t, char tpe, unsigned short bufstart, +deffuma( /* define function or macro entry. */ + tdico *dico, char *t, char tpe, unsigned short bufstart, unsigned char *pjumped, bool *perr) { unsigned char jumped = *pjumped; @@ -606,53 +615,53 @@ deffuma ( /* define function or macro entry. */ if jumped, return index to existing function */ int i, j; - Strbig (Llen, v); - i = attrib (dico, t, ' '); + + Strbig(Llen, v); + + i = attrib(dico, t, ' '); j = 0; - if (i <= 0) - { - err = message (dico, " Symbol table overflow"); - } - else - { - if (dico->dat[i].tp != '?') - { + + if (i <= 0) { + err = message(dico, " Symbol table overflow"); + } else { + if (dico->dat[i].tp != '?') { /* old item! */ if (jumped) j = dico->dat[i].ivl; else - err = message (dico, "%s already defined", t); - } - else - { + err = message(dico, "%s already defined", t); + } else { dico->dat[i].tp = tpe; dico->nfms++; j = dico->nfms; dico->dat[i].ivl = j; dico->fms[j].start = bufstart; - /* =ibf->bufaddr = start addr in buffer */ ; + /* = ibf->bufaddr = start addr in buffer */ } } + *pjumped = jumped; *perr = err; return j; } #endif + /************ input scanner stuff **************/ static unsigned char -keyword ( SPICE_DSTRINGPTR keys_p, SPICE_DSTRINGPTR tstr_p) +keyword(SPICE_DSTRINGPTR keys_p, SPICE_DSTRINGPTR tstr_p) { /* return 0 if t not found in list keys, else the ordinal number */ unsigned char i, j, k; int lt, lk; bool ok; - char *t ; - char *keys ; - lt = spice_dstring_length(tstr_p) ; - t = spice_dstring_value(tstr_p) ; - lk = spice_dstring_length (keys_p); + char *t; + char *keys; + + lt = spice_dstring_length(tstr_p); + t = spice_dstring_value(tstr_p); + lk = spice_dstring_length(keys_p); keys = spice_dstring_value(keys_p); k = 0; j = 0; @@ -668,8 +677,7 @@ keyword ( SPICE_DSTRINGPTR keys_p, SPICE_DSTRINGPTR tstr_p) i++; k++; ok = (k <= lk) && (t[i - 1] == keys[k - 1]); - } - while (ok && (i < lt)); + } while (ok && (i < lt)); if (ok) ok = (k == lk) || (keys[k] <= ' '); @@ -677,8 +685,7 @@ keyword ( SPICE_DSTRINGPTR keys_p, SPICE_DSTRINGPTR tstr_p) if (!ok && (k < lk)) /* skip to next item */ while ((k <= lk) && (keys[k - 1] > ' ')) k++; - } - while (!ok && (k < lk)); + } while (!ok && (k < lk)); if (ok) return j; @@ -686,39 +693,41 @@ keyword ( SPICE_DSTRINGPTR keys_p, SPICE_DSTRINGPTR tstr_p) return 0; } + static double -parseunit (char *s) +parseunit(char *s) /* the Spice suffixes */ { - switch(toupper(s[0])) + switch (toupper(s[0])) { - case 'G': return 1e9; - case 'K': return 1e3; - case 'M': return ci_prefix("MEG", s) ? 1e6 : 1e-3; - case 'U': return 1e-6; - case 'N': return 1e-9; - case 'P': return 1e-12; - case 'F': return 1e-15; - default : return 1; + case 'G': return 1e9; + case 'K': return 1e3; + case 'M': return ci_prefix("MEG", s) ? 1e6 : 1e-3; + case 'U': return 1e-6; + case 'N': return 1e-9; + case 'P': return 1e-12; + case 'F': return 1e-15; + default : return 1; } } + static int -fetchid (char *s, SPICE_DSTRINGPTR t, int ls, int i) +fetchid(char *s, SPICE_DSTRINGPTR t, int ls, int i) /* copy next identifier from s into t, advance and return scan index i */ { char c; bool ok; + c = s[i - 1]; - while (!alfa (c) && (i < ls)) - { + while (!alfa(c) && (i < ls)) { i++; c = s[i - 1]; } - spice_dstring_reinit(t) ; - cadd (t, upcase (c)); + spice_dstring_reinit(t); + cadd(t, upcase(c)); do { @@ -728,19 +737,20 @@ fetchid (char *s, SPICE_DSTRINGPTR t, int ls, int i) else c = '\0'; - c = upcase (c); - ok = alfanum (c) || c == '.'; + c = upcase(c); + ok = alfanum(c) || c == '.'; if (ok) - cadd (t, c); + cadd(t, c); - } - while (ok); - return i /* return updated i */ ; + } while (ok); + + return i; /* return updated i */ } + static double -exists (tdico * d, char *s, int *pi, bool *perror) +exists(tdico *d, char *s, int *pi, bool *perror) /* check if s in simboltable 'defined': expect (ident) and return 0 or 1 */ { bool error = *perror; @@ -749,10 +759,10 @@ exists (tdico * d, char *s, int *pi, bool *perror) int ls; char c; bool ok; - SPICE_DSTRING t ; + SPICE_DSTRING t; - ls = length (s); - spice_dstring_init(&t) ; + ls = length(s); + spice_dstring_init(&t); x = 0.0; do @@ -764,12 +774,12 @@ exists (tdico * d, char *s, int *pi, bool *perror) c = s[i - 1]; ok = (c == '('); - } - while (!ok && (c != '\0')); + + } while (!ok && (c != '\0')); if (ok) { - i = fetchid (s, &t, ls, i); + i = fetchid(s, &t, ls, i); i--; if (entrynb(d, spice_dstring_value(&t))) x = 1.0; @@ -784,22 +794,25 @@ exists (tdico * d, char *s, int *pi, bool *perror) c = s[i - 1]; ok = (c == ')'); - } - while (!ok && (c != '\0')); + + } while (!ok && (c != '\0')); } + if (!ok) - error = message (d, " Defined() syntax"); + error = message(d, " Defined() syntax"); /* keep pointer on last closing ")" */ *perror = error; *pi = i; - spice_dstring_free(&t) ; + spice_dstring_free(&t); + return x; } + static double -fetchnumber (tdico * dico, char *s, int *pi, bool *perror) +fetchnumber(tdico *dico, char *s, int *pi, bool *perror) /* parse a Spice number in string s */ { double u; @@ -807,15 +820,15 @@ fetchnumber (tdico * dico, char *s, int *pi, bool *perror) s += *pi - 1; /* broken semantic !! */ - if(1 != sscanf(s, "%lG%n", &u, &n)) { + if (1 != sscanf(s, "%lG%n", &u, &n)) { - *perror = message (dico, "Number format error: \"%s\"", s) ; + *perror = message(dico, "Number format error: \"%s\"", s); return 0.0; /* FIXME return NaN */ } - u *= parseunit (s + n); + u *= parseunit(s + n); /* swallow unit * FIXME `100MegBaz42' should emit an error message @@ -826,15 +839,17 @@ fetchnumber (tdico * dico, char *s, int *pi, bool *perror) n++; *pi += n-1; /* very broken semantic !!! */ + return u; } + static char -fetchoperator (tdico * dico, - char *s, int ls, - int *pi, - unsigned char *pstate, unsigned char *plevel, - bool *perror) +fetchoperator(tdico *dico, + char *s, int ls, + int *pi, + unsigned char *pstate, unsigned char *plevel, + bool *perror) /* grab an operator from string s and advance scan index pi. each operator has: one-char alias, precedence level, new interpreter state. */ @@ -844,6 +859,7 @@ fetchoperator (tdico * dico, unsigned char level = *plevel; bool error = *perror; char c, d; + c = s[i - 1]; if (i < ls) @@ -851,104 +867,77 @@ fetchoperator (tdico * dico, else d = '\0'; - if ((c == '!') && (d == '=')) - { + if ((c == '!') && (d == '=')) { c = '#'; i++; - } - else if ((c == '<') && (d == '>')) - { + } else if ((c == '<') && (d == '>')) { c = '#'; i++; - } - else if ((c == '<') && (d == '=')) - { + } else if ((c == '<') && (d == '=')) { c = 'L'; i++; - } - else if ((c == '>') && (d == '=')) - { + } else if ((c == '>') && (d == '=')) { c = 'G'; i++; - } - else if ((c == '*') && (d == '*')) - { + } else if ((c == '*') && (d == '*')) { c = '^'; i++; - } - else if ((c == '=') && (d == '=')) - { + } else if ((c == '=') && (d == '=')) { i++; - } - else if ((c == '&') && (d == '&')) - { + } else if ((c == '&') && (d == '&')) { i++; - } - else if ((c == '|') && (d == '|')) - { + } else if ((c == '|') && (d == '|')) { i++; - } - if ((c == '+') || (c == '-')) - { - state = 2; /* pending operator */ + } if ((c == '+') || (c == '-')) { + state = 2; /* pending operator */ level = 4; - } - else if ((c == '*') || (c == '/') || (c == '%') || (c == '\\')) - { + } else if ((c == '*') || (c == '/') || (c == '%') || (c == '\\')) { state = 2; level = 3; - } - else if (c == '^') - { + } else if (c == '^') { state = 2; level = 2; - } - else if (cpos (c, "=<>#GL") >= 0) - { + } else if (cpos(c, "=<>#GL") >= 0) { state = 2; level = 5; - } - else if (c == '&') - { + } else if (c == '&') { state = 2; level = 6; - } - else if (c == '|') - { + } else if (c == '|') { state = 2; level = 7; - } - else if (c == '!') - { + } else if (c == '!') { state = 3; - } - else - { + } else { state = 0; if (c > ' ') - error = message (dico, "Syntax error: letter [%c]", c); + error = message(dico, "Syntax error: letter [%c]", c); } + *pi = i; *pstate = state; *plevel = level; *perror = error; + return c; } + static char -opfunctkey (tdico * dico, - unsigned char kw, char c, - unsigned char *pstate, unsigned char *plevel, - bool *perror) +opfunctkey(tdico *dico, + unsigned char kw, char c, + unsigned char *pstate, unsigned char *plevel, + bool *perror) /* handle operator and built-in keywords */ { unsigned char state = *pstate; unsigned char level = *plevel; bool error = *perror; + /*if kw operator keyword, c=token*/ switch (kw) { - /* & | ~ DIV MOD Defined */ + /* & | ~ DIV MOD Defined */ case 1: c = '&'; state = 2; @@ -981,18 +970,20 @@ opfunctkey (tdico * dico, break; default: state = 0; - error = message (dico, " Unexpected Keyword"); + error = message(dico, " Unexpected Keyword"); break; - } /* case */ + } *pstate = state; *plevel = level; *perror = error; + return c; } + static double -operate (char op, double x, double y) +operate(char op, double x, double y) { /* execute operator op on a pair of reals */ /* bug: x:=x op y or simply x:=y for empty op? No error signalling! */ @@ -1000,10 +991,11 @@ operate (char op, double x, double y) double z = 0.0; double epsi = 1e-30; double t; + switch (op) { case ' ': - x = y; /* problem here: do type conversions ?! */ ; + x = y; /* problem here: do type conversions ?! */ break; case '+': x = x + y; @@ -1015,23 +1007,23 @@ operate (char op, double x, double y) x = x * y; break; case '/': -// if (absf (y) > epsi) + // if (absf(y) > epsi) x = x / y; break; - case '^': /* power */ - t = absf (x); + case '^': /* power */ + t = absf(x); if (t < epsi) x = z; else - x = exp (y * ln (t)); + x = exp(y * ln(t)); break; - case '&': /* && */ + case '&': /* && */ if (y < x) - x = y; /*=Min*/ ; + x = y; /*=Min*/ break; - case '|': /* || */ + case '|': /* || */ if (y > x) - x = y; /*=Max*/ ; + x = y; /*=Max*/ break; case '=': if (x == y) @@ -1039,7 +1031,7 @@ operate (char op, double x, double y) else x = z; break; - case '#': /* <> */ + case '#': /* <> */ if (x != y) x = u; else @@ -1057,48 +1049,50 @@ operate (char op, double x, double y) else x = z; break; - case 'G': /* >= */ + case 'G': /* >= */ if (x >= y) x = u; else x = z; break; - case 'L': /* <= */ + case 'L': /* <= */ if (x <= y) x = u; else x = z; break; - case '!': /* ! */ + case '!': /* ! */ if (y == z) x = u; else x = z; break; - case '%': /* % */ - t = np_trunc (x / y); + case '%': /* % */ + t = np_trunc(x / y); x = x - y * t; break; - case '\\': /* / */ - x = np_trunc (absf (x / y)); + case '\\': /* / */ + x = np_trunc(absf(x / y)); break; - } /* case */ + } + return x; } + static double -formula (tdico * dico, char *s, bool *perror) +formula(tdico *dico, char *s, bool *perror) { /* Expression parser. - s is a formula with parentheses and math ops +-* / ... - State machine and an array of accumulators handle operator precedence. - Parentheses handled by recursion. - Empty expression is forbidden: must find at least 1 atom. - Syntax error if no toggle between binoperator && (unop/state1) ! - States : 1=atom, 2=binOp, 3=unOp, 4= stop-codon. - Allowed transitions: 1->2->(3,1) and 3->(3,1). + s is a formula with parentheses and math ops +-* / ... + State machine and an array of accumulators handle operator precedence. + Parentheses handled by recursion. + Empty expression is forbidden: must find at least 1 atom. + Syntax error if no toggle between binoperator && (unop/state1) ! + States : 1=atom, 2=binOp, 3=unOp, 4= stop-codon. + Allowed transitions: 1->2->(3,1) and 3->(3,1). */ - typedef enum {nprece=9} _nnprece; /* maximal nb of precedence levels */ + typedef enum {nprece = 9} _nnprece; /* maximal nb of precedence levels */ bool error = *perror; bool negate = 0; unsigned char state, oldstate, topop, ustack, level, kw, fu; @@ -1109,19 +1103,20 @@ formula (tdico * dico, char *s, bool *perror) int i, k, ls, natom, arg2, arg3; char c, d; bool ok; - SPICE_DSTRING tstr ; + SPICE_DSTRING tstr; - spice_dstring_init(&tstr) ; - for (i = 0; i <= nprece; i++) - { + spice_dstring_init(&tstr); + + for (i = 0; i <= nprece; i++) { accu[i] = 0.0; oper[i] = ' '; } + i = 0; - ls = length (s); + ls = length(s); while ((ls > 0) && (s[ls - 1] <= ' ')) - ls--; /* clean s */ + ls--; /* clean s */ state = 0; natom = 0; @@ -1132,12 +1127,10 @@ formula (tdico * dico, char *s, bool *perror) error = 0; level = 0; - while ((i < ls) && !error) - { + while ((i < ls) && !error) { i++; c = s[i - 1]; - if (c == '(') - { + if (c == '(') { /* sub-formula or math function */ level = 1; /* new: must support multi-arg functions */ @@ -1159,191 +1152,202 @@ formula (tdico * dico, char *s, bool *perror) else if (d == ')') level--; - if ((d == ',') && (level == 1)) - { + if ((d == ',') && (level == 1)) { if (arg2 == 0) arg2 = k; else - arg3 = k; /* kludge for more than 2 args (ternary expression) */ - } /* comma list? */ ; - } - while ((k <= ls) && !((d == ')') && (level <= 0))); + arg3 = k; /* kludge for more than 2 args (ternary expression) */ + } /* comma list? */ - if (k > ls) - { - error = message (dico, "Closing \")\" not found."); - natom++; /* shut up other error message */ ; - } - else - { - if (arg2 > i) - { - pscopy (&tstr, s, i, arg2 - i - 1); - v = formula (dico, spice_dstring_value(&tstr), &error); + } while ((k <= ls) && !((d == ')') && (level <= 0))); + + if (k > ls) { + error = message(dico, "Closing \")\" not found."); + natom++; /* shut up other error message */ + } else { + if (arg2 > i) { + pscopy(&tstr, s, i, arg2 - i - 1); + v = formula(dico, spice_dstring_value(&tstr), &error); i = arg2; } - if (arg3 > i) - { - pscopy (&tstr, s, i, arg3 - i - 1); - w = formula (dico, spice_dstring_value(&tstr), &error); + if (arg3 > i) { + pscopy(&tstr, s, i, arg3 - i - 1); + w = formula(dico, spice_dstring_value(&tstr), &error); i = arg3; } - pscopy (&tstr, s, i, k - i - 1); - u = formula (dico, spice_dstring_value(&tstr), &error); - state = 1; /* atom */ - if (fu > 0) - { + pscopy(&tstr, s, i, k - i - 1); + u = formula(dico, spice_dstring_value(&tstr), &error); + state = 1; /* atom */ + if (fu > 0) { if ((fu == 18)) - u = ternary_fcn ((int) v, w, u); + u = ternary_fcn((int) v, w, u); else if ((fu == 20)) - u = agauss (v, w, u); + u = agauss(v, w, u); else if ((fu == 22)) - u = gauss (v, w, u); + u = gauss(v, w, u); else if ((fu == 23)) - u = unif (v, u); + u = unif(v, u); else if ((fu == 24)) - u = aunif (v, u); + u = aunif(v, u); else if ((fu == 25)) - u = limit (v, u); + u = limit(v, u); else - u = mathfunction (fu, v, u); + u = mathfunction(fu, v, u); } } i = k; fu = 0; - } - else if (alfa (c)) - { - i = fetchid (s, &tstr, ls, i); /* user id, but sort out keywords */ + } else if (alfa(c)) { + i = fetchid(s, &tstr, ls, i); /* user id, but sort out keywords */ state = 1; i--; - kw = keyword (&keyS, &tstr); /* debug ws('[',kw,']'); */ - if (kw == 0) - { - fu = keyword (&fmathS, &tstr); /* numeric function? */ + kw = keyword(&keyS, &tstr); /* debug ws('[',kw,']'); */ + if (kw == 0) { + fu = keyword(&fmathS, &tstr); /* numeric function? */ if (fu == 0) - u = fetchnumentry (dico, spice_dstring_value(&tstr), &error); + u = fetchnumentry(dico, spice_dstring_value(&tstr), &error); else - state = 0; /* state==0 means: ignore for the moment */ + state = 0; /* state==0 means: ignore for the moment */ + } else { + c = opfunctkey(dico, kw, c, &state, &level, &error); } - else - c = opfunctkey (dico, kw, c, &state, &level, &error); if (kw == Defd) - u = exists (dico, s, &i, &error); - } - else if (((c == '.') || ((c >= '0') && (c <= '9')))) - { - u = fetchnumber (dico, s, &i, &error); - if (negate) - { + u = exists(dico, s, &i, &error); + } else if (((c == '.') || ((c >= '0') && (c <= '9')))) { + u = fetchnumber(dico, s, &i, &error); + if (negate) { u = -1 * u; negate = 0; } state = 1; + } else { + c = fetchoperator(dico, s, ls, &i, &state, &level, &error); } - else - c = fetchoperator (dico, s, ls, &i, &state, &level, &error); + /* may change c to some other operator char! */ /* control chars <' ' ignored */ ok = (oldstate == 0) || (state == 0) || - ((oldstate == 1) && (state == 2)) || ((oldstate != 1) - && (state != 2)); - if (oldstate == 2 && state == 2 && c == '-') - { + ((oldstate == 1) && (state == 2)) || + ((oldstate != 1) && (state != 2)); + + if (oldstate == 2 && state == 2 && c == '-') { ok = 1; negate = 1; continue; } if (!ok) - error = message (dico, " Misplaced operator"); + error = message(dico, " Misplaced operator"); - if (state == 3) - { + if (state == 3) { /* push unary operator */ ustack++; uop[ustack] = c; - } - else if (state == 1) - { + } else if (state == 1) { /* atom pending */ natom++; - if (i >= ls) - { + if (i >= ls) { state = 4; level = topop; - } /* close all ops below */ + } /* close all ops below */ + for (k = ustack; k >= 1; k--) - u = operate (uop[k], u, u); + u = operate(uop[k], u, u); ustack = 0; - accu[0] = u; /* done: all pending unary operators */ ; + accu[0] = u; /* done: all pending unary operators */ } - if ((state == 2) || (state == 4)) - { + if ((state == 2) || (state == 4)) { /* do pending binaries of priority Upto "level" */ - for (k = 1; k <= level; k++) - { + for (k = 1; k <= level; k++) { /* not yet speed optimized! */ - accu[k] = operate (oper[k], accu[k], accu[k - 1]); + accu[k] = operate(oper[k], accu[k], accu[k - 1]); accu[k - 1] = 0.0; - oper[k] = ' '; /* reset intermediates */ ; + oper[k] = ' '; /* reset intermediates */ } oper[level] = c; if (level > topop) topop = level; } + if (state > 0) oldstate = state; - } /* while */ ; + } if ((natom == 0) || (oldstate != 4)) - error = message (dico, " Expression err: %s", s); + error = message(dico, " Expression err: %s", s); if (negate == 1) - { - error = - message (dico, - " Problem with formula eval -- wrongly determined negation!"); - } + error = message(dico, + " Problem with formula eval -- wrongly determined negation!"); *perror = error; - spice_dstring_free(&tstr) ; + spice_dstring_free(&tstr); if (error) return 1.0; else return accu[topop]; -} /* formula */ +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + static bool -evaluate (tdico * dico, SPICE_DSTRINGPTR qstr_p, char *t, unsigned char mode) +evaluate(tdico *dico, SPICE_DSTRINGPTR qstr_p, char *t, unsigned char mode) { /* transform t to result q. mode 0: expression, mode 1: simple variable */ double u = 0.0; int j, lq; - char dt/*, fmt*/; - entry *entry_p ; + char dt; + entry *entry_p; bool numeric, done, nolookup; bool err; - spice_dstring_reinit(qstr_p) ; + spice_dstring_reinit(qstr_p); numeric = 0; err = 0; - if (mode == 1) - { + if (mode == 1) { /* string? */ - stupcase (t); - entry_p = entrynb (dico, t); + stupcase(t); + entry_p = entrynb(dico, t); nolookup = !entry_p; - while (entry_p && (entry_p->tp == 'P')) - entry_p = entry_p->pointer ; /* follow pointer chain */ + + while (entry_p && (entry_p->tp == 'P')) + entry_p = entry_p->pointer; /* follow pointer chain */ /* pointer chain */ if (entry_p) @@ -1352,45 +1356,41 @@ evaluate (tdico * dico, SPICE_DSTRINGPTR qstr_p, char *t, unsigned char mode) dt = ' '; /* data type: Real or String */ - if (dt == 'R') - { + if (dt == 'R') { u = entry_p->vl; numeric = 1; - } - else if (dt == 'S') - { + } else if (dt == 'S') { /* suppose source text "..." at */ j = entry_p->ivl; lq = 0; + do { j++; lq++; dt = /* ibf->bf[j]; */ entry_p->sbbase[j]; - if (cpos ('3', spice_dstring_value(&dico->option)) <= 0) - dt = upcase (dt); /* spice-2 */ + if (cpos('3', spice_dstring_value(&dico->option)) <= 0) + dt = upcase(dt); /* spice-2 */ done = (dt == '\"') || (dt < ' ') || (lq > 99); if (!done) - cadd (qstr_p, dt); - } - while (!done); + cadd(qstr_p, dt); + + } while (!done); } if (!entry_p) - err = message (dico, - "\"%s\" not evaluated.%s", t, nolookup ? " Lookup failure." : ""); - } - else - { - u = formula (dico, t, &err); + err = message(dico, + "\"%s\" not evaluated.%s", t, + nolookup ? " Lookup failure." : ""); + } else { + u = formula(dico, t, &err); numeric = 1; } - if (numeric) - { + if (numeric) { /* we want *exactly* 17 chars, we have * sign, leading digit, '.', 'e', sign, upto 3 digits exponent * ==> 8 chars, thus we have 9 left for precision @@ -1398,7 +1398,7 @@ evaluate (tdico * dico, SPICE_DSTRINGPTR qstr_p, char *t, unsigned char mode) */ char buf[17+1]; - if(snprintf(buf, sizeof(buf), "% 17.9e", u) != 17) { + if (snprintf(buf, sizeof(buf), "% 17.9e", u) != 17) { fprintf(stderr, "ERROR: xpressn.c, %s(%d)\n", __FUNCTION__, __LINE__); controlled_exit(1); } @@ -1408,38 +1408,42 @@ evaluate (tdico * dico, SPICE_DSTRINGPTR qstr_p, char *t, unsigned char mode) return err; } + #if 0 static bool -scanline (tdico * dico, char *s, char *r, bool err) +scanline(tdico *dico, char *s, char *r, bool err) /* scan host code line s for macro substitution. r=result line */ { int i, k, ls, level, nd, nnest; bool spice3; char c, d; - Strbig (Llen, q); - Strbig (Llen, t); - Str (20, u); - spice3 = cpos ('3', dico->option) > 0; /* we had -3 on the command line */ + + Strbig(Llen, q); + Strbig(Llen, t); + Str(20, u); + spice3 = cpos('3', dico->option) > 0; /* we had -3 on the command line */ i = 0; - ls = length (s); - scopy (r, ""); + ls = length(s); + scopy(r, ""); err = 0; - pscopy (u, s, 1, 3); - if ((ls > 7) && steq (u, "**&")) - { + pscopy(u, s, 1, 3); + + if ((ls > 7) && steq(u, "**&")) { /* special Comment **&AC #... */ - pscopy (r, s, 1, 7); + pscopy(r, s, 1, 7); i = 7; } - while ((i < ls) && !err) - { + + while ((i < ls) && !err) { i++; c = s[i - 1]; - if (c == Psp) - { + + if (c == Psp) { + /* try ps expression syntax */ k = i; nnest = 1; + do { k++; @@ -1448,44 +1452,40 @@ scanline (tdico * dico, char *s, char *r, bool err) nnest++; else if (d == '}') nnest--; - } - while ((nnest != 0) && (d != '\0')); - if (d == '\0') - { - err = message (dico, "Closing \"}\" not found."); - } - else - { - pscopy (t, s, i + 1, k - i - 1); - if( dico->hs_compatibility && (strcasecmp(t,"LAST")==0) ) - { - strcpy(q,"last") ; - err=0; + + } while ((nnest != 0) && (d != '\0')); + + if (d == '\0') { + err = message(dico, "Closing \"}\" not found."); + } else { + pscopy(t, s, i + 1, k - i - 1); + if (dico->hs_compatibility && (strcasecmp(t, "LAST") == 0)) { + strcpy(q, "last"); + err = 0; + } else { + err = evaluate(dico, q, t, 0); } - else - err = evaluate (dico, q, t, 0); } + i = k; - if (!err) - { - /* insert number */ - sadd (r, q); - } + + if (!err) /* insert number */ + sadd(r, q); else - { - err = message (dico, "%s", s); - } - } - else if (c == Intro) - { - Inc (i); + err = message(dico, "%s", s); + + } else if (c == Intro) { + + Inc(i); while ((i < ls) && (s[i - 1] <= ' ')) i++; + k = i; - if (s[k - 1] == '(') - { + + if (s[k - 1] == '(') { /* sub-formula */ level = 1; + do { k++; @@ -1498,21 +1498,20 @@ scanline (tdico * dico, char *s, char *r, bool err) level++; else if (d == ')') level--; + + } while ((k <= ls) && !((d == ')') && (level <= 0))); + + if (k > ls) { + err = message(dico, "Closing \")\" not found."); + } else { + pscopy(t, s, i + 1, k - i - 1); + err = evaluate(dico, q, t, 0); } - while ((k <= ls) && !((d == ')') && (level <= 0))); - if (k > ls) - { - err = message (dico, "Closing \")\" not found."); - } - else - { - pscopy (t, s, i + 1, k - i - 1); - err = evaluate (dico, q, t, 0); - } + i = k; - } - else - { + + } else { + /* simple identifier may also be string */ do { @@ -1521,62 +1520,59 @@ scanline (tdico * dico, char *s, char *r, bool err) d = '\0'; else d = s[k - 1]; - } - while ((k <= ls) && (d > ' ')); - pscopy (t, s, i, k - i); - err = evaluate (dico, q, t, 1); + + } while ((k <= ls) && (d > ' ')); + + pscopy(t, s, i, k - i); + err = evaluate(dico, q, t, 1); i = k - 1; } - if (!err) - { - /* insert the number */ - sadd (r, q); - } - else - { - message (dico, "%s", s); - } - } - else if (c == Nodekey) - { - /* follows: a node keyword */ - do - { - i++; - } - while (s[i - 1] <= ' '); - k = i; - do - { - k++; - } - while ((k <= ls) && alfanum (s[k - 1])); - pscopy (q, s, i, k - i); - nd = parsenode (Addr (dico->nodetab), q); - if (!spice3) - { - stri (nd, q); - } /* substitute by number */ - sadd (r, q); - i = k - 1; - } - else - { - if (!spice3) - c = upcase (c); - cadd (r, c); /* c<>Intro */ ; + if (!err) /* insert the number */ + sadd(r, q); + else + message(dico, "%s", s); + + } else if (c == Nodekey) { + /* follows: a node keyword */ + + do + i++; + while (s[i - 1] <= ' '); + + k = i; + + do + k++; + while ((k <= ls) && alfanum(s[k - 1])); + + pscopy(q, s, i, k - i); + nd = parsenode(Addr(dico->nodetab), q); + + if (!spice3) + stri(nd, q); /* substitute by number */ + + sadd(r, q); + i = k - 1; + + } else { + + if (!spice3) + c = upcase(c); + + cadd(r, c); /* c<>Intro */ } - } /* while */ + } + return err; } #endif + /********* interface functions for spice3f5 extension ***********/ - static int -insertnumber (tdico * dico, int i, char *s, SPICE_DSTRINGPTR ustr_p) +insertnumber(tdico *dico, int i, char *s, SPICE_DSTRINGPTR ustr_p) /* insert u in string s in place of the next placeholder number */ { const char *u = spice_dstring_value(ustr_p); @@ -1588,7 +1584,7 @@ insertnumber (tdico * dico, int i, char *s, SPICE_DSTRINGPTR ustr_p) char *p = strstr(s+i, "numparm__"); - if( p && + if (p && (1 == sscanf(p, "numparm__%8lx%n", &id, &n)) && (n == ACT_CHARACTS) && (id > 0) && (id < dynsubst + 1) && @@ -1599,45 +1595,45 @@ insertnumber (tdico * dico, int i, char *s, SPICE_DSTRINGPTR ustr_p) } message - ( dico, - "insertnumber: fails.\n" - " s+i = \"%s\" u=\"%s\" id=%ld", - s+i, u, id ); + (dico, + "insertnumber: fails.\n" + " s+i = \"%s\" u=\"%s\" id=%ld", + s+i, u, id); /* swallow everything on failure */ return i + (int) strlen(s+i); } + bool -nupa_substitute (tdico * dico, char *s, char *r, bool err) +nupa_substitute(tdico *dico, char *s, char *r, bool err) /* s: pointer to original source line. r: pointer to result line, already heavily modified wrt s anywhere we find a 10-char numstring in r, substitute it. - bug: wont flag overflow! + bug: wont flag overflow! */ { int i, k, ls, level, nnest, ir; char c, d; - SPICE_DSTRING qstr ; /* temp result dynamic string */ - SPICE_DSTRING tstr ; /* temp dynamic string */ + SPICE_DSTRING qstr; /* temp result dynamic string */ + SPICE_DSTRING tstr; /* temp dynamic string */ - spice_dstring_init(&qstr) ; - spice_dstring_init(&tstr) ; + spice_dstring_init(&qstr); + spice_dstring_init(&tstr); i = 0; - ls = length (s); + ls = length(s); err = 0; ir = 0; - while ((i < ls) && !err) - { + while ((i < ls) && !err) { i++; c = s[i - 1]; - if (c == Psp) - { + if (c == Psp) { /* try ps expression syntax */ k = i; nnest = 1; + do { k++; @@ -1646,36 +1642,33 @@ nupa_substitute (tdico * dico, char *s, char *r, bool err) nnest++; else if (d == '}') nnest--; - } - while ((nnest != 0) && (d != '\0')); - if (d == '\0') - err = message (dico, "Closing \"}\" not found."); - else - { - pscopy (&tstr, s, i , k - i - 1); + } while ((nnest != 0) && (d != '\0')); + + if (d == '\0') { + err = message(dico, "Closing \"}\" not found."); + } else { + pscopy(&tstr, s, i , k - i - 1); /* exeption made for .meas */ - if( strcasecmp( spice_dstring_value(&tstr),"LAST")==0) - { - spice_dstring_reinit(&qstr) ; - sadd(&qstr,"last") ; - err=0; + if (strcasecmp(spice_dstring_value(&tstr), "LAST") == 0) { + spice_dstring_reinit(&qstr); + sadd(&qstr, "last"); + err = 0; + } else { + err = evaluate(dico, &qstr, spice_dstring_value(&tstr), 0); } - else - err = evaluate (dico, &qstr, spice_dstring_value(&tstr), 0); } i = k; if (!err) - ir = insertnumber (dico, ir, r, &qstr) ; + ir = insertnumber(dico, ir, r, &qstr); else - err = message (dico, "Cannot compute substitute"); - } - else if (c == Intro) - { + err = message(dico, "Cannot compute substitute"); + + } else if (c == Intro) { /* skip "&&" which may occur in B source */ - if ((i + 1 < ls) && (s[i] == Intro)) - { + + if ((i + 1 < ls) && (s[i] == Intro)) { i++; continue; } @@ -1686,10 +1679,10 @@ nupa_substitute (tdico * dico, char *s, char *r, bool err) k = i; - if (s[k - 1] == '(') - { + if (s[k - 1] == '(') { /* sub-formula */ level = 1; + do { k++; @@ -1702,21 +1695,21 @@ nupa_substitute (tdico * dico, char *s, char *r, bool err) level++; else if (d == ')') level--; - } - while ((k <= ls) && !((d == ')') && (level <= 0))); - if (k > ls) - err = message (dico, "Closing \")\" not found."); - else - { - pscopy (&tstr, s, i, k - i - 1); - err = evaluate (dico, &qstr, spice_dstring_value(&tstr), 0); + } while ((k <= ls) && !((d == ')') && (level <= 0))); + + if (k > ls) { + err = message(dico, "Closing \")\" not found."); + } else { + pscopy(&tstr, s, i, k - i - 1); + err = evaluate(dico, &qstr, spice_dstring_value(&tstr), 0); } + i = k; - } - else - { + + } else { /* simple identifier may also be string? */ + do { k++; @@ -1724,78 +1717,83 @@ nupa_substitute (tdico * dico, char *s, char *r, bool err) d = '\0'; else d = s[k - 1]; - } - while ((k <= ls) && (d > ' ')); - pscopy (&tstr, s, i-1, k - i); - err = evaluate (dico, &qstr, spice_dstring_value(&tstr), 1); + } while ((k <= ls) && (d > ' ')); + + pscopy(&tstr, s, i-1, k - i); + err = evaluate(dico, &qstr, spice_dstring_value(&tstr), 1); i = k - 1; } if (!err) - ir = insertnumber (dico, ir, r, &qstr); + ir = insertnumber(dico, ir, r, &qstr); else - message (dico, "Cannot compute &(expression)"); + message(dico, "Cannot compute &(expression)"); } } - /* while */ - spice_dstring_free(&qstr) ; - spice_dstring_free(&tstr) ; + + spice_dstring_free(&qstr); + spice_dstring_free(&tstr); + return err; } + static unsigned char -getword (char *s, SPICE_DSTRINGPTR tstr_p, int after, int *pi) +getword(char *s, SPICE_DSTRINGPTR tstr_p, int after, int *pi) /* isolate a word from s after position "after". return i= last read+1 */ { int i = *pi; int ls; unsigned char key; - char *t_p ; + char *t_p; + i = after; - ls = length (s); + ls = length(s); do i++; - while ((i < ls) && !alfa (s[i - 1])); + while ((i < ls) && !alfa(s[i - 1])); - spice_dstring_reinit(tstr_p) ; + spice_dstring_reinit(tstr_p); - while ((i <= ls) && (alfa (s[i - 1]) || num (s[i - 1]))) - { - cadd (tstr_p, upcase (s[i - 1])); + while ((i <= ls) && (alfa(s[i - 1]) || num(s[i - 1]))) { + cadd(tstr_p, upcase(s[i - 1])); i++; } - t_p = spice_dstring_value(tstr_p) ; + t_p = spice_dstring_value(tstr_p); + if (t_p[0]) - key = keyword (&keyS, tstr_p); + key = keyword(&keyS, tstr_p); else key = 0; *pi = i; + return key; } + static char -getexpress (char *s, SPICE_DSTRINGPTR tstr_p, int *pi) +getexpress(char *s, SPICE_DSTRINGPTR tstr_p, int *pi) /* returns expression-like string until next separator - Input i=position before expr, output i=just after expr, on separator. - returns tpe=='R' if ( numeric, 'S' if ( string only + Input i=position before expr, output i=just after expr, on separator. + returns tpe=='R' if (numeric, 'S' if (string only */ { int i = *pi; int ia, ls, level; char c, d, tpe; bool comment = 0; - ls = length (s); + + ls = length(s); ia = i + 1; while ((ia < ls) && (s[ia - 1] <= ' ')) - ia++; /*white space ? */ + ia++; /*white space ? */ - if (s[ia - 1] == '"') - { + if (s[ia - 1] == '"') { /* string constant */ ia++; i = ia; @@ -1808,9 +1806,8 @@ getexpress (char *s, SPICE_DSTRINGPTR tstr_p, int *pi) do i++; while ((i <= ls) && (s[i - 1] <= ' ')); - } - else - { + + } else { if (s[ia - 1] == '{') ia++; @@ -1826,8 +1823,7 @@ getexpress (char *s, SPICE_DSTRINGPTR tstr_p, int *pi) else c = s[i - 1]; - if (c == '(') - { + if (c == '(') { /* sub-formula */ level = 1; do @@ -1843,32 +1839,35 @@ getexpress (char *s, SPICE_DSTRINGPTR tstr_p, int *pi) level++; else if (d == ')') level--; - } - while ((i <= ls) && !((d == ')') && (level <= 0))); + + } while ((i <= ls) && !((d == ')') && (level <= 0))); } - /* buggy? */ if ((c == '/') || (c == '-')) + + /* buggy? */ + if ((c == '/') || (c == '-')) comment = (s[i] == c); - } - while (!((cpos (c, ",;)}") >= 0) || comment)); /* legal separators */ + + } while (!((cpos (c, ",;)}") >= 0) || comment)); /* legal separators */ tpe = 'R'; - } - pscopy (tstr_p, s, ia-1, i - ia); + pscopy(tstr_p, s, ia-1, i - ia); if (s[i - 1] == '}') i++; if (tpe == 'S') - i++; /* beyond quote */ + i++; /* beyond quote */ *pi = i; + return tpe; } + bool -nupa_assignment (tdico * dico, char *s, char mode) +nupa_assignment(tdico *dico, char *s, char mode) /* is called for all 'Param' lines of the input file. is also called for the params: section of a subckt . mode='N' define new local variable, else global... @@ -1882,18 +1881,20 @@ nupa_assignment (tdico * dico, char *s, char mode) char dtype; int wval = 0; double rval = 0.0; - char *t_p ; /* dstring contents value */ - SPICE_DSTRING tstr ; /* temporary dstring */ - SPICE_DSTRING ustr ; /* temporary dstring */ - spice_dstring_init(&tstr) ; - spice_dstring_init(&ustr) ; - ls = length (s); + char *t_p; /* dstring contents value */ + SPICE_DSTRING tstr; /* temporary dstring */ + SPICE_DSTRING ustr; /* temporary dstring */ + + spice_dstring_init(&tstr); + spice_dstring_init(&ustr); + ls = length(s); error = 0; i = 0; - j = spos_ ("//", s); /* stop before comment if any */ + j = spos_("//", s); /* stop before comment if any */ if (j >= 0) - ls = j ; + ls = j; + /* bug: doesnt work. need to revise getexpress ... !!! */ i = 0; @@ -1903,138 +1904,135 @@ nupa_assignment (tdico * dico, char *s, char mode) if (s[i] == Intro) i++; - if (s[i] == '.') - { - /* skip any dot keyword */ + if (s[i] == '.') /* skip any dot keyword */ while (s[i] > ' ') i++; - } - while ((i < ls) && !error) - { - key = getword (s, &tstr, i, &i); - t_p = spice_dstring_value(&tstr) ; + while ((i < ls) && !error) { + + key = getword(s, &tstr, i, &i); + t_p = spice_dstring_value(&tstr); if ((t_p[0] == '\0') || (key > 0)) - error = message (dico, " Identifier expected"); + error = message(dico, " Identifier expected"); - if (!error) - { + if (!error) { /* assignment expressions */ while ((i <= ls) && (s[i - 1] != '=')) i++; if (i > ls) - error = message (dico, " = sign expected ."); + error = message(dico, " = sign expected ."); - dtype = getexpress (s, &ustr, &i); + dtype = getexpress(s, &ustr, &i); - if (dtype == 'R') - { - rval = formula (dico, spice_dstring_value(&ustr), &error); - if (error) - { - message (dico, " Formula() error."); - fprintf (stderr, " %s\n", s); + if (dtype == 'R') { + rval = formula(dico, spice_dstring_value(&ustr), &error); + if (error) { + message(dico, " Formula() error."); + fprintf(stderr, " %s\n", s); } - } - else if (dtype == 'S') + } else if (dtype == 'S') { wval = i; + } - err = define (dico, spice_dstring_value(&tstr), mode /* was ' ' */ , - dtype, rval, wval, NULL, NULL); + err = define(dico, spice_dstring_value(&tstr), mode /* was ' ' */ , + dtype, rval, wval, NULL, NULL); error = error || err; } if ((i < ls) && (s[i - 1] != ';')) - error = message (dico, " ; sign expected."); + error = message(dico, " ; sign expected."); /* else - i++; */ + i++; */ } - spice_dstring_free(&tstr) ; - spice_dstring_free(&ustr) ; + + spice_dstring_free(&tstr); + spice_dstring_free(&ustr); + return error; } + bool -nupa_subcktcall (tdico * dico, char *s, char *x, bool err) +nupa_subcktcall(tdico *dico, char *s, char *x, bool err) /* s= a subckt define line, with formal params. x= a matching subckt call line, with actual params */ { int n, i, j, k, g, h, narg = 0, ls, nest; - SPICE_DSTRING subname ; - SPICE_DSTRING tstr ; - SPICE_DSTRING ustr ; - SPICE_DSTRING vstr ; - SPICE_DSTRING idlist ; - SPICE_DSTRING parsebuf ; + SPICE_DSTRING subname; + SPICE_DSTRING tstr; + SPICE_DSTRING ustr; + SPICE_DSTRING vstr; + SPICE_DSTRING idlist; + SPICE_DSTRING parsebuf; char *buf, *token; - char *t_p ; - char *u_p ; + char *t_p; + char *u_p; bool found; - spice_dstring_init(&subname) ; - spice_dstring_init(&tstr) ; - spice_dstring_init(&ustr) ; - spice_dstring_init(&vstr) ; - spice_dstring_init(&idlist) ; + + spice_dstring_init(&subname); + spice_dstring_init(&tstr); + spice_dstring_init(&ustr); + spice_dstring_init(&vstr); + spice_dstring_init(&idlist); + /* - skip over instance name -- fixes bug where instance 'x1' is - same name as subckt 'x1' - */ + skip over instance name -- fixes bug where instance 'x1' is + same name as subckt 'x1' + */ while (*x != ' ') x++; /***** first, analyze the subckt definition line */ - n = 0; /* number of parameters if any */ - ls = length (s); - j = spos_ ("//", s); + n = 0; /* number of parameters if any */ + ls = length(s); + j = spos_("//", s); if (j >= 0) - pscopy_up (&tstr, s, 0, j ); + pscopy_up(&tstr, s, 0, j); else - scopy_up (&tstr, s); + scopy_up(&tstr, s); - j = spos_ ("SUBCKT", spice_dstring_value(&tstr) ) ; + j = spos_("SUBCKT", spice_dstring_value(&tstr)); - if (j >= 0) - { - j = j + 6; /* fetch its name - skip subckt */ - t_p = spice_dstring_value(&tstr) ; + if (j >= 0) { + j = j + 6; /* fetch its name - skip subckt */ + t_p = spice_dstring_value(&tstr); while ((j < ls) && (t_p[j] <= ' ')) j++; - while (t_p[j] != ' ') - { - cadd (&subname, t_p[j]); + while (t_p[j] != ' ') { + cadd(&subname, t_p[j]); j++; } + } else { + err = message(dico, " ! a subckt line!"); } - else - err = message (dico, " ! a subckt line!"); - i = spos_ ("PARAMS:", spice_dstring_value(&tstr)); + i = spos_("PARAMS:", spice_dstring_value(&tstr)); - if (i >= 0) - { + if (i >= 0) { const char *optr, *jptr; - pscopy (&tstr, spice_dstring_value(&tstr), i + 7, spice_dstring_length (&tstr)); + pscopy(&tstr, spice_dstring_value(&tstr), i + 7, spice_dstring_length(&tstr)); /* search identifier to the left of '=' assignments */ for (optr = spice_dstring_value(&tstr); - (jptr = strchr(optr, '=')) != NULL; optr = jptr + 1) + (jptr = strchr(optr, '=')) != NULL; + optr = jptr + 1) { const char *kptr, *hptr; /* skip "==" */ - if(jptr[1] == '=') { + if (jptr[1] == '=') { jptr++; continue; } /* skip "<=" ">=" "!=" */ - if(jptr > optr && strchr("<>!", jptr[-1])) + if (jptr > optr && strchr("<>!", jptr[-1])) continue; kptr = jptr; @@ -2045,84 +2043,78 @@ nupa_subcktcall (tdico * dico, char *s, char *x, bool err) while (hptr >= optr && alfanum(*hptr)) hptr--; - if (hptr < kptr && alfa(hptr[1])) - { - while(hptr++ < kptr) - cadd (&idlist, *hptr); + if (hptr < kptr && alfa(hptr[1])) { + while (hptr++ < kptr) + cadd(&idlist, *hptr); - sadd (&idlist, "=$;"); + sadd(&idlist, "=$;"); n++; + } else { + message(dico, "identifier expected."); } - else - message (dico, "identifier expected."); } } /***** next, analyze the circuit call line */ - if (!err) - { - narg = 0; - j = spos_ ("//", x); + if (!err) { - if (j >= 0) - pscopy_up ( &tstr, x, 0, j ); - else - { - scopy_up (&tstr, x); - j = 0 ; + narg = 0; + j = spos_("//", x); + + if (j >= 0) { + pscopy_up(&tstr, x, 0, j); + } else { + scopy_up(&tstr, x); + j = 0; } - ls = spice_dstring_length (&tstr); + ls = spice_dstring_length(&tstr); - spice_dstring_init(&parsebuf) ; - scopyd(&parsebuf, &tstr) ; - buf = spice_dstring_value(&parsebuf) ; + spice_dstring_init(&parsebuf); + scopyd(&parsebuf, &tstr); + buf = spice_dstring_value(&parsebuf); found = 0; - token = strtok(buf, " "); /* a bit more exact - but not sufficient everytime */ + token = strtok(buf, " "); /* a bit more exact - but not sufficient everytime */ j = j + (int) strlen(token) + 1; if (strcmp(token, spice_dstring_value(&subname))) - { - while ((token = strtok(NULL, " ")) != NULL) - { - if (!strcmp(token, spice_dstring_value(&subname))) - { + while ((token = strtok(NULL, " ")) != NULL) { + if (!strcmp(token, spice_dstring_value(&subname))) { found = 1; break; } j = j + (int) strlen(token) + 1; } - } - spice_dstring_free(&parsebuf) ; + + spice_dstring_free(&parsebuf); /* make sure that subname followed by space */ - if (found) - { - j = j + spice_dstring_length (&subname) + 1; /* 1st position of arglist: j */ + if (found) { + j = j + spice_dstring_length(&subname) + 1; /* 1st position of arglist: j */ - t_p = spice_dstring_value(&tstr) ; + t_p = spice_dstring_value(&tstr); while ((j < ls) && ((t_p[j] <= ' ') || (t_p[j] == ','))) j++; - while (j < ls) - { + while (j < ls) { + /* try to fetch valid arguments */ k = j; - spice_dstring_reinit(&ustr) ; - if (t_p[k] == Intro) - { + spice_dstring_reinit(&ustr); + + if (t_p[k] == Intro) { + /* handle historical syntax... */ - if (alfa (t_p[k + 1])) + if (alfa(t_p[k + 1])) { k++; - else if (t_p[k + 1] == '(') - { + } else if (t_p[k + 1] == '(') { /* transform to braces... */ k++; t_p[k] = '{'; g = k; nest = 1; - while ((nest > 0) && (g < ls)) - { + + while ((nest > 0) && (g < ls)) { g++; if (t_p[g] == '(') nest++; @@ -2135,76 +2127,70 @@ nupa_subcktcall (tdico * dico, char *s, char *x, bool err) } } - if (alfanum (t_p[k]) || t_p[k] == '.') - { + if (alfanum(t_p[k]) || t_p[k] == '.') { /* number, identifier */ h = k; while (t_p[k] > ' ') k++; - - pscopy (&ustr, spice_dstring_value(&tstr), h, k - h); + pscopy(&ustr, spice_dstring_value(&tstr), h, k - h); j = k; - } - else if (t_p[k] == '{') - { - getexpress ( spice_dstring_value(&tstr), &ustr, &j); - j--; /* confusion: j was in Turbo Pascal convention */ ; - } - else - { + } else if (t_p[k] == '{') { + getexpress(spice_dstring_value(&tstr), &ustr, &j); + j--; /* confusion: j was in Turbo Pascal convention */ + } else { j++; - if (t_p[k] > ' ') - { + if (t_p[k] > ' ') { spice_dstring_append(&vstr, "Subckt call, symbol ", -1); - cadd (&vstr, t_p[k]); - sadd (&vstr, " not understood"); - message (dico, "%s", spice_dstring_value(&vstr)); + cadd(&vstr, t_p[k]); + sadd(&vstr, " not understood"); + message(dico, "%s", spice_dstring_value(&vstr)); } } - u_p = spice_dstring_value(&ustr) ; - if (u_p[0]) - { + u_p = spice_dstring_value(&ustr); + if (u_p[0]) { narg++; - k = cpos ('$', spice_dstring_value(&idlist)) ; - - if (k >= 0) - { + k = cpos('$', spice_dstring_value(&idlist)); + if (k >= 0) { /* replace dollar with expression string u */ - pscopy (&vstr, spice_dstring_value(&idlist), 0, k); - sadd ( &vstr, spice_dstring_value(&ustr)) ; - pscopy (&ustr, spice_dstring_value(&idlist), k+1, spice_dstring_length (&idlist)); - scopyd (&idlist, &vstr); - sadd (&idlist, spice_dstring_value(&ustr)); + pscopy(&vstr, spice_dstring_value(&idlist), 0, k); + sadd(&vstr, spice_dstring_value(&ustr)); + pscopy(&ustr, spice_dstring_value(&idlist), k+1, spice_dstring_length(&idlist)); + scopyd(&idlist, &vstr); + sadd(&idlist, spice_dstring_value(&ustr)); } } } + } else { + message(dico, "Cannot find called subcircuit"); } - else - message (dico, "Cannot find called subcircuit"); } - /***** finally, execute the multi-assignment line */ - dicostack (dico, Push); /* create local symbol scope */ - if (narg != n) - { - err = message ( dico, - " Mismatch: %d formal but %d actual params.\n" - "%s", - n, narg, spice_dstring_value(&idlist) ); - /* ;} else { debugwarn(dico, idlist) */ ; - } - err = nupa_assignment (dico, spice_dstring_value(&idlist), 'N'); - spice_dstring_free(&subname) ; - spice_dstring_free(&tstr) ; - spice_dstring_free(&ustr) ; - spice_dstring_free(&vstr) ; - spice_dstring_free(&idlist) ; + /***** finally, execute the multi-assignment line */ + dicostack(dico, Push); /* create local symbol scope */ + + if (narg != n) { + err = message(dico, + " Mismatch: %d formal but %d actual params.\n" + "%s", + n, narg, spice_dstring_value(&idlist)); + /* ;} else { debugwarn(dico, idlist) */ + } + + err = nupa_assignment(dico, spice_dstring_value(&idlist), 'N'); + + spice_dstring_free(&subname); + spice_dstring_free(&tstr); + spice_dstring_free(&ustr); + spice_dstring_free(&vstr); + spice_dstring_free(&idlist); + return err; } + void -nupa_subcktexit (tdico * dico) +nupa_subcktexit(tdico *dico) { - dicostack (dico, Pop); + dicostack(dico, Pop); } diff --git a/src/frontend/nutinp.c b/src/frontend/nutinp.c index b550b7925..506d670e8 100644 --- a/src/frontend/nutinp.c +++ b/src/frontend/nutinp.c @@ -33,8 +33,8 @@ inp_nutsource(FILE *fp, bool comfile, char *filename) wordlist *wl = NULL, *end = NULL; wordlist *controls = NULL; FILE *lastin, *lastout, *lasterr; - - inp_readall(fp, &deck, 0, NULL, comfile) /* still to check if . or filename instead of NULL */; + + inp_readall(fp, &deck, 0, NULL, comfile); /* still to check if . or filename instead of NULL */ if (!deck) return; @@ -49,7 +49,7 @@ inp_nutsource(FILE *fp, bool comfile, char *filename) (void) fclose(fp); /* Now save the IO context and start a new control set... After - * we are done with the source we'll put the old file descriptors + * we are done with the source we'll put the old file descriptors * back. I guess we could use a FILE stack, but since this routine * is recursive anyway... */ @@ -62,7 +62,7 @@ inp_nutsource(FILE *fp, bool comfile, char *filename) cp_pushcontrol(); - /* We should now go through the deck and execute front-end + /* We should now go through the deck and execute front-end * commands and remove them. Front-end commands are enclosed by * the lines .control and .endc, unless comfile * is TRUE, in which case every line must be a front-end command. @@ -77,19 +77,18 @@ inp_nutsource(FILE *fp, bool comfile, char *filename) if ((dd->li_line[0] == '*') && (dd->li_line[1] != '#')) continue; if (!ciprefix(".control", dd->li_line) && - !ciprefix(".endc", dd->li_line)) { + !ciprefix(".endc", dd->li_line)) { if (dd->li_line[0] == '*') (void) cp_evloop(dd->li_line + 2); else (void) cp_evloop(dd->li_line); - } + } tfree(dd->li_line); tfree(dd); - } + } } else { for (dd = deck->li_next; dd; dd = ld->li_next) { - if ((dd->li_line[0] == '*') && - (dd->li_line[1] != '#')) { + if ((dd->li_line[0] == '*') && (dd->li_line[1] != '#')) { ld = dd; continue; } @@ -105,8 +104,7 @@ inp_nutsource(FILE *fp, bool comfile, char *filename) tfree(dd->li_line); tfree(dd); if (commands) - fprintf(cp_err, - "Warning: redundant .control line\n"); + fprintf(cp_err, "Warning: redundant .control line\n"); else commands = TRUE; } else if (ciprefix(".endc", dd->li_line)) { @@ -116,8 +114,7 @@ inp_nutsource(FILE *fp, bool comfile, char *filename) if (commands) commands = FALSE; else - fprintf(cp_err, - "Warning: misplaced .endc line\n"); + fprintf(cp_err, "Warning: misplaced .endc line\n"); } else if (commands || prefix("*#", dd->li_line)) { controls = wl_cons(NULL, controls); wl = controls; @@ -138,15 +135,17 @@ inp_nutsource(FILE *fp, bool comfile, char *filename) inp_casefix(s); inp_casefix(dd->li_line); if (eq(s, ".width") || ciprefix(".four", s) || - eq(s, ".plot") || - eq(s, ".print") || - eq(s, ".save")) { + eq(s, ".plot") || + eq(s, ".print") || + eq(s, ".save")) + { wl_append_word(&wl, &end, copy(dd->li_line)); ld->li_next = dd->li_next; tfree(dd->li_line); tfree(dd); - } else + } else { ld = dd; + } } } if (deck->li_next) { @@ -154,13 +153,12 @@ inp_nutsource(FILE *fp, bool comfile, char *filename) fprintf(cp_out, "\nCircuit: %s\n\n", tt); fprintf(stderr, "\nCircuit: %s\n\n", tt); - /* Now expand subcircuit macros. Note that we have to - * fix the case before we do this but after we + /* Now expand subcircuit macros. Note that we have to + * fix the case before we do this but after we * deal with the commands. */ if (!cp_getvar("nosubckt", CP_BOOL, NULL)) - deck->li_next = inp_subcktexpand(deck-> - li_next); + deck->li_next = inp_subcktexpand(deck->li_next); deck->li_actual = realdeck; nutinp_dodeck(deck, tt, wl, FALSE, options, filename); } @@ -185,6 +183,7 @@ inp_nutsource(FILE *fp, bool comfile, char *filename) return; } + void nutcom_source(wordlist *wl) { @@ -219,8 +218,10 @@ nutcom_source(wordlist *wl) wl = wl->wl_next; } (void) fseek(fp, 0L, SEEK_SET); - } else + } else { fp = inp_pathopen(wl->wl_word, "r"); + } + if (fp == NULL) { perror(wl->wl_word); cp_interactive = TRUE; @@ -228,21 +229,26 @@ nutcom_source(wordlist *wl) } /* Don't print the title if this is a .spiceinit file. */ - if (ft_nutmeg || substring(INITSTR, owl->wl_word) - || substring(ALT_INITSTR, owl->wl_word)) + if (ft_nutmeg || + substring(INITSTR, owl->wl_word) || + substring(ALT_INITSTR, owl->wl_word)) + { inp_nutsource(fp, TRUE, tempfile ? NULL : wl->wl_word); - else + } else { inp_nutsource(fp, FALSE, tempfile ? NULL : wl->wl_word); + } + cp_interactive = inter; if (tempfile) (void) unlink(tempfile); return; } + void nutinp_source(char *file) { - static struct wordlist wl = { NULL, NULL, NULL } ; + static struct wordlist wl = { NULL, NULL, NULL }; wl.wl_word = file; nutcom_source(&wl); diff --git a/src/frontend/options.c b/src/frontend/options.c index c66f247d1..3dfc57262 100644 --- a/src/frontend/options.c +++ b/src/frontend/options.c @@ -191,8 +191,9 @@ inp_getopts(struct line *deck) deck->li_next = dd->li_next; dd->li_next = opts; opts = dd; - } else + } else { last = dd; + } } return (opts); @@ -204,7 +205,7 @@ struct line * inp_getoptsc(char *in_line, struct line *com_options) { struct line *next = NULL; - char* line; + char *line; line = TMALLOC(char, strlen(in_line) + 3); /* option -> .options */ @@ -252,8 +253,9 @@ cp_usrset(struct variable *var, bool isset) fprintf(cp_err, "Error: bad type for debug var\n"); } else if (var->va_type == CP_STRING) { setdb(var->va_string); - } else + } else { fprintf(cp_err, "Error: bad type for debug var\n"); + } #ifndef FTEDEBUG fprintf(cp_err, "Warning: %s compiled without debug messages\n", cp_program); diff --git a/src/frontend/outitf.c b/src/frontend/outitf.c index a3718ee91..b6ea62e85 100644 --- a/src/frontend/outitf.c +++ b/src/frontend/outitf.c @@ -36,7 +36,6 @@ extern char *spice_analysis_get_name(int index); extern char *spice_analysis_get_description(int index); -/* static declarations */ static int beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analName, char *refName, int refType, int numNames, char **dataNames, int dataType, bool windowed, runDesc **runp); @@ -86,7 +85,8 @@ OUTpBeginPlot(CKTcircuit *circuitPtr, JOB *analysisPtr, char *name; #ifdef PARALLEL_ARCH - if (ARCHme != 0) return(OK); + if (ARCHme != 0) + return (OK); #endif if (ft_curckt->ci_ckt == circuitPtr) @@ -109,7 +109,8 @@ OUTwBeginPlot(CKTcircuit *circuitPtr, JOB *analysisPtr, { #ifdef PARALLEL_ARCH - if (ARCHme != 0) return(OK); + if (ARCHme != 0) + return (OK); #endif return (beginPlot(analysisPtr, circuitPtr, "circuit name", @@ -133,9 +134,9 @@ beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analNam bool savealli = FALSE; char *an_name; /*to resume a run saj - *All it does is reassign the file pointer and return (requires *runp to be NULL if this is not needed) - */ - if(dataType == 666 && numNames == 666) { + *All it does is reassign the file pointer and return (requires *runp to be NULL if this is not needed) + */ + if (dataType == 666 && numNames == 666) { run = *runp; run->writeOut = ft_getOutReq(&run->fp, &run->runPlot, &run->binary, run->type, run->name); @@ -211,33 +212,28 @@ beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analNam /* Pass 1. */ if (numsaves && !saveall) { - for (i = 0; i < numsaves; i++) { - if (!savesused[i]) { - for (j = 0; j < numNames; j++) { + for (i = 0; i < numsaves; i++) + if (!savesused[i]) + for (j = 0; j < numNames; j++) if (name_eq(saves[i].name, dataNames[j])) { addDataDesc(run, dataNames[j], dataType, j); savesused[i] = TRUE; saves[i].used = 1; break; } - } - } - } } else { for (i = 0; i < numNames; i++) - if (!refName || !name_eq(dataNames[i], refName)) { - + if (!refName || !name_eq(dataNames[i], refName)) /* Save the node as long as it's an internal device node */ - if (!strstr(dataNames[i], "#internal") && - !strstr(dataNames[i], "#source") && - !strstr(dataNames[i], "#drain") && - !strstr(dataNames[i], "#collector") && - !strstr(dataNames[i], "#emitter") && - !strstr(dataNames[i], "#base")) { + !strstr(dataNames[i], "#source") && + !strstr(dataNames[i], "#drain") && + !strstr(dataNames[i], "#collector") && + !strstr(dataNames[i], "#emitter") && + !strstr(dataNames[i], "#base")) + { addDataDesc(run, dataNames[i], dataType, i); } - } } /* Pass 1 and a bit. @@ -248,11 +244,12 @@ beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analNam depind = 0; for (i = 0; i < numNames; i++) { if (strstr(dataNames[i], "#internal") || - strstr(dataNames[i], "#source") || - strstr(dataNames[i], "#drain") || - strstr(dataNames[i], "#collector") || - strstr(dataNames[i], "#emitter") || - strstr(dataNames[i], "#base")) { + strstr(dataNames[i], "#source") || + strstr(dataNames[i], "#drain") || + strstr(dataNames[i], "#collector") || + strstr(dataNames[i], "#emitter") || + strstr(dataNames[i], "#base")) + { tmpname[0] = '@'; tmpname[1] = '\0'; strncat(tmpname, dataNames[i], BSIZE_SP-1); @@ -286,8 +283,8 @@ beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analNam } if (parseSpecial(tmpname, namebuf, parambuf, depbuf)) { if (*depbuf) { - fprintf( stderr, - "Warning : unexpected dependent variable on %s\n", tmpname); + fprintf(stderr, + "Warning : unexpected dependent variable on %s\n", tmpname); } else { addSpecialDesc(run, tmpname, namebuf, parambuf, depind); } @@ -347,8 +344,9 @@ beginPlot(JOB *analysisPtr, CKTcircuit *circuitPtr, char *cktName, char *analNam } if (numNames && - ((run->numData == 1 && run->refIndex != -1) || - (run->numData == 0 && run->refIndex == -1)) ) { + ((run->numData == 1 && run->refIndex != -1) || + (run->numData == 0 && run->refIndex == -1))) + { fprintf(cp_err, "Error: no data saved for %s; analysis not run\n", spice_analysis_get_description(analysisPtr->JOBtype)); return E_NOTFOUND; @@ -451,7 +449,8 @@ OUTpData(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr) int i; #ifdef PARALLEL_ARCH - if (ARCHme != 0) return(OK); + if (ARCHme != 0) + return (OK); #endif run->pointCount++; @@ -472,8 +471,8 @@ OUTpData(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr) fileAddComplexValue(run->fp, run->binary, refValue->cValue); /* While we're looking at the reference value, print it to the screen - every quarter of a second, to give some feedback without using - too much CPU time */ + every quarter of a second, to give some feedback without using + too much CPU time */ #ifndef HAS_WINDOWS currclock = clock(); if ((currclock-lastclock) > (0.25*CLOCKS_PER_SEC)) { @@ -490,7 +489,8 @@ OUTpData(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr) #ifndef HAS_WINDOWS currclock = clock(); if ((currclock-lastclock) > (0.25*CLOCKS_PER_SEC)) { - fprintf(stderr, " Reference value : % 12.5e\r", refValue->rValue); + fprintf(stderr, " Reference value : % 12.5e\r", + refValue->rValue); lastclock = currclock; } #endif @@ -507,7 +507,7 @@ OUTpData(runDesc *plotPtr, IFvalue *refValue, IFvalue *valuePtr) #endif if (run->data[i].regular) { - if(run->data[i].type == IF_REAL) + if (run->data[i].type == IF_REAL) fileAddRealValue(run->fp, run->binary, valuePtr->v.vec.rVec [run->data[i].outIndex]); else if (run->data[i].type == IF_COMPLEX) @@ -676,7 +676,8 @@ OUTendPlot(runDesc *plotPtr) runDesc *run = plotPtr; // FIXME #ifdef PARALLEL_ARCH - if (ARCHme != 0) return(OK); + if (ARCHme != 0) + return (OK); #endif if (run->writeOut) { @@ -828,14 +829,14 @@ fileInit_pass2(runDesc *run) else type = SV_VOLTAGE; - if ( type == SV_CURRENT ) { + if (type == SV_CURRENT) { char *branch = strstr(name, "#branch"); if (branch) *branch = '\0'; fprintf(run->fp, "\t%d\ti(%s)\t%s", i, name, ft_typenames(type)); if (branch) *branch = '#'; - } else if ( type == SV_VOLTAGE ) { + } else if (type == SV_VOLTAGE) { fprintf(run->fp, "\t%d\tv(%s)\t%s", i, name, ft_typenames(type)); } else { fprintf(run->fp, "\t%d\t%s\t%s", i, name, ft_typenames(type)); @@ -968,8 +969,9 @@ plotInit(runDesc *run) if (isdigit(*dd->name)) { (void) sprintf(buf, "V(%s)", dd->name); v->v_name = copy(buf); - } else + } else { v->v_name = copy(dd->name); + } if (substring("#branch", v->v_name)) v->v_type = SV_CURRENT; else if (cieq(v->v_name, "time")) @@ -1024,6 +1026,7 @@ plotAddRealValue(dataDesc *desc, double value) v->v_compdata[v->v_length].cx_real = value; v->v_compdata[v->v_length].cx_imag = 0.0; } + v->v_length++; v->v_dims[0] = v->v_length; /* va, must be updated */ } @@ -1037,6 +1040,7 @@ plotAddComplexValue(dataDesc *desc, IFcomplex value) v->v_compdata = TREALLOC(ngcomplex_t, v->v_compdata, v->v_length + 1); v->v_compdata[v->v_length].cx_real = value.real; v->v_compdata[v->v_length].cx_imag = value.imag; + v->v_length++; v->v_dims[0] = v->v_length; /* va, must be updated */ } @@ -1070,6 +1074,7 @@ parseSpecial(char *name, char *dev, char *param, char *ind) while (*name && (*name != '[')) *s++ = *name++; *s = '\0'; + if (!*name) return TRUE; name++; @@ -1078,6 +1083,7 @@ parseSpecial(char *name, char *dev, char *param, char *ind) while (*name && (*name != ',') && (*name != ']')) *s++ = *name++; *s = '\0'; + if (*name == ']') return (!name[1] ? TRUE : FALSE); else if (!*name) @@ -1088,6 +1094,7 @@ parseSpecial(char *name, char *dev, char *param, char *ind) while (*name && (*name != ']')) *s++ = *name++; *s = '\0'; + if (*name && !name[1]) return TRUE; else diff --git a/src/frontend/outitf.h b/src/frontend/outitf.h index a4922b60d..d2787dc3e 100644 --- a/src/frontend/outitf.h +++ b/src/frontend/outitf.h @@ -10,20 +10,21 @@ typedef struct dataDesc { - char *name; /* The name of the vector. */ - int type; /* The type. */ - GRIDTYPE gtype; /* default plot scale */ - bool regular; /* Is this given to us? */ - int outIndex; /* If regular then the index. */ - char *specName; /* The device name if special. */ - char *specParamName; /* The parameter name if special. */ - int specIndex; /* For sensitivity, if special. */ + char *name; /* The name of the vector. */ + int type; /* The type. */ + GRIDTYPE gtype; /* default plot scale */ + bool regular; /* Is this given to us? */ + int outIndex; /* If regular then the index. */ + char *specName; /* The device name if special. */ + char *specParamName; /* The parameter name if special. */ + int specIndex; /* For sensitivity, if special. */ int specType; GENinstance *specFast; - int refIndex; /* The index of our ref vector. */ + int refIndex; /* The index of our ref vector. */ struct dvec *vec; } dataDesc; + struct runDesc { void *analysis; CKTcircuit *circuit; @@ -37,12 +38,13 @@ struct runDesc { bool binary; struct plot *runPlot; FILE *fp; - long pointPos; /* where to write pointCount */ + long pointPos; /* where to write pointCount */ int pointCount; int isComplex; int windowCount; }; + int OUTpBeginPlot(CKTcircuit *circuitPtr, JOB *analysisPtr, IFuid analName, IFuid refName, int refType, diff --git a/src/frontend/parse.c b/src/frontend/parse.c index 439b21943..d40b5c5b2 100644 --- a/src/frontend/parse.c +++ b/src/frontend/parse.c @@ -17,18 +17,17 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group #include "evaluate.h" #include "parse.h" -/* static declarations */ + static bool checkvalid(struct pnode *pn); -static struct pnode * mkbnode(int opnum, struct pnode *arg1, struct pnode *arg2); -static struct pnode * mkunode(int op, struct pnode *arg); -static struct pnode * mkfnode(const char *func, struct pnode *arg); -static struct pnode * mknnode(double number); -static struct pnode * mksnode(const char *string); +static struct pnode *mkbnode(int opnum, struct pnode *arg1, struct pnode *arg2); +static struct pnode *mkunode(int op, struct pnode *arg); +static struct pnode *mkfnode(const char *func, struct pnode *arg); +static struct pnode *mknnode(double number); +static struct pnode *mksnode(const char *string); #include "parse-bison.c" -char * db_print_pnode_tree(struct pnode *p, char *print); - +char *db_print_pnode_tree(struct pnode *p, char *print); struct pnode * @@ -45,11 +44,11 @@ ft_getpnames(wordlist *wl, bool check) xsbuf = sbuf = wl_flatten(wl); - rv = PPparse (&sbuf, &pn); + rv = PPparse(&sbuf, &pn); tfree(xsbuf); - if(rv) + if (rv) return (NULL); if (check && !checkvalid(pn)) @@ -68,20 +67,19 @@ checkvalid(struct pnode *pn) { while (pn) { if (pn->pn_value) { - if ((pn->pn_value->v_length == 0) && + if ((pn->pn_value->v_length == 0) && !eq(pn->pn_value->v_name, "list")) { if (eq(pn->pn_value->v_name, "all")) fprintf(cp_err, - "Error: %s: no matching vectors.\n", - pn->pn_value->v_name); + "Error: %s: no matching vectors.\n", + pn->pn_value->v_name); else fprintf(cp_err, - "Error(parse.c--checkvalid): %s: no such vector.\n", - pn->pn_value->v_name); + "Error(parse.c--checkvalid): %s: no such vector.\n", + pn->pn_value->v_name); return (FALSE); } - } else if (pn->pn_func || - (pn->pn_op && (pn->pn_op->op_arity == 1))) { + } else if (pn->pn_func || (pn->pn_op && (pn->pn_op->op_arity == 1))) { if (!checkvalid(pn->pn_left)) return (FALSE); } else if (pn->pn_op && (pn->pn_op->op_arity == 2)) { @@ -89,108 +87,109 @@ checkvalid(struct pnode *pn) return (FALSE); if (!checkvalid(pn->pn_right)) return (FALSE); - } else - fprintf(cp_err, - "checkvalid: Internal Error: bad node\n"); + } else { + fprintf(cp_err, + "checkvalid: Internal Error: bad node\n"); + } pn = pn->pn_next; } return (TRUE); } - /* Some auxiliary functions for building the parse tree. */ -static -struct op ops[] = { - { PT_OP_PLUS, "+", 2, {(void(*)(void)) op_plus} } , - { PT_OP_MINUS, "-", 2, {(void(*)(void)) op_minus} } , - { PT_OP_TIMES, "*", 2, {(void(*)(void)) op_times} } , - { PT_OP_MOD, "%", 2, {(void(*)(void)) op_mod} } , - { PT_OP_DIVIDE, "/", 2, {(void(*)(void)) op_divide} } , - { PT_OP_COMMA, ",", 2, {(void(*)(void)) op_comma} } , - { PT_OP_POWER, "^", 2, {(void(*)(void)) op_power} } , - { PT_OP_EQ, "=", 2, {(void(*)(void)) op_eq} } , - { PT_OP_GT, ">", 2, {(void(*)(void)) op_gt} } , - { PT_OP_LT, "<", 2, {(void(*)(void)) op_lt} } , - { PT_OP_GE, ">=", 2, {(void(*)(void)) op_ge} } , - { PT_OP_LE, "<=", 2, {(void(*)(void)) op_le} } , - { PT_OP_NE, "<>", 2, {(void(*)(void)) op_ne} } , - { PT_OP_AND, "&", 2, {(void(*)(void)) op_and} } , - { PT_OP_OR, "|", 2, {(void(*)(void)) op_or} } , - { PT_OP_INDX, "[", 2, {(void(*)(void)) op_ind} } , - { PT_OP_RANGE, "[[", 2, {(void(*)(void)) op_range} } , - { PT_OP_TERNARY, "?:", 2, {NULL} } , - { 0, NULL, 0, {NULL} } -} ; +static struct op ops[] = { + { PT_OP_PLUS, "+", 2, {(void(*)(void)) op_plus} }, + { PT_OP_MINUS, "-", 2, {(void(*)(void)) op_minus} }, + { PT_OP_TIMES, "*", 2, {(void(*)(void)) op_times} }, + { PT_OP_MOD, "%", 2, {(void(*)(void)) op_mod} }, + { PT_OP_DIVIDE, "/", 2, {(void(*)(void)) op_divide} }, + { PT_OP_COMMA, ",", 2, {(void(*)(void)) op_comma} }, + { PT_OP_POWER, "^", 2, {(void(*)(void)) op_power} }, + { PT_OP_EQ, "=", 2, {(void(*)(void)) op_eq} }, + { PT_OP_GT, ">", 2, {(void(*)(void)) op_gt} }, + { PT_OP_LT, "<", 2, {(void(*)(void)) op_lt} }, + { PT_OP_GE, ">=", 2, {(void(*)(void)) op_ge} }, + { PT_OP_LE, "<=", 2, {(void(*)(void)) op_le} }, + { PT_OP_NE, "<>", 2, {(void(*)(void)) op_ne} }, + { PT_OP_AND, "&", 2, {(void(*)(void)) op_and} }, + { PT_OP_OR, "|", 2, {(void(*)(void)) op_or} }, + { PT_OP_INDX, "[", 2, {(void(*)(void)) op_ind} }, + { PT_OP_RANGE, "[[", 2, {(void(*)(void)) op_range} }, + { PT_OP_TERNARY, "?:", 2, {NULL} }, + { 0, NULL, 0, {NULL} } +}; -static -struct op uops[] = { - { PT_OP_UMINUS, "-", 1, {(void(*)(void)) op_uminus} } , - { PT_OP_NOT, "~", 1, {(void(*)(void)) op_not} } , + +static struct op uops[] = { + { PT_OP_UMINUS, "-", 1, {(void(*)(void)) op_uminus} }, + { PT_OP_NOT, "~", 1, {(void(*)(void)) op_not} }, { 0, NULL, 0, {NULL} } -} ; +}; + /* We have 'v' declared as a function, because if we don't then the defines * we do for vm(), etc won't work. This is caught in evaluate(). Bad kludge. */ -typedef void* cx_function_t(void*,short int,int,int*,short int*); +typedef void* cx_function_t(void*, short int, int, int*, short int*); struct func ft_funcs[] = { - { "mag", cx_mag } , - { "magnitude", cx_mag } , - { "cph", cx_cph } , /* SJdV */ - { "cphase", cx_cph } , /* SJdV Continious phase*/ - { "ph", cx_ph } , - { "phase", cx_ph } , - { "j", cx_j } , - { "real", cx_real } , - { "re", cx_real } , - { "imag", cx_imag } , - { "im", cx_imag } , - { "db", cx_db } , - { "log", cx_log } , - { "log10", cx_log } , - { "ln", cx_ln } , - { "exp", cx_exp } , - { "abs", cx_mag } , - { "sqrt", cx_sqrt } , - { "sin", cx_sin } , - { "cos", cx_cos } , - { "tan", cx_tan } , - { "sinh", cx_sinh } , - { "cosh", cx_cosh } , - { "tanh", cx_tanh } , - { "atan", cx_atan } , - { "norm", cx_norm } , - { "rnd", cx_rnd } , - { "sunif", cx_sunif } , - { "poisson",cx_poisson } , - { "exponential", cx_exponential } , - { "sgauss", cx_sgauss } , - { "pos", cx_pos } , - { "floor", cx_floor } , - { "ceil", cx_ceil } , - { "mean", cx_mean } , - { "avg", cx_avg } , /* A.Roldan 03/06/05 incremental average new function */ - { "group_delay", (cx_function_t*) cx_group_delay } , /* A.Roldan 10/06/05 group delay new function */ - { "vector", cx_vector } , - { "unitvec", cx_unitvec } , - { "length", cx_length } , - { "vecmin", cx_min } , - { "vecmax", cx_max } , - { "vecd", cx_d } , - { "interpolate", (cx_function_t*) cx_interpolate } , - { "deriv", (cx_function_t*) cx_deriv } , - { "v", NULL } , - { NULL, NULL } -} ; + { "mag", cx_mag }, + { "magnitude", cx_mag }, + { "cph", cx_cph }, /* SJdV */ + { "cphase", cx_cph }, /* SJdV Continious phase*/ + { "ph", cx_ph }, + { "phase", cx_ph }, + { "j", cx_j }, + { "real", cx_real }, + { "re", cx_real }, + { "imag", cx_imag }, + { "im", cx_imag }, + { "db", cx_db }, + { "log", cx_log }, + { "log10", cx_log }, + { "ln", cx_ln }, + { "exp", cx_exp }, + { "abs", cx_mag }, + { "sqrt", cx_sqrt }, + { "sin", cx_sin }, + { "cos", cx_cos }, + { "tan", cx_tan }, + { "sinh", cx_sinh }, + { "cosh", cx_cosh }, + { "tanh", cx_tanh }, + { "atan", cx_atan }, + { "norm", cx_norm }, + { "rnd", cx_rnd }, + { "sunif", cx_sunif }, + { "poisson", cx_poisson }, + { "exponential", cx_exponential }, + { "sgauss", cx_sgauss }, + { "pos", cx_pos }, + { "floor", cx_floor }, + { "ceil", cx_ceil }, + { "mean", cx_mean }, + { "avg", cx_avg }, /* A.Roldan 03/06/05 incremental average new function */ + { "group_delay", (cx_function_t*) cx_group_delay }, /* A.Roldan 10/06/05 group delay new function */ + { "vector", cx_vector }, + { "unitvec", cx_unitvec }, + { "length", cx_length }, + { "vecmin", cx_min }, + { "vecmax", cx_max }, + { "vecd", cx_d }, + { "interpolate", (cx_function_t*) cx_interpolate }, + { "deriv", (cx_function_t*) cx_deriv }, + { "v", NULL }, + { NULL, NULL } +}; struct func func_uminus = { "minus", cx_uminus }; struct func func_not = { "not", cx_not }; + /* Binary operator node. */ static struct pnode * @@ -202,23 +201,28 @@ mkbnode(int opnum, struct pnode *arg1, struct pnode *arg2) for (o = &ops[0]; o->op_name; o++) if (o->op_num == opnum) break; + if (!o->op_name) fprintf(cp_err, "mkbnode: Internal Error: no such op num %d\n", - opnum); + opnum); + p = alloc(struct pnode); p->pn_use = 0; p->pn_value = NULL; - p->pn_name = NULL; /* sjb */ + p->pn_name = NULL; /* sjb */ p->pn_func = NULL; p->pn_op = o; p->pn_left = arg1; - if(p->pn_left) p->pn_left->pn_use++; + if (p->pn_left) + p->pn_left->pn_use++; p->pn_right = arg2; - if(p->pn_right) p->pn_right->pn_use++; + if (p->pn_right) + p->pn_right->pn_use++; p->pn_next = NULL; return (p); } + /* Unary operator node. */ static struct pnode * @@ -231,6 +235,7 @@ mkunode(int op, struct pnode *arg) for (o = uops; o->op_name; o++) if (o->op_num == op) break; + if (!o->op_name) fprintf(cp_err, "mkunode: Internal Error: no such op num %d\n", op); @@ -238,15 +243,17 @@ mkunode(int op, struct pnode *arg) p->pn_op = o; p->pn_use = 0; p->pn_value = NULL; - p->pn_name = NULL; /* sjb */ + p->pn_name = NULL; /* sjb */ p->pn_func = NULL; p->pn_left = arg; - if(p->pn_left) p->pn_left->pn_use++; + if (p->pn_left) + p->pn_left->pn_use++; p->pn_right = NULL; p->pn_next = NULL; return (p); } + /* Function node. We have to worry about a lot of things here. Something * like f(a) could be three things -- a call to a standard function, which * is easiest to deal with, a variable name, in which case we do the @@ -266,22 +273,25 @@ mkfnode(const char *func, struct pnode *arg) (void) strcpy(buf, func); strtolower(buf); /* Make sure the case is ok. */ + for (f = &ft_funcs[0]; f->fu_name; f++) if (eq(f->fu_name, buf)) break; + if (f->fu_name == NULL) { /* Give the user-defined functions a try. */ q = ft_substdef(func, arg); if (q) return (q); } + if ((f->fu_name == NULL) && arg->pn_value) { /* Kludge -- maybe it is really a variable name. */ (void) sprintf(buf, "%s(%s)", func, arg->pn_value->v_name); d = vec_get(buf); if (d == NULL) { /* Well, too bad. */ - fprintf(cp_err, "Error: no such function as %s.\n", + fprintf(cp_err, "Error: no such function as %s.\n", func); return (NULL); } @@ -290,14 +300,14 @@ mkfnode(const char *func, struct pnode *arg) } else if (f->fu_name == NULL) { fprintf(cp_err, "Error: no function as %s with that arity.\n", func); - return (NULL); + return (NULL); } if (!f->fu_func && arg->pn_op && arg->pn_op->op_num == PT_OP_COMMA) { - p = mkbnode(PT_OP_MINUS, mkfnode(func, arg->pn_left), - mkfnode(func, arg->pn_right)); - tfree(arg); - return p; + p = mkbnode(PT_OP_MINUS, mkfnode(func, arg->pn_left), + mkfnode(func, arg->pn_right)); + tfree(arg); + return p; } p = alloc(struct pnode); @@ -307,12 +317,14 @@ mkfnode(const char *func, struct pnode *arg) p->pn_func = f; p->pn_op = NULL; p->pn_left = arg; - if(p->pn_left) p->pn_left->pn_use++; + if (p->pn_left) + p->pn_left->pn_use++; p->pn_right = NULL; p->pn_next = NULL; return (p); } + /* Number node. */ static struct pnode * @@ -352,6 +364,7 @@ mknnode(double number) return (p); } + /* String node. */ static struct pnode * @@ -370,7 +383,7 @@ mksnode(const char *string) v = vec_get(string); if (v == NULL) { nv = alloc(struct dvec); - ZERO(nv, struct dvec); + ZERO(nv, struct dvec); p->pn_value = nv; nv->v_name = copy(string); return (p); @@ -388,143 +401,147 @@ mksnode(const char *string) end = nv; } p->pn_value = newv; - + /* va: tfree v in case of @xxx[par], because vec_get created a new vec and nobody will free it elsewhere */ - /*if (v && v->v_name && *v->v_name=='@' && isreal(v) && v->v_realdata) { - vec_free(v); - } */ + /*if (v && v->v_name && *v->v_name == '@' && isreal(v) && v->v_realdata) { + vec_free(v); + } */ /* The two lines above have been commented out to prevent deletion of @xxx[par] - after execution of only a single command like plot @xxx[par] or write. We need to - monitor if this will lead to excessive memory usage. h_vogt 090221 */ + after execution of only a single command like plot @xxx[par] or write. We need to + monitor if this will lead to excessive memory usage. h_vogt 090221 */ return (p); } -/* Don't call this directly, always use the free_pnode() macro. + +/* Don't call this directly, always use the free_pnode() macro. The linked pnodes do not necessarily form a perfect tree as some nodes get reused. Hence, in this recursive walk trough the 'tree' we only free node that have their pn_use value at zero. Nodes that have pn_use values above zero have the link severed and their pn_use value decremented. In addition, we don't walk past nodes with pn_use values avoid zero, just in case we have a circular reference (this probable does not happen in - practice, but it does no harm playing safe) */ + practice, but it does no harm playing safe) */ void free_pnode_x(struct pnode *t) { if (!t) - return; - + return; + /* don't walk past nodes used elsewhere. We decrement the pn_use value here, but the link gets severed by the action of the free_pnode() macro */ - if(t->pn_use>1) - t->pn_use--; - else { - /* pn_use is now 1, so its safe to free the pnode */ - free_pnode(t->pn_left); - free_pnode(t->pn_right); - free_pnode(t->pn_next); - tfree(t->pn_name); /* va: it is a copy() of original string, can be free'd */ - if (t->pn_value && !(t->pn_value->v_flags & VF_PERMANENT)) - vec_free(t->pn_value); /* patch by Stefan Jones */ - tfree(t); + if (t->pn_use > 1) { + t->pn_use--; + } else { + /* pn_use is now 1, so its safe to free the pnode */ + free_pnode(t->pn_left); + free_pnode(t->pn_right); + free_pnode(t->pn_next); + tfree(t->pn_name); /* va: it is a copy() of original string, can be free'd */ + if (t->pn_value && !(t->pn_value->v_flags & VF_PERMANENT)) + vec_free(t->pn_value); /* patch by Stefan Jones */ + tfree(t); } } + /* here is the original free_node, which is needed in spec.c and com_fft.c */ void free_pnode_o(struct pnode *t) { - if (!t) - return; - free_pnode(t->pn_left); - free_pnode(t->pn_right); - free_pnode(t->pn_next); - tfree(t); + if (!t) + return; + free_pnode(t->pn_left); + free_pnode(t->pn_right); + free_pnode(t->pn_next); + tfree(t); } - static void db_print_func(FILE *fdst, struct func *f) { - if(!f) { - fprintf(fdst,"nil"); + if (!f) { + fprintf(fdst, "nil"); return; } - fprintf(fdst,"(func :fu_name %s :fu_func %p)", f->fu_name, f->fu_func); + fprintf(fdst, "(func :fu_name %s :fu_func %p)", f->fu_name, f->fu_func); } static void db_print_op(FILE *fdst, struct op *op) { - if(!op) { - fprintf(fdst,"nil"); + if (!op) { + fprintf(fdst, "nil"); return; } - fprintf(fdst,"(op :op_num %d :op_name %s :op_arity %d :op_func %p)", - op->op_num, op->op_name, op->op_arity, op->op_func.anonymous); + fprintf(fdst, "(op :op_num %d :op_name %s :op_arity %d :op_func %p)", + op->op_num, op->op_name, op->op_arity, op->op_func.anonymous); } static void db_print_dvec(FILE *fdst, struct dvec *d) { - if(!d) { - fprintf(fdst,"nil"); + if (!d) { + fprintf(fdst, "nil"); return; } - fprintf(fdst,"(dvec :v_name %s :v_type %d :v_flags %d :v_length %d ...)", - d->v_name, d->v_type, d->v_flags, d->v_length); + fprintf(fdst, "(dvec :v_name %s :v_type %d :v_flags %d :v_length %d ...)", + d->v_name, d->v_type, d->v_flags, d->v_length); } static void db_print_pnode(FILE *fdst, struct pnode *p) { - if(!p) { - fprintf(fdst,"nil\n"); + if (!p) { + fprintf(fdst, "nil\n"); return; } - if(!p->pn_name && p->pn_value && !p->pn_func && !p->pn_op - && !p->pn_left && !p->pn_right && !p->pn_next) { - fprintf(fdst,"(pnode-value :pn_use %d", p->pn_use); - fprintf(fdst," :pn_value "); db_print_dvec(fdst, p->pn_value); - fprintf(fdst,")\n"); + if (!p->pn_name && p->pn_value && !p->pn_func && !p->pn_op && + !p->pn_left && !p->pn_right && !p->pn_next) + { + fprintf(fdst, "(pnode-value :pn_use %d", p->pn_use); + fprintf(fdst, " :pn_value "); db_print_dvec(fdst, p->pn_value); + fprintf(fdst, ")\n"); return; } - if (!p->pn_name && !p->pn_value && p->pn_func && !p->pn_op - && !p->pn_right && !p->pn_next) { - fprintf(fdst,"(pnode-func :pn_use %d", p->pn_use); - fprintf(fdst,"\n :pn_func "); db_print_func(fdst, p->pn_func); - fprintf(fdst,"\n :pn_left "); db_print_pnode(fdst, p->pn_left); - fprintf(fdst,")\n"); + if (!p->pn_name && !p->pn_value && p->pn_func && !p->pn_op && + !p->pn_right && !p->pn_next) + { + fprintf(fdst, "(pnode-func :pn_use %d", p->pn_use); + fprintf(fdst, "\n :pn_func "); db_print_func(fdst, p->pn_func); + fprintf(fdst, "\n :pn_left "); db_print_pnode(fdst, p->pn_left); + fprintf(fdst, ")\n"); return; } - if (!p->pn_name && !p->pn_value && !p->pn_func && p->pn_op - && !p->pn_next) { - fprintf(fdst,"(pnode-op :pn_use %d", p->pn_use); - fprintf(fdst,"\n :pn_op "); db_print_op(fdst, p->pn_op); - fprintf(fdst,"\n :pn_left "); db_print_pnode(fdst, p->pn_left); - fprintf(fdst,"\n :pn_right "); db_print_pnode(fdst, p->pn_right); - fprintf(fdst,")\n"); + if (!p->pn_name && !p->pn_value && !p->pn_func && p->pn_op && + !p->pn_next) + { + fprintf(fdst, "(pnode-op :pn_use %d", p->pn_use); + fprintf(fdst, "\n :pn_op "); db_print_op(fdst, p->pn_op); + fprintf(fdst, "\n :pn_left "); db_print_pnode(fdst, p->pn_left); + fprintf(fdst, "\n :pn_right "); db_print_pnode(fdst, p->pn_right); + fprintf(fdst, ")\n"); return; } - fprintf(fdst,"(pnode :pn_name \"%s\" pn_use %d", p->pn_name, p->pn_use); - fprintf(fdst,"\n :pn_value "); db_print_dvec(fdst, p->pn_value); - fprintf(fdst,"\n :pn_func "); db_print_func(fdst, p->pn_func); - fprintf(fdst,"\n :pn_op "); db_print_op(fdst, p->pn_op); - fprintf(fdst,"\n :pn_left "); db_print_pnode(fdst, p->pn_left); - fprintf(fdst,"\n :pn_right "); db_print_pnode(fdst, p->pn_right); - fprintf(fdst,"\n :pn_next "); db_print_pnode(fdst, p->pn_next); - fprintf(fdst,"\n)\n"); + fprintf(fdst, "(pnode :pn_name \"%s\" pn_use %d", p->pn_name, p->pn_use); + fprintf(fdst, "\n :pn_value "); db_print_dvec(fdst, p->pn_value); + fprintf(fdst, "\n :pn_func "); db_print_func(fdst, p->pn_func); + fprintf(fdst, "\n :pn_op "); db_print_op(fdst, p->pn_op); + fprintf(fdst, "\n :pn_left "); db_print_pnode(fdst, p->pn_left); + fprintf(fdst, "\n :pn_right "); db_print_pnode(fdst, p->pn_right); + fprintf(fdst, "\n :pn_next "); db_print_pnode(fdst, p->pn_next); + fprintf(fdst, "\n)\n"); } @@ -538,10 +555,10 @@ db_print_pnode_tree(struct pnode *p, char *print) #else char *buf; size_t buf_size; - FILE *db_stream = open_memstream (&buf, &buf_size); + FILE *db_stream = open_memstream(&buf, &buf_size); db_print_pnode(db_stream, p); fclose(db_stream); - if(print) + if (print) printf("%s:%d: %s {%s}\n%s\n", __FILE__, __LINE__, __func__, print, buf); return buf; #endif @@ -560,7 +577,7 @@ PPlex(YYSTYPE *lvalp, struct PPltype *llocp, char **line) llocp->start = sbuf; -#define lexer_return(token_, length) \ +#define lexer_return(token_, length) \ do { token = token_; sbuf += length; goto done; } while(0) if ((sbuf[0] == 'g') && (sbuf[1] == 't') && @@ -610,20 +627,20 @@ PPlex(YYSTYPE *lvalp, struct PPltype *llocp, char **line) case '>': case '<': - { - /* Workaround, The Frontend makes "<>" into "< >" */ - int j = 1; - while (isspace(sbuf[j])) - j++; - if (((sbuf[j] == '<') || (sbuf[j] == '>')) && (sbuf[0] != sbuf[j])) { - /* Allow both <> and >< for NE. */ - lexer_return(TOK_NE, j+1); - } else if (sbuf[1] == '=') { - lexer_return((sbuf[0] == '>') ? TOK_GE : TOK_LE, 2); - } else { - lexer_return(*sbuf, 1); - } + { + /* Workaround, The Frontend makes "<>" into "< >" */ + int j = 1; + while (isspace(sbuf[j])) + j++; + if (((sbuf[j] == '<') || (sbuf[j] == '>')) && (sbuf[0] != sbuf[j])) { + /* Allow both <> and >< for NE. */ + lexer_return(TOK_NE, j+1); + } else if (sbuf[1] == '=') { + lexer_return((sbuf[0] == '>') ? TOK_GE : TOK_LE, 2); + } else { + lexer_return(*sbuf, 1); } + } case '?': case ':': @@ -646,49 +663,49 @@ PPlex(YYSTYPE *lvalp, struct PPltype *llocp, char **line) lexer_return(*sbuf, 0); case '"': - { - char *start = ++sbuf; - while(*sbuf && (*sbuf != '"')) - sbuf++; - lvalp->str = copy_substring(start, sbuf); - if(*sbuf) - sbuf++; - lexer_return(TOK_STR, 0); - } + { + char *start = ++sbuf; + while (*sbuf && (*sbuf != '"')) + sbuf++; + lvalp->str = copy_substring(start, sbuf); + if (*sbuf) + sbuf++; + lexer_return(TOK_STR, 0); + } default: - { - char *s = sbuf; - double *td = ft_numparse(&s, FALSE); - if ((!s || *s != ':') && td) { - sbuf = s; - lvalp->num = *td; - lexer_return(TOK_NUM, 0); - } else { - int atsign = 0; - char *start = sbuf; - /* It is bad how we have to recognise '[' -- sometimes - * it is part of a word, when it defines a parameter - * name, and otherwise it isn't. - * va, ']' too - */ - for (; *sbuf && !strchr(specials, *sbuf); sbuf++) - if (*sbuf == '@') - atsign = 1; - else if (!atsign && ( *sbuf == '[' || *sbuf == ']' )) - break; + { + char *s = sbuf; + double *td = ft_numparse(&s, FALSE); + if ((!s || *s != ':') && td) { + sbuf = s; + lvalp->num = *td; + lexer_return(TOK_NUM, 0); + } else { + int atsign = 0; + char *start = sbuf; + /* It is bad how we have to recognise '[' -- sometimes + * it is part of a word, when it defines a parameter + * name, and otherwise it isn't. + * va, ']' too + */ + for (; *sbuf && !strchr(specials, *sbuf); sbuf++) + if (*sbuf == '@') + atsign = 1; + else if (!atsign && (*sbuf == '[' || *sbuf == ']')) + break; - lvalp->str = copy_substring(start, sbuf); - lexer_return(TOK_STR, 0); - } + lvalp->str = copy_substring(start, sbuf); + lexer_return(TOK_STR, 0); } } + } done: if (ft_parsedb) { - if(token == TOK_STR) + if (token == TOK_STR) fprintf(stderr, "lexer: TOK_STR, \"%s\"\n", lvalp->str); - else if(token == TOK_NUM) + else if (token == TOK_NUM) fprintf(stderr, "lexer: TOK_NUM, %G\n", lvalp->num); else fprintf(stderr, "lexer: token %d\n", token); diff --git a/src/frontend/parser/backq.c b/src/frontend/parser/backq.c index 1ebd213e6..b2cc5c42d 100644 --- a/src/frontend/parser/backq.c +++ b/src/frontend/parser/backq.c @@ -4,8 +4,7 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group **********/ /* - * - * Do backquote substitution on a word list. + * Do backquote substitution on a word list. */ #include "ngspice/config.h" @@ -18,6 +17,7 @@ static wordlist *backeval(char *string); char cp_back = '`'; + wordlist * cp_bquote(wordlist *wlist) { @@ -26,12 +26,13 @@ cp_bquote(wordlist *wlist) int i; for (wl = wlist; wl; wl = wl->wl_next) { - + t = wl->wl_word; if (!t) continue; i = 0; -loop: s =strchr(t, cp_back); + loop: + s = strchr(t, cp_back); if (s == NULL) continue; while (t < s) @@ -47,28 +48,28 @@ loop: s =strchr(t, cp_back); /* What the heck, let "echo `foo" work... */ *s = '\0'; t++; /* Get past the second ` */ - if ((nwl = backeval(buf)) == NULL) { + if ((nwl = backeval(buf)) == NULL) { wlist->wl_word = NULL; return (wlist); } - (void) strcpy(buf, wbuf); - if (nwl->wl_word) { - (void) strcat(buf, nwl->wl_word); - tfree(nwl->wl_word); - } - nwl->wl_word = copy(buf); - - (void) strcpy(tbuf, t); - wl = wl_splice(wl, nwl); - for(wlist = wl; wlist->wl_prev; wlist = wlist->wl_prev) - ; - /* MW. We must move to the begging of new wordlist. */ - + (void) strcpy(buf, wbuf); + if (nwl->wl_word) { + (void) strcat(buf, nwl->wl_word); + tfree(nwl->wl_word); + } + nwl->wl_word = copy(buf); + + (void) strcpy(tbuf, t); + wl = wl_splice(wl, nwl); + for (wlist = wl; wlist->wl_prev; wlist = wlist->wl_prev) + ; + /* MW. We must move to the begging of new wordlist. */ + (void) strcpy(buf, wl->wl_word); - i = (int) strlen(buf); + i = (int) strlen(buf); (void) strcat(buf, tbuf); tfree(wl->wl_word); - wl->wl_word = copy(buf); + wl->wl_word = copy(buf); t = &wl->wl_word[i]; s = wl->wl_word; for (i = 0; s < t; s++) @@ -78,6 +79,7 @@ loop: s =strchr(t, cp_back); return (wlist); } + /* Do a popen with the string, and then reset the file pointers so that * we can use the first pass of the parser on the output. */ diff --git a/src/frontend/parser/backq.h b/src/frontend/parser/backq.h index 164c2a03b..1262d1aa2 100644 --- a/src/frontend/parser/backq.h +++ b/src/frontend/parser/backq.h @@ -7,5 +7,4 @@ #define BACKQ_H_INCLUDED - #endif diff --git a/src/frontend/parser/complete.c b/src/frontend/parser/complete.c index 7579272f2..2050c1e8a 100644 --- a/src/frontend/parser/complete.c +++ b/src/frontend/parser/complete.c @@ -36,7 +36,7 @@ Modified: 1999 Paolo Nenzi #endif #if !defined(__MINGW32__) && !defined(_MSC_VER) - /* MW. We also need ioctl.h here I think */ +/* MW. We also need ioctl.h here I think */ #include #endif @@ -54,42 +54,40 @@ Modified: 1999 Paolo Nenzi #endif -#define CNTRL_D '\004' -#define ESCAPE '\033' +#define CNTRL_D '\004' +#define ESCAPE '\033' #define NCLASSES 32 bool cp_nocc; /* Don't do command completion. */ - static struct ccom *commands = NULL; /* The available commands. */ static struct ccom *keywords[NCLASSES]; /* Keywords. */ -/* static declarations */ - -#ifdef TIOCSTI /* va, functions used in this branch only */ -static struct ccom * getccom(char *first); -static wordlist * ccfilec(char *buf); -static wordlist * ccmatch(char *word, struct ccom **dbase); +#ifdef TIOCSTI /* va, functions used in this branch only */ +static struct ccom *getccom(char *first); +static wordlist *ccfilec(char *buf); +static wordlist *ccmatch(char *word, struct ccom **dbase); static void printem(wordlist *wl); #endif -static wordlist * cctowl(struct ccom *cc, bool sib); -static struct ccom * clookup(register char *word, struct ccom **dd, bool pref, - bool create); + +static wordlist *cctowl(struct ccom *cc, bool sib); +static struct ccom *clookup(register char *word, struct ccom **dd, bool pref, + bool create); /* MW. I need top node in cdelete */ static void cdelete(struct ccom *node, struct ccom **top); - #ifdef TIOCSTI + void cp_ccom(wordlist *wlist, char *buf, bool esc) { struct ccom *cc; wordlist *a, *pmatches = NULL; char wbuf[BSIZE_SP], *s; - int i=0; + int i = 0; int j, arg; buf = cp_unquote(copy(buf)); @@ -104,14 +102,14 @@ cp_ccom(wordlist *wlist, char *buf, bool esc) /* First filenames. */ if (cc && (cc->cc_kwords[arg] & 1)) { pmatches = ccfilec(buf); - s =strrchr(buf, '/'); + s = strrchr(buf, '/'); i = (int) strlen(s ? s + 1 : buf); if ((*buf == '~') && !strchr(buf, '/')) i--; } /* The keywords. */ - for (j = 1; j < NCLASSES; j++) { + for (j = 1; j < NCLASSES; j++) if (cc && (cc->cc_kwords[arg] & (1 << j))) { /* Find all the matching keywords. */ a = ccmatch(buf, &keywords[j]); @@ -121,15 +119,14 @@ cp_ccom(wordlist *wlist, char *buf, bool esc) else pmatches = a; } - } wl_sort(pmatches); } else { pmatches = ccmatch(buf, &commands); i = (int) strlen(buf); } - - tfree(buf); /*CDHW*/ - + + tfree(buf); /*CDHW*/ + if (!esc) { printem(pmatches); wl_free(pmatches); @@ -151,21 +148,23 @@ cp_ccom(wordlist *wlist, char *buf, bool esc) for (j = 0;; j++, i++) { wbuf[j] = pmatches->wl_word[i]; for (a = pmatches->wl_next; a; a = a->wl_next) - if (a->wl_word[i] != wbuf[j]) { - (void) putchar('\07'); - (void) fflush(cp_out); - wbuf[j] = '\0'; - goto found; - } + if (a->wl_word[i] != wbuf[j]) { + (void) putchar('\07'); + (void) fflush(cp_out); + wbuf[j] = '\0'; + goto found; + } if (wbuf[j] == '\0') goto found; } -found: for (i = 0; wbuf[i]; i++) +found: + for (i = 0; wbuf[i]; i++) (void) ioctl(fileno(cp_in), TIOCSTI, &wbuf[i]); wl_free(pmatches); return; } + /* Figure out what the command is, given the name. Returns NULL if there * is no such command in the command list. This is tricky, because we have * to do a preliminary history and alias parse. (Or at least we should.) @@ -177,7 +176,7 @@ getccom(char *first) struct alias *al; int ntries = 21; - /* First look for aliases. Just interested in the first word... + /* First look for aliases. Just interested in the first word... * Don't bother doing history yet -- that might get complicated. */ while (ntries-- > 0) { @@ -196,6 +195,7 @@ getccom(char *first) return (clookup(first, &commands, FALSE, FALSE)); } + /* Figure out what files match the prefix. */ static wordlist * @@ -209,17 +209,15 @@ ccfilec(char *buf) buf = copy(buf); /* Don't mangle anything... */ - lcomp =strrchr(buf, '/'); + lcomp = strrchr(buf, '/'); if (lcomp == NULL) { dir = "."; lcomp = buf; if (*buf == cp_til) { /* User name completion... */ buf++; - while ((pw = getpwent()) != NULL) { - if (prefix(buf, pw->pw_name)) { + while ((pw = getpwent()) != NULL) + if (prefix(buf, pw->pw_name)) wl = wl_cons(copy(pw->pw_name), wl); - } - } (void) endpwent(); return (wl); } @@ -233,13 +231,14 @@ ccfilec(char *buf) return (NULL); } } + if (!(wdir = opendir(dir))) return (NULL); + while ((de = readdir(wdir)) != NULL) - if ((prefix(lcomp, de->d_name)) && (*lcomp || - (*de->d_name != '.'))) { + if ((prefix(lcomp, de->d_name)) && (*lcomp || (*de->d_name != '.'))) wl = wl_cons(copy(de->d_name), wl); - } + (void) closedir(wdir); wl_sort(wl); @@ -257,18 +256,22 @@ ccmatch(char *word, struct ccom **dbase) { wordlist *wl; register struct ccom *cc; - + cc = clookup(word, dbase, TRUE, FALSE); + if (cc) { if (*word) /* This is a big drag. */ wl = cctowl(cc, FALSE); else wl = cctowl(cc, TRUE); - } else + } else { wl = NULL; + } + return (wl); } + /* Print the words in the wordlist in columns. They are already * sorted... This is a hard thing to do with wordlists... */ @@ -280,28 +283,30 @@ printem(wordlist *wl) int maxl = 0, num, i, j, k, width = 79, ncols, nlines; (void) putchar('\n'); - if (wl == NULL) { + if (wl == NULL) return; - } + num = wl_length(wl); for (ww = wl; ww; ww = ww->wl_next) { j = (int) strlen(ww->wl_word); if (j > maxl) maxl = j; } + if (++maxl % 8) maxl += 8 - (maxl % 8); ncols = width / maxl; if (ncols == 0) ncols = 1; + nlines = num / ncols + (num % ncols ? 1 : 0); + for (k = 0; k < nlines; k++) { for (i = 0; i < ncols; i++) { j = i * nlines + k; - if (j < num) { - fprintf(cp_out, "%-*s", maxl, - wl_nthelem(j, wl)->wl_word); - } else + if (j < num) + fprintf(cp_out, "%-*s", maxl, wl_nthelem(j, wl)->wl_word); + else break; } (void) putchar('\n'); @@ -310,6 +315,7 @@ printem(wordlist *wl) } #else /* if not TIOCSTI */ + void cp_ccom(wordlist *wlist, char *buf, bool esc) { @@ -318,25 +324,26 @@ cp_ccom(wordlist *wlist, char *buf, bool esc) NG_IGNORE(esc); return; } + #endif + static wordlist * cctowl(struct ccom *cc, bool sib) { wordlist *wl; - + if (!cc) return (NULL); wl = cctowl(cc->cc_child, TRUE); - if (!cc->cc_invalid) { + if (!cc->cc_invalid) wl = wl_cons(copy(cc->cc_name), wl); - } - if (sib) { + if (sib) wl = wl_append(wl, cctowl(cc->cc_sibling, TRUE)); - } return (wl); } + /* We use this in com_device... */ wordlist * @@ -345,6 +352,7 @@ cp_cctowl(struct ccom *stuff) return (cctowl(stuff, TRUE)); } + /* Turn on and off the escape break character and cooked mode. */ void @@ -404,24 +412,24 @@ cp_ccon(bool on) if (ison == TRUE) { #if HAVE_TCGETATTR - tcgetattr(fileno(cp_in),&OS_Buf); + tcgetattr(fileno(cp_in), &OS_Buf); #else - (void) ioctl(fileno(cp_in), TERM_GET, &OS_Buf); + (void) ioctl(fileno(cp_in), TERM_GET, &OS_Buf); #endif - sbuf = OS_Buf; - sbuf.c_cc[VEOF] = 0; - sbuf.c_cc[VEOL] = ESCAPE; - sbuf.c_cc[VEOL2] = CNTRL_D; + sbuf = OS_Buf; + sbuf.c_cc[VEOF] = 0; + sbuf.c_cc[VEOL] = ESCAPE; + sbuf.c_cc[VEOL2] = CNTRL_D; #if HAVE_TCSETATTR - tcsetattr(fileno(cp_in),TCSANOW,&sbuf); + tcsetattr(fileno(cp_in), TCSANOW, &sbuf); #else - (void) ioctl(fileno(cp_in), TERM_SET, &sbuf); + (void) ioctl(fileno(cp_in), TERM_SET, &sbuf); #endif } else { #ifdef HAVE_TCSETATTR - tcsetattr(fileno(cp_in),TCSANOW,&OS_Buf); + tcsetattr(fileno(cp_in), TCSANOW, &OS_Buf); #else - (void) ioctl(fileno(cp_in), TERM_SET, &OS_Buf); + (void) ioctl(fileno(cp_in), TERM_SET, &OS_Buf); #endif } @@ -435,6 +443,7 @@ cp_ccon(bool on) return; } + /* The following routines deal with the command and keyword databases. * Say whether a given word exists in the command database. */ @@ -448,6 +457,7 @@ cp_comlook(char *word) return (FALSE); } + /* Add a command to the database, with the given keywords and filename * flag. */ @@ -465,19 +475,21 @@ cp_addcomm(char *word, long int bits0, long int bits1, long int bits2, long int return; } + /* Remove a command from the database. */ void cp_remcomm(char *word) { struct ccom *cc; - + cc = clookup(word, &commands, FALSE, FALSE); if (cc) cdelete(cc, &commands); return; } + /* Add a keyword to the database. */ void @@ -490,7 +502,7 @@ cp_addkword(int kw_class, char *word) kw_class); return; } -/* word = copy(word); va: not necessary, clookup copies itself (memory leak) */ + /* word = copy(word); va: not necessary, clookup copies itself (memory leak) */ cc = clookup(word, &keywords[kw_class], FALSE, TRUE); cc->cc_invalid = 0; return; @@ -501,18 +513,19 @@ void cp_destroy_keywords(void) { int i; - for (i=0; i= NCLASSES)) { fprintf(cp_err, "cp_remkword: Internal Error: bad class %d\n", kw_class); @@ -524,6 +537,7 @@ cp_remkword(int kw_class, char *word) return; } + /* This routine is used when there are several keyword sets that are * to be switched between rapidly. The return value is the old tree at * that position, and the keyword class given is set to the argument. @@ -556,19 +570,22 @@ cp_ccrestart(bool kwords) return; } + void throwaway(struct ccom *dbase) { - if (!dbase) return; /* va: security first */ + if (!dbase) + return; /* va: security first */ if (dbase->cc_child) throwaway(dbase->cc_child); if (dbase->cc_sibling) throwaway(dbase->cc_sibling); - tfree(dbase->cc_name); /* va: also tfree dbase->cc_name (memory leak) */ + tfree(dbase->cc_name); /* va: also tfree dbase->cc_name (memory leak) */ tfree(dbase); return; } + /* Look up a word in the database. Because of the way the tree is set * up, this also works for looking up all words with a given prefix * (if the pref arg is TRUE). If create is TRUE, then the node is @@ -584,11 +601,11 @@ clookup(register char *word, struct ccom **dd, bool pref, bool create) if (!place) { /* This is the first time we were called. */ - if (!create) + if (!create) { return (NULL); - else { + } else { *dd = place = alloc(struct ccom); - ZERO(place, struct ccom); + ZERO(place, struct ccom); buf[0] = *word; buf[1] = '\0'; place->cc_name = copy(buf); @@ -596,6 +613,7 @@ clookup(register char *word, struct ccom **dd, bool pref, bool create) place->cc_invalid = 1; } } + while (word[ind]) { /* Walk down the sibling list until we find a node that * matches 'word' to 'ind' places. @@ -606,7 +624,7 @@ clookup(register char *word, struct ccom **dd, bool pref, bool create) /* This line doesn't go out that far... */ if (create) { place->cc_sibling = alloc(struct ccom); - ZERO(place->cc_sibling, struct ccom); + ZERO(place->cc_sibling, struct ccom); place->cc_sibling->cc_ysibling = place; place->cc_sibling->cc_parent = place->cc_parent; place = place->cc_sibling; @@ -622,7 +640,7 @@ clookup(register char *word, struct ccom **dd, bool pref, bool create) if (create) { /* Put this one between place and its pred. */ tmpc = alloc(struct ccom); - ZERO(tmpc, struct ccom); + ZERO(tmpc, struct ccom); tmpc->cc_parent = place->cc_parent; tmpc->cc_sibling = place; tmpc->cc_ysibling = place->cc_ysibling; @@ -652,7 +670,7 @@ clookup(register char *word, struct ccom **dd, bool pref, bool create) /* No children, maybe make one and go on. */ if (create) { tmpc = alloc(struct ccom); - ZERO(tmpc, struct ccom); + ZERO(tmpc, struct ccom); tmpc->cc_parent = place; place->cc_child = tmpc; place = tmpc; @@ -665,57 +683,63 @@ clookup(register char *word, struct ccom **dd, bool pref, bool create) } else { return (NULL); } - } else + } else { place = place->cc_child; + } ind++; - } else + } else { break; + } } + if (!pref && !create && place->cc_invalid) { /* This is no good, we want a real word. */ return (NULL); } + return (place); } + /* Delete a node from the tree. Returns the new tree... */ -/* MW. It is quite difficoult to free() everything right, but... +/* MW. It is quite difficoult to free() everything right, but... * Anyway this could be more optimal, I think */ static void cdelete(struct ccom *node, struct ccom **top) { - /* if cc_child exist only mark as deleted */ - node->cc_invalid = 1; - if (node->cc_child) - return; - - /* fix cc_sibling */ - if (node->cc_sibling) - node->cc_sibling->cc_ysibling = node->cc_ysibling; - if (node->cc_ysibling) - node->cc_ysibling->cc_sibling = node->cc_sibling; - - /* if we have cc_parent, check if it should not be removed too */ - if (node->cc_parent) { - - /* this node will be free() */ - if (node->cc_parent->cc_child == node) { - if (node->cc_ysibling) - node->cc_parent->cc_child = node->cc_ysibling; - else - node->cc_parent->cc_child = node->cc_sibling; - } - if (node->cc_parent->cc_invalid == 1) - /* free parent only if it is invalid */ - cdelete(node->cc_parent, top); - } - - /* now free() everything and check the top */ - if (node == *top) - *top = node->cc_sibling; - tfree(node->cc_name); /* va: we should allways use tfree */ - tfree(node); - return; -} + /* if cc_child exist only mark as deleted */ + node->cc_invalid = 1; + if (node->cc_child) + return; + /* fix cc_sibling */ + if (node->cc_sibling) + node->cc_sibling->cc_ysibling = node->cc_ysibling; + if (node->cc_ysibling) + node->cc_ysibling->cc_sibling = node->cc_sibling; + + /* if we have cc_parent, check if it should not be removed too */ + if (node->cc_parent) { + + /* this node will be free() */ + if (node->cc_parent->cc_child == node) { + if (node->cc_ysibling) + node->cc_parent->cc_child = node->cc_ysibling; + else + node->cc_parent->cc_child = node->cc_sibling; + } + + /* free parent only if it is invalid */ + if (node->cc_parent->cc_invalid == 1) + cdelete(node->cc_parent, top); + } + + /* now free() everything and check the top */ + if (node == *top) + *top = node->cc_sibling; + + tfree(node->cc_name); /* va: we should allways use tfree */ + tfree(node); + return; +} diff --git a/src/frontend/parser/complete.h b/src/frontend/parser/complete.h index 1bd6da4e0..691eaf481 100644 --- a/src/frontend/parser/complete.h +++ b/src/frontend/parser/complete.h @@ -14,18 +14,17 @@ */ - #define NARGS 4 struct ccom { - char *cc_name; /* Command or keyword name. */ - long cc_kwords[NARGS]; /* What this command takes. */ - char cc_invalid; /* This node has been deleted. */ - struct ccom *cc_child; /* Left-most child. */ - struct ccom *cc_sibling;/* Right (alph. greater) sibling. */ - struct ccom *cc_ysibling;/* Left (alph. less) sibling. */ - struct ccom *cc_parent; /* Parent node. */ -} ; + char *cc_name; /* Command or keyword name. */ + long cc_kwords[NARGS]; /* What this command takes. */ + char cc_invalid; /* This node has been deleted. */ + struct ccom *cc_child; /* Left-most child. */ + struct ccom *cc_sibling; /* Right (alph. greater) sibling. */ + struct ccom *cc_ysibling; /* Left (alph. less) sibling. */ + struct ccom *cc_parent; /* Parent node. */ +}; void throwaway(struct ccom *dbase); diff --git a/src/frontend/parser/cshpar.c b/src/frontend/parser/cshpar.c index ed85585f0..0eed170c5 100644 --- a/src/frontend/parser/cshpar.c +++ b/src/frontend/parser/cshpar.c @@ -43,7 +43,7 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group * and command ignoring. Also deal with command completion. * (2) Do history substitutions. (!, ^) * (3) Do alias substitution. - * + * * In front.c these things get done: * (4) Do variable substitution. ($varname) * (5) Do backquote substitution. (``) @@ -51,7 +51,6 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group * (7) Do io redirection. */ -/* static functions */ static void pwlist(wordlist *wlist, char *name); @@ -91,6 +90,7 @@ cp_parse(char *string) return (wlist); } + static void pwlist(wordlist *wlist, char *name) { @@ -104,4 +104,3 @@ pwlist(wordlist *wlist, char *name) fprintf(cp_err, "]\n"); return; } - diff --git a/src/frontend/parser/glob.c b/src/frontend/parser/glob.c index f2f03713c..ab30e183e 100644 --- a/src/frontend/parser/glob.c +++ b/src/frontend/parser/glob.c @@ -32,7 +32,6 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group #endif - char cp_comma = ','; char cp_ocurl = '{'; char cp_ccurl = '}'; @@ -52,7 +51,7 @@ static wordlist *brac2(char *string); wordlist * cp_doglob(wordlist *wlist) { - wordlist *wl; + wordlist *wl; char *s; /* Expand {a,b,c} */ @@ -76,14 +75,15 @@ cp_doglob(wordlist *wlist) s = cp_tildexpand(wl->wl_word); txfree(wl->wl_word); /* sjb - fix memory leak */ if (!s) - *wl->wl_word = '\0'; /* MW. We Con't touch tmalloc addres */ + *wl->wl_word = '\0'; /* MW. We Con't touch tmalloc addres */ else - wl->wl_word = s; + wl->wl_word = s; } return (wlist); } + static wordlist * bracexpand(char *string) { @@ -145,9 +145,10 @@ brac1(char *string) } wl_free(words); words = newwl; - } else + } else { for (wl = words; wl; wl = wl->wl_next) appendc(wl->wl_word, *s); + } } return (words); } @@ -200,17 +201,17 @@ brac2(char *string) char * cp_tildexpand(char *string) { - char *result; + char *result; result = tildexpand(string); if (!result) { - if (cp_nonomatch) { - return copy(string); - } else { - return NULL; - } + if (cp_nonomatch) + return copy(string); + else + return NULL; } + return result; } @@ -222,6 +223,5 @@ cp_tildexpand(char *string) bool cp_globmatch(char *p, char *s) { - return(!(strcmp(p, s))); + return (!(strcmp(p, s))); } - diff --git a/src/frontend/parser/glob.h b/src/frontend/parser/glob.h index 13c30ede2..97b817062 100644 --- a/src/frontend/parser/glob.h +++ b/src/frontend/parser/glob.h @@ -7,5 +7,4 @@ #define GLOB_H_INCLUDED - #endif diff --git a/src/frontend/parser/input.c b/src/frontend/parser/input.c index 6f4898954..a953e2a4a 100644 --- a/src/frontend/parser/input.c +++ b/src/frontend/parser/input.c @@ -18,50 +18,53 @@ Author: 1988 Jeffrey M. Hsu #ifdef _MSC_VER #include "BaseTsd.h" /* for SSIZE_T */ #define ssize_t SSIZE_T -#ifndef HAS_WINDOWS +#ifndef HAS_WINDOWS #define read _read /* only for console */ #endif #endif + /* A special 'getc' so that we can deal with ^D properly. There is no way for * stdio to know if we have typed a ^D after some other characters, so * don't use buffering at all */ + int inchar(FILE *fp) { - -#ifndef HAS_WINDOWS +#ifndef HAS_WINDOWS char c; ssize_t i; if (cp_interactive && !cp_nocc) { - do { - i = read(fileno(fp), &c, 1); - } while (i == -1 && errno == EINTR); - if (i == 0 || c == '\004') - return (EOF); - else if (i == -1) { - perror("read"); - return (EOF); - } else - return ((int) c); + do + i = read(fileno(fp), &c, 1); + while (i == -1 && errno == EINTR); + + if (i == 0 || c == '\004') { + return (EOF); + } else if (i == -1) { + perror("read"); + return (EOF); + } else { + return ((int) c); + } } else -#endif - return (getc(fp)); +#endif + return (getc(fp)); } -int +int input(FILE *fp) { - REQUEST request; RESPONSE response; request.option = char_option; request.fp = fp; - Input(&request, &response); - return(inchar(fp)); + Input(&request, &response); + + return (inchar(fp)); } diff --git a/src/frontend/parser/lexical.c b/src/frontend/parser/lexical.c index b80271534..6d4f71cdf 100644 --- a/src/frontend/parser/lexical.c +++ b/src/frontend/parser/lexical.c @@ -213,8 +213,9 @@ nloop: goto done; case '\'': - while (((c = (string ? *string++ : input(cp_inp_cur))) != '\'') - && (i < NEW_BSIZE_SP - 1)) { + while (((c = (string ? *string++ : input(cp_inp_cur))) != '\'') && + (i < NEW_BSIZE_SP - 1)) + { if ((c == '\n') || (c == EOF) || (c == ESCAPE)) goto gotchar; buf[i++] = (char) quote(c); @@ -227,8 +228,9 @@ nloop: case '`': d = c; buf[i++] = (char) d; - while (((c = (string ? *string++ : input(cp_inp_cur))) != d) - && (i < NEW_BSIZE_SP - 2)) { + while (((c = (string ? *string++ : input(cp_inp_cur))) != d) && + (i < NEW_BSIZE_SP - 2)) + { if ((c == '\n') || (c == EOF) || (c == ESCAPE)) goto gotchar; if (c == '\\') { @@ -269,7 +271,7 @@ nloop: #ifdef TIOCSTI (void) ioctl(fileno(cp_out), TIOCSTI, linebuf + j); #else - fputc(linebuf[j], cp_out); /* But you can't edit */ + fputc(linebuf[j], cp_out); /* But you can't edit */ #endif wlist = cw = NULL; goto nloop; @@ -294,7 +296,7 @@ nloop: #ifdef TIOCSTI (void) ioctl(fileno(cp_out), TIOCSTI, linebuf + j); #else - fputc(linebuf[j], cp_out); /* But you can't edit */ + fputc(linebuf[j], cp_out); /* But you can't edit */ #endif // cp_ccom doesn't mess wlist, read only access to wlist->wl_word cp_ccom(wlist, buf, TRUE); @@ -327,7 +329,7 @@ nloop: case '<': case '>': /* va: <=, >= are unbreakable words */ - if(string) + if (string) if ((i == 0) && (*string == '=')) { buf[i++] = (char) c; break; @@ -351,7 +353,7 @@ nloop: done: if (wlist->wl_word) - pwlist_echo(wlist,"Command>"); + pwlist_echo(wlist, "Command>"); return wlist; } diff --git a/src/frontend/parser/numparse.c b/src/frontend/parser/numparse.c index 628d753a3..81cdb34c6 100644 --- a/src/frontend/parser/numparse.c +++ b/src/frontend/parser/numparse.c @@ -25,6 +25,7 @@ power10(double num) /* Chris Inbody */ bool ft_strictnumparse = FALSE; + /* Parse a number. This will handle things like 10M, etc... If the number * must not end before the end of the string, then whole is TRUE. * If whole is FALSE and there is more left to the number, the argument @@ -34,6 +35,7 @@ bool ft_strictnumparse = FALSE; * * If ft_strictnumparse is TRUE, and whole is FALSE, the first of the * trailing characters must be a '_'. */ + double * ft_numparse(char **s, bool whole) { @@ -44,22 +46,22 @@ ft_numparse(char **s, bool whole) char *string = *s; /* See if the number begins with + or -. */ - if (*string == '+') + if (*string == '+') { string++; - else if (*string == '-') { + } else if (*string == '-') { string++; sign = -1; } /* We don't want to recognise "P" as 0P, or .P as 0.0P... */ if ((!isdigit(*string) && *string != '.') || - ((*string == '.') && !isdigit(string[1]))) + ((*string == '.') && !isdigit(string[1]))) return (NULL); /* Now accumulate a number. Note ascii dependencies here... */ while (isdigit(*string)) mant = mant * 10.0 + (*string++ - '0'); - + /* Now maybe a decimal point. */ if (*string == '.') { string++; @@ -70,81 +72,83 @@ ft_numparse(char **s, bool whole) /* Now look for the scale factor or the exponent (can't have both). */ switch (*string) { - case 'e': - case 'E': - /* Parse another number. */ + case 'e': + case 'E': + /* Parse another number. */ + string++; + if (*string == '+') { + exsign = 1; string++; - if (*string == '+') { - exsign = 1; - string++; - } else if (*string == '-') { - exsign = -1; - string++; - } - while(isdigit(*string)) - expo = expo * 10.0 + (*string++ - '0'); - if (*string == '.') { - string++; - p = 1; - while (isdigit(*string)) - expo += (*string++ - '0') / power10(p++); - } - expo *= exsign; - break; - case 't': - case 'T': - expo = 12.0; + } else if (*string == '-') { + exsign = -1; string++; - break; - case 'g': - case 'G': - expo = 9.0; + } + while (isdigit(*string)) + expo = expo * 10.0 + (*string++ - '0'); + if (*string == '.') { string++; - break; - case 'k': - case 'K': - expo = 3.0; - string++; - break; - case 'u': - case 'U': + p = 1; + while (isdigit(*string)) + expo += (*string++ - '0') / power10(p++); + } + expo *= exsign; + break; + case 't': + case 'T': + expo = 12.0; + string++; + break; + case 'g': + case 'G': + expo = 9.0; + string++; + break; + case 'k': + case 'K': + expo = 3.0; + string++; + break; + case 'u': + case 'U': + expo = -6.0; + string++; + break; + case 'n': + case 'N': + expo = -9.0; + string++; + break; + case 'p': + case 'P': + expo = -12.0; + string++; + break; + case 'f': + case 'F': + expo = -15.0; + string++; + break; + case 'm': + case 'M': + /* Can be either m, mil, or meg. */ + if (string[1] && string[2] && + ((string[1] == 'e') || (string[1] == 'E')) && + ((string[2] == 'g') || (string[2] == 'G'))) + { + expo = 6.0; + string += 3; + } else if (string[1] && string[2] && + ((string[1] == 'i') || (string[1] == 'I')) && + ((string[2] == 'l') || (string[2] == 'L'))) + { expo = -6.0; + mant *= 25.4; + string += 3; + } else { + expo = -3.0; string++; - break; - case 'n': - case 'N': - expo = -9.0; - string++; - break; - case 'p': - case 'P': - expo = -12.0; - string++; - break; - case 'f': - case 'F': - expo = -15.0; - string++; - break; - case 'm': - case 'M': - /* Can be either m, mil, or meg. */ - if (string[1] && string[2] && - ((string[1] == 'e') || (string[1] == 'E')) && - ((string[2] == 'g') || (string[2] == 'G'))) { - expo = 6.0; - string += 3; - } else if (string[1] && string[2] && - ((string[1] == 'i') || (string[1] == 'I')) && - ((string[2] == 'l') || (string[2] == 'L'))) { - expo = -6.0; - mant *= 25.4; - string += 3; - } else { - expo = -3.0; - string++; - } - break; + } + break; } if (whole && *string != '\0') { diff --git a/src/frontend/parser/numparse.h b/src/frontend/parser/numparse.h index a69b24703..b2c8dfa1a 100644 --- a/src/frontend/parser/numparse.h +++ b/src/frontend/parser/numparse.h @@ -7,7 +7,4 @@ #define NUMPARSE_H_INCLUDED - - - #endif diff --git a/src/frontend/parser/unixcom.c b/src/frontend/parser/unixcom.c index bc0d473f4..17f10ad3b 100644 --- a/src/frontend/parser/unixcom.c +++ b/src/frontend/parser/unixcom.c @@ -48,7 +48,8 @@ struct hashent { char *h_name; char *h_path; struct hashent *h_next; -} ; +}; + #define HASHSIZE 256 @@ -56,6 +57,7 @@ static struct hashent *hashtab[HASHSIZE]; static char *dirbuffer; static int dirlength, dirpos; + /* Create the hash table for the given search path. pathlist is a : seperated * list of directories. If docc is TRUE, then all the commands found are * added to the command completion lists. @@ -79,23 +81,23 @@ cp_rehash(char *pathlist, bool docc) */ tfree(hh); } - hashtab[i] = NULL; + hashtab[i] = NULL; } while (pathlist && *pathlist) { /* Copy one path to buf. We have to make sure that the path * is a full path name. */ - if (*pathlist == '/') + if (*pathlist == '/') { i = 0; - else { + } else { #ifdef HAVE_GETWD (void) getwd(buf); #else -# ifdef HAVE_GETCWD +# ifdef HAVE_GETCWD (void) getcwd(buf, sizeof(buf)); # else - *buf = 0; + *buf = 0; # endif #endif i = strlen(buf); @@ -115,7 +117,7 @@ cp_rehash(char *pathlist, bool docc) (void) strcat(pbuf, entry->d_name); /* Now we could make sure that it is really an * executable, but that is too slow - * (as if "we" really cared). + * (as if "we" really cared). */ hh = alloc(struct hashent); hh->h_name = copy(entry->d_name); @@ -129,19 +131,21 @@ cp_rehash(char *pathlist, bool docc) while (ht->h_next) ht = ht->h_next; ht->h_next = hh; - } else + } else { hashtab[i] = hh; + } + if (docc) { /* Add to completion hash table. */ - cp_addcomm(entry->d_name, (long) 0, (long) 0, (long) 0, - (long) 0); + cp_addcomm(entry->d_name, (long) 0, (long) 0, (long) 0, (long) 0); } } - closedir(pdir); + closedir(pdir); } return; } + /* The return value is FALSE if no command was found, and TRUE if it was. */ bool @@ -165,16 +169,16 @@ cp_unixcom(wordlist *wl) if (strchr(name, '/')) return (tryexec(name, argv)); i = hash(name); - for (hh = hashtab[i]; hh; hh = hh->h_next) { + for (hh = hashtab[i]; hh; hh = hh->h_next) if (eq(name, hh->h_name)) { (void) sprintf(buf, "%s/%s", hh->h_path, hh->h_name); if (tryexec(buf, argv)) return (TRUE); } - } return (FALSE); } + static bool tryexec(char *name, char *argv[]) { @@ -183,33 +187,36 @@ tryexec(char *name, char *argv[]) # else union wait status; # endif - int pid, j; - RETSIGTYPE (*svint)( ), (*svquit)( ), (*svtstp)( ); - pid = vfork( ); + int pid, j; + RETSIGTYPE (*svint)(), (*svquit)(), (*svtstp)(); + + pid = vfork(); if (pid == 0) { - fixdescriptors(); + fixdescriptors(); (void) execv(name, argv); (void) _exit(120); /* A random value. */ /* NOTREACHED */ } else { - svint = signal(SIGINT, SIG_DFL); - svquit = signal(SIGQUIT, SIG_DFL); - svtstp = signal(SIGTSTP, SIG_DFL); + svint = signal(SIGINT, SIG_DFL); + svquit = signal(SIGQUIT, SIG_DFL); + svtstp = signal(SIGTSTP, SIG_DFL); do { j = wait(&status); } while (j != pid); - (void) signal(SIGINT, (SIGNAL_FUNCTION) svint); - (void) signal(SIGQUIT, (SIGNAL_FUNCTION) svquit); - (void) signal(SIGTSTP, (SIGNAL_FUNCTION) svtstp); + (void) signal(SIGINT, (SIGNAL_FUNCTION) svint); + (void) signal(SIGQUIT, (SIGNAL_FUNCTION) svquit); + (void) signal(SIGTSTP, (SIGNAL_FUNCTION) svtstp); } + if (WTERMSIG(status) == 0 && WEXITSTATUS(status) == 120) - /*if ((status.w_termsig == 0) && (status.w_retcode == 120)) */ - return (FALSE); + /*if ((status.w_termsig == 0) && (status.w_retcode == 120)) */ + return (FALSE); else - return (TRUE); + return (TRUE); } + static int hash(register char *str) { @@ -217,9 +224,11 @@ hash(register char *str) while (*str) i += *str++; + return (i % HASHSIZE); } + /* Debugging. */ void @@ -235,8 +244,10 @@ cp_hstat(void) return; } + #else + void cp_rehash(char *pathlist, bool docc) { @@ -244,6 +255,7 @@ cp_rehash(char *pathlist, bool docc) NG_IGNORE(pathlist); } + bool cp_unixcom(wordlist *wl) { @@ -253,7 +265,6 @@ cp_unixcom(wordlist *wl) return (FALSE); else return (TRUE); - } #endif diff --git a/src/frontend/parser/unixcom.h b/src/frontend/parser/unixcom.h index 734df53f4..707c6d86f 100644 --- a/src/frontend/parser/unixcom.h +++ b/src/frontend/parser/unixcom.h @@ -7,7 +7,4 @@ #define UNIXCOM_H_INCLUDED - - - #endif diff --git a/src/frontend/plotting/agraf.c b/src/frontend/plotting/agraf.c index 780e766f8..aff52c2a7 100644 --- a/src/frontend/plotting/agraf.c +++ b/src/frontend/plotting/agraf.c @@ -15,11 +15,11 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group #include "agraf.h" -#define FUDGE 7 -#define MARGIN_BASE 11 -#define LCHAR '.' -#define MCHAR 'X' -#define PCHARS "+*=$%!0123456789" +#define FUDGE 7 +#define MARGIN_BASE 11 +#define LCHAR '.' +#define MCHAR 'X' +#define PCHARS "+*=$%!0123456789" /* We should really deal with the xlog and delta arguments. This routine is * full of magic numbers that make the formatting correct. @@ -52,40 +52,43 @@ ft_agraf(double *xlims, double *ylims, struct dvec *xscale, struct plot *plot, s /* ANSI C does not specify how many digits are in an exponent for %c * We assumed it was 2. If it's more, shift starting position over. */ - sprintf(buf, "%1.1e", 0.0); /* expect 0.0e+00 */ + sprintf(buf, "%1.1e", 0.0); /* expect 0.0e+00 */ shift = (int) strlen(buf) - 7; margin += shift; /* Make sure the margin is correct */ omargin = margin; novalue = cp_getvar("noasciiplotvalue", CP_BOOL, NULL); - if (!novalue && - !vec_eq(xscale, vecs)) { + if (!novalue && !vec_eq(xscale, vecs)) margin *= 2; - } else + else novalue = TRUE; - if ((xscale->v_gridtype == GRID_YLOG) || - (xscale->v_gridtype == GRID_LOGLOG)) + + if ((xscale->v_gridtype == GRID_YLOG) || (xscale->v_gridtype == GRID_LOGLOG)) ylogscale = TRUE; - if (!cp_getvar("width", CP_NUM, &maxy)) { - maxy = DEF_WIDTH; - } + + if (!cp_getvar("width", CP_NUM, &maxy)) + maxy = DEF_WIDTH; + if (!cp_getvar("height", CP_NUM, &height)) height = DEF_HEIGHT; + if (ft_nopage) - nobreakp = TRUE; + nobreakp = TRUE; else - nobreakp = cp_getvar("nobreak", CP_BOOL, NULL); + nobreakp = cp_getvar("nobreak", CP_BOOL, NULL); + maxy -= (margin + FUDGE); maxx = xscale->v_length; + xrange[0] = xlims[0]; xrange[1] = xlims[1]; yrange[0] = ylims[0]; yrange[1] = ylims[1]; if (maxx < 2) { - fprintf(cp_err, - "Error: asciiplot can't handle scale with length < 2\n"); + fprintf(cp_err, + "Error: asciiplot can't handle scale with length < 2\n"); return; } @@ -94,16 +97,16 @@ ft_agraf(double *xlims, double *ylims, struct dvec *xscale, struct plot *plot, s return; } - for (v = vecs, i = 0; v; v = v->v_link2) { + for (v = vecs, i = 0; v; v = v->v_link2) v->v_linestyle = (PCHARS[i] ? PCHARS[i++] : '#'); - } + /* Now allocate the field and stuff. */ field = TMALLOC(char, (maxy + 1) * (maxx + 1)); line1 = TMALLOC(char, maxy + margin + FUDGE + 1); line2 = TMALLOC(char, maxy + margin + FUDGE + 1); if (!novalue) values = TMALLOC(double, maxx); - + /* Clear the field, put the lines in the right places, and create * the headers. */ @@ -117,8 +120,8 @@ ft_agraf(double *xlims, double *ylims, struct dvec *xscale, struct plot *plot, s /* The following is similar to the stuff in grid.c */ if ((xrange[0] > xrange[1]) || (yrange[0] > yrange[1])) { - fprintf(cp_err, - "ft_agraf: Internal Error: bad limits %g, %g, %g, %g\n", + fprintf(cp_err, + "ft_agraf: Internal Error: bad limits %g, %g, %g, %g\n", xrange[0], xrange[1], yrange[0], yrange[1]); return; } @@ -127,7 +130,7 @@ ft_agraf(double *xlims, double *ylims, struct dvec *xscale, struct plot *plot, s if (ylims[1] == 0.0) { mag = (int) floor(mylog10(- ylims[0])); tenpowmag = pow(10.0, (double) mag); - } else if (ylims[0] == 0.0) { + } else if (ylims[0] == 0.0) { mag = (int) floor(mylog10(ylims[1])); tenpowmag = pow(10.0, (double) mag); } else { @@ -144,17 +147,17 @@ ft_agraf(double *xlims, double *ylims, struct dvec *xscale, struct plot *plot, s dst = hmt - lmt; /* This is a strange case; I don't know why it's here. */ - if (dst == 11) + if (dst == 11) { dst = 12; - else if (dst == 1) { + } else if (dst == 1) { dst = 10; mag++; hmt *= 10; lmt *= 10; } else if (dst == 0) { dst = 2; - lmt -= 1; - hmt += 1; + lmt -= 1; + hmt += 1; } for (nsp = 4; nsp < 8; nsp++) @@ -176,7 +179,7 @@ ft_agraf(double *xlims, double *ylims, struct dvec *xscale, struct plot *plot, s line1[i + margin + 2 * shift] = '|'; (void) sprintf(buf, "%.2e", j * pow(10.0, (double) mag)); bcopy(buf, &line2[i + margin - ((j < 0) ? 2 : 1) - shift], - strlen(buf)); + strlen(buf)); } line1[i - spacing + margin + 1] = '\0'; @@ -184,8 +187,8 @@ ft_agraf(double *xlims, double *ylims, struct dvec *xscale, struct plot *plot, s line2[i] = xscale->v_name[i - 1]; if (!novalue) for (i = omargin + 1; - i < margin - 2 && (vecs->v_name[i - omargin - 1]); - i++) + i < margin - 2 && (vecs->v_name[i - omargin - 1]); + i++) line2[i] = vecs->v_name[i - omargin - 1]; /* Now the buffers are all set up properly. Plot points for each @@ -198,29 +201,29 @@ ft_agraf(double *xlims, double *ylims, struct dvec *xscale, struct plot *plot, s for (i = 0; i < maxx; i++) { if (nointerp) x = isreal(xscale) ? xscale->v_realdata[i] : - realpart(xscale->v_compdata[i]); + realpart(xscale->v_compdata[i]); else if (xlog && xrange[0] > 0.0 && xrange[1] > 0.0) - x = xrange[0] * pow( 10.0, mylog10(xrange[1]/xrange[0]) - * i / (maxx - 1)); + x = xrange[0] * pow(10.0, mylog10(xrange[1]/xrange[0]) + * i / (maxx - 1)); else x = xrange[0] + (xrange[1] - xrange[0]) * i / - (maxx - 1); + (maxx - 1); while ((isreal(xscale) ? (xscale->v_realdata[upper] < x) : (realpart(xscale->v_compdata[upper]) < x)) && - (upper < xscale->v_length - 1)) + (upper < xscale->v_length - 1)) upper++; while ((isreal(xscale) ? (xscale->v_realdata[lower] < x) : (realpart(xscale->v_compdata[lower]) < x)) && - (lower < xscale->v_length - 1)) + (lower < xscale->v_length - 1)) lower++; if ((isreal(xscale) ? (xscale->v_realdata[lower] > x) : - (realpart(xscale->v_compdata[lower]) > x)) && - (lower > 0)) + (realpart(xscale->v_compdata[lower]) > x)) && + (lower > 0)) lower--; x1 = (isreal(xscale) ? xscale->v_realdata[lower] : - realpart(xscale->v_compdata[lower])); + realpart(xscale->v_compdata[lower])); x2 = (isreal(xscale) ? xscale->v_realdata[upper] : - realpart(xscale->v_compdata[upper])); + realpart(xscale->v_compdata[upper])); if (x1 > x2) { fprintf(cp_err, "Error: X scale (%s) not monotonic\n", xscale->v_name); @@ -228,9 +231,9 @@ ft_agraf(double *xlims, double *ylims, struct dvec *xscale, struct plot *plot, s } for (v = vecs; v; v = v->v_link2) { yy1 = (isreal(v) ? v->v_realdata[lower] : - realpart(v->v_compdata[lower])); + realpart(v->v_compdata[lower])); y2 = (isreal(v) ? v->v_realdata[upper] : - realpart(v->v_compdata[upper])); + realpart(v->v_compdata[upper])); if (x1 == x2) y = yy1; else @@ -245,7 +248,7 @@ ft_agraf(double *xlims, double *ylims, struct dvec *xscale, struct plot *plot, s field[omaxy * i + ypt] = MCHAR; } } - + out_init(); for (i = 0; i < omaxy + margin; i++) out_send("-"); @@ -268,8 +271,10 @@ ft_agraf(double *xlims, double *ylims, struct dvec *xscale, struct plot *plot, s out_send("Legend: "); i = 0; j = (maxx + margin - 8) / 20; + if (j == 0) j = 1; + for (v = vecs; v; v = v->v_link2) { out_printf("%c = %-17s", (char) v->v_linestyle, v->v_name); if (!(++i % j) && v->v_link2) { @@ -278,45 +283,49 @@ ft_agraf(double *xlims, double *ylims, struct dvec *xscale, struct plot *plot, s } } out_send("\n"); + for (i = 0; i < omaxy + margin; i++) out_send("-"); out_send("\n"); i = 0; out_printf("%s\n%s\n", line2, line1); curline += 2; + for (i = 0; i < maxx; i++) { if (nointerp) - x = isreal(xscale) ? xscale->v_realdata[i] : + x = isreal(xscale) ? xscale->v_realdata[i] : realpart(xscale->v_compdata[i]); else if (xlog && xrange[0] > 0.0 && xrange[1] > 0.0) - x = xrange[0] * pow( 10.0, mylog10(xrange[1]/xrange[0]) - * i / (maxx - 1)); - else - x = xrange[0] + (xrange[1] - xrange[0]) * i / (maxx - 1); - if (x < 0.0) { + x = xrange[0] * pow(10.0, mylog10(xrange[1]/xrange[0]) + * i / (maxx - 1)); + else + x = xrange[0] + (xrange[1] - xrange[0]) * i / (maxx - 1); + + if (x < 0.0) out_printf("%.3e ", x); - } else { + else out_printf(" %.3e ", x); - } + if (!novalue) { - if (values[i] < 0.0) { + if (values[i] < 0.0) out_printf("%.3e ", values[i]); - } else { + else out_printf(" %.3e ", values[i]); - } } + cb = field[(i + 1) * omaxy]; field[(i + 1) * omaxy] = '\0'; out_send(&field[i * omaxy]); field[(i + 1) * omaxy] = cb; out_send("\n"); - if (((curline++ % height) == 0) && (i < maxx - 1) && - !nobreakp) { - out_printf("%s\n%s\n\014\n%s\n%s\n", line1, line2, - line2, line1); + + if (((curline++ % height) == 0) && (i < maxx - 1) && !nobreakp) { + out_printf("%s\n%s\n\014\n%s\n%s\n", + line1, line2, line2, line1); curline += 5; } } + out_printf("%s\n%s\n", line1, line2); tfree(field); @@ -324,5 +333,6 @@ ft_agraf(double *xlims, double *ylims, struct dvec *xscale, struct plot *plot, s tfree(line2); if (!novalue) tfree(values); + return; } diff --git a/src/frontend/plotting/agraf.h b/src/frontend/plotting/agraf.h index 409e46988..e7b9f1904 100644 --- a/src/frontend/plotting/agraf.h +++ b/src/frontend/plotting/agraf.h @@ -11,8 +11,8 @@ #include "ngspice/plot.h" void ft_agraf(double *xlims, double *ylims, struct dvec *xscale, - struct plot *plot, struct dvec *vecs, - double xdel, double ydel, bool xlog, bool ylog, - bool nointerp); + struct plot *plot, struct dvec *vecs, + double xdel, double ydel, bool xlog, bool ylog, + bool nointerp); #endif diff --git a/src/frontend/plotting/clip.c b/src/frontend/plotting/clip.c index 64f4379f2..82310e3cc 100644 --- a/src/frontend/plotting/clip.c +++ b/src/frontend/plotting/clip.c @@ -58,10 +58,11 @@ clip_line(int *pX1, int *pY1, int *pX2, int *pY2, int l, int b, int r, int t) int x2 = *pX2; int y2 = *pY2; int x = 0, y = 0; - int c,c1,c2; + int c, c1, c2; + + CODE(x1, y1, c1); + CODE(x2, y2, c2); - CODE(x1,y1,c1); - CODE(x2,y2,c2); while (c1 || c2) { if (c1 & c2) return (TRUE); /* Line is invisible. */ @@ -83,11 +84,11 @@ clip_line(int *pX1, int *pY1, int *pX2, int *pY2, int l, int b, int r, int t) if (c == c1) { x1 = x; y1 = y; - CODE(x,y,c1); + CODE(x, y, c1); } else { x2 = x; - y2 = y; - CODE(x,y,c2); + y2 = y; + CODE(x, y, c2); } } *pX1 = x1; @@ -97,6 +98,7 @@ clip_line(int *pX1, int *pY1, int *pX2, int *pY2, int l, int b, int r, int t) return (FALSE); /* Line is at least partially visible.*/ } + /* This routine will clip a line to a circle, returning TRUE if the line * is entirely outside the circle. Note that we have to be careful not * to switch the points around, since in grid.c we need to know which is @@ -115,13 +117,13 @@ clip_to_circle(int *x1, int *y1, int *x2, int *y2, int cx, int cy, int rad) /* Get the angles between the origin and the endpoints. */ if ((*x1-cx) || (*y1-cy)) - theta1 = atan2((double) *y1 - cy, (double) *x1 - cx); + theta1 = atan2((double) *y1 - cy, (double) *x1 - cx); else - theta1 = M_PI; + theta1 = M_PI; if ((*x2-cx) || (*y2-cy)) - theta2 = atan2((double) *y2 - cy, (double) *x2 - cx); + theta2 = atan2((double) *y2 - cy, (double) *x2 - cx); else - theta2 = M_PI; + theta2 = M_PI; if (theta1 < 0.0) theta1 = 2 * M_PI + theta1; @@ -152,8 +154,7 @@ clip_to_circle(int *x1, int *y1, int *x2, int *y2, int cx, int cy, int rad) /* Figure out the distances between the points */ a = sqrt((double) ((*x1 - cx) * (*x1 - cx) + (*y1 - cy) * (*y1 - cy))); b = sqrt((double) ((*x2 - cx) * (*x2 - cx) + (*y2 - cy) * (*y2 - cy))); - c = sqrt((double) ((*x1 - *x2) * (*x1 - *x2) + - (*y1 - *y2) * (*y1 - *y2))); + c = sqrt((double) ((*x1 - *x2) * (*x1 - *x2) + (*y1 - *y2) * (*y1 - *y2))); /* We have three cases now -- either the midpoint of the line is * closest to the origon, or point 1 or point 2 is. Actually the @@ -198,6 +199,7 @@ clip_to_circle(int *x1, int *y1, int *x2, int *y2, int cx, int cy, int rad) *x1 = (int)(cx + rad * cos(theta1 + beta)); *y1 = (int)(cy + rad * sin(theta1 + beta)); } + if (b > rad) { tt = (c * c + b * b - a * a) / (2 * b * c); if (tt > 1.0) @@ -212,6 +214,7 @@ clip_to_circle(int *x1, int *y1, int *x2, int *y2, int cx, int cy, int rad) *x2 = (int)(cx + rad * cos(theta2 - beta)); *y2 = (int)(cy + rad * sin(theta2 - beta)); } + if (flip) { i = *x1; *x1 = *x2; @@ -220,5 +223,6 @@ clip_to_circle(int *x1, int *y1, int *x2, int *y2, int cx, int cy, int rad) *y1 = *y2; *y2 = i; } + return (FALSE); } diff --git a/src/frontend/plotting/gnuplot.c b/src/frontend/plotting/gnuplot.c index 5eb3e6e47..c4baabeda 100644 --- a/src/frontend/plotting/gnuplot.c +++ b/src/frontend/plotting/gnuplot.c @@ -20,10 +20,10 @@ #define GP_MAXVECTORS 64 + void ft_gnuplot(double *xlims, double *ylims, char *filename, char *title, char *xlabel, char *ylabel, GRIDTYPE gridtype, PLOTTYPE plottype, struct dvec *vecs) { - FILE *file, *file_data; struct dvec *v, *scale = NULL; double xval, yval; @@ -38,13 +38,13 @@ ft_gnuplot(double *xlims, double *ylims, char *filename, char *title, char *xlab sprintf(filename_plt, "%s.plt", filename); /* Sanity checking. */ - for ( v = vecs, numVecs = 0; v; v = v->v_link2 ) { + for (v = vecs, numVecs = 0; v; v = v->v_link2) numVecs++; - } + if (numVecs == 0) { return; } else if (numVecs > GP_MAXVECTORS) { - fprintf( cp_err, "Error: too many vectors for gnuplot.\n" ); + fprintf(cp_err, "Error: too many vectors for gnuplot.\n"); return; } if (!cp_getvar("xbrushwidth", CP_NUM, &linewidth)) @@ -54,11 +54,10 @@ ft_gnuplot(double *xlims, double *ylims, char *filename, char *title, char *xlab if (!cp_getvar("pointstyle", CP_STRING, pointstyle)) { markers = FALSE; } else { - if (cieq(pointstyle,"markers")) { + if (cieq(pointstyle,"markers")) markers = TRUE; - } else { + else markers = FALSE; - } } @@ -84,7 +83,7 @@ ft_gnuplot(double *xlims, double *ylims, char *filename, char *title, char *xlab xlog = ylog = FALSE; break; default: - fprintf( cp_err, "Error: grid type unsupported by gnuplot.\n" ); + fprintf(cp_err, "Error: grid type unsupported by gnuplot.\n"); return; } @@ -97,63 +96,59 @@ ft_gnuplot(double *xlims, double *ylims, char *filename, char *title, char *xlab /* Set up the file header. */ if (title) { text = cp_unquote(title); - fprintf( file, "set title \"%s\"\n", text ); + fprintf(file, "set title \"%s\"\n", text); tfree(text); } if (xlabel) { text = cp_unquote(xlabel); - fprintf( file, "set xlabel \"%s\"\n", text ); + fprintf(file, "set xlabel \"%s\"\n", text); tfree(text); } if (ylabel) { text = cp_unquote(ylabel); - fprintf( file, "set ylabel \"%s\"\n", text ); + fprintf(file, "set ylabel \"%s\"\n", text); tfree(text); } if (!nogrid) { if (linewidth > 1) - fprintf( file, "set grid lw %d \n" , linewidth ); + fprintf(file, "set grid lw %d \n" , linewidth); else - fprintf( file, "set grid\n" ); + fprintf(file, "set grid\n"); } if (xlog) { - fprintf( file, "set logscale x\n" ); - if (xlims) { - fprintf( file, "set xrange [%e:%e]\n", xlims[0], xlims[1] ); - } + fprintf(file, "set logscale x\n"); + if (xlims) + fprintf(file, "set xrange [%e:%e]\n", xlims[0], xlims[1]); } else { - fprintf( file, "unset logscale x \n" ); - if (xlims) { - fprintf( file, "set xrange [%e:%e]\n", xlims[0], xlims[1] ); - } + fprintf(file, "unset logscale x \n"); + if (xlims) + fprintf(file, "set xrange [%e:%e]\n", xlims[0], xlims[1]); } if (ylog) { - fprintf( file, "set logscale y \n" ); - if (ylims) { - fprintf( file, "set yrange [%e:%e]\n", ylims[0], ylims[1] ); - } + fprintf(file, "set logscale y \n"); + if (ylims) + fprintf(file, "set yrange [%e:%e]\n", ylims[0], ylims[1]); } else { - fprintf( file, "unset logscale y \n" ); - if (ylims) { - fprintf( file, "set yrange [%e:%e]\n", ylims[0], ylims[1] ); - } + fprintf(file, "unset logscale y \n"); + if (ylims) + fprintf(file, "set yrange [%e:%e]\n", ylims[0], ylims[1]); } - fprintf( file, "#set xtics 1\n" ); - fprintf( file, "#set x2tics 1\n" ); - fprintf( file, "#set ytics 1\n" ); - fprintf( file, "#set y2tics 1\n" ); + fprintf(file, "#set xtics 1\n"); + fprintf(file, "#set x2tics 1\n"); + fprintf(file, "#set ytics 1\n"); + fprintf(file, "#set y2tics 1\n"); if (linewidth > 1) - fprintf( file, "set border lw %d\n", linewidth ); + fprintf(file, "set border lw %d\n", linewidth); if (plottype == PLOT_COMB) { strcpy(plotstyle, "boxes"); } else if (plottype == PLOT_POINT) { if (markers) { -// fprintf( file, "Markers: True\n" ); + // fprintf(file, "Markers: True\n"); } else { -// fprintf( file, "LargePixels: True\n" ); + // fprintf(file, "LargePixels: True\n"); } strcpy(plotstyle, "points"); } else { @@ -166,11 +161,11 @@ ft_gnuplot(double *xlims, double *ylims, char *filename, char *title, char *xlab return; } - fprintf( file, "plot " ); + fprintf(file, "plot "); i = 0; /* Write out the gnuplot command */ - for ( v = vecs; v; v = v->v_link2 ) { + for (v = vecs; v; v = v->v_link2) { scale = v->v_scale; if (v->v_name) { i = i + 2; @@ -179,19 +174,19 @@ ft_gnuplot(double *xlims, double *ylims, char *filename, char *title, char *xlab filename_data, i-1, i, plotstyle, linewidth, v->v_name); } } - fprintf( file, "\n"); - fprintf (file, "set terminal push\n"); - fprintf (file, "set terminal postscript eps color\n"); - fprintf (file, "set out \'%s.eps\'\n", filename); - fprintf (file, "replot\n"); - fprintf (file, "set term pop\n"); - fprintf (file, "replot\n"); + fprintf(file, "\n"); + fprintf(file, "set terminal push\n"); + fprintf(file, "set terminal postscript eps color\n"); + fprintf(file, "set out \'%s.eps\'\n", filename); + fprintf(file, "replot\n"); + fprintf(file, "set term pop\n"); + fprintf(file, "replot\n"); - (void) fclose( file ); + (void) fclose(file); /* Write out the data and setup arrays */ - for ( i = 0; i < scale->v_length; i++ ) { - for ( v = vecs; v; v = v->v_link2 ) { + for (i = 0; i < scale->v_length; i++) { + for (v = vecs; v; v = v->v_link2) { scale = v->v_scale; xval = isreal(scale) ? @@ -200,35 +195,34 @@ ft_gnuplot(double *xlims, double *ylims, char *filename, char *title, char *xlab yval = isreal(v) ? v->v_realdata[i] : realpart(v->v_compdata[i]); - fprintf( file_data, "% e % e ", xval, yval ); + fprintf(file_data, "% e % e ", xval, yval); } - fprintf( file_data, "\n"); + fprintf(file_data, "\n"); } - (void) fclose( file_data ); + (void) fclose(file_data); #if defined(__MINGW32__) || defined(_MSC_VER) /* for external fcn system() */ -// (void) sprintf( buf, "start /B wgnuplot %s -" , filename_plt ); - (void) sprintf( buf, "start /B wgnuplot -persist %s " , filename_plt ); + // (void) sprintf(buf, "start /B wgnuplot %s -" , filename_plt); + (void) sprintf(buf, "start /B wgnuplot -persist %s " , filename_plt); _flushall(); #else /* for external fcn system() from LINUX environment */ - (void) sprintf( buf, "xterm -e gnuplot %s - &", filename_plt ); + (void) sprintf(buf, "xterm -e gnuplot %s - &", filename_plt); #endif - err = system( buf ); - + err = system(buf); return; } + /* simple printout of data into a file, similar to data table in ft_gnuplot command: wrsimple file vecs */ void ft_writesimple(double *xlims, double *ylims, char *filename, char *title, char *xlabel, char *ylabel, GRIDTYPE gridtype, PLOTTYPE plottype, struct dvec *vecs) { - FILE *file_data; struct dvec *v, *scale = NULL; double xval; @@ -249,12 +243,11 @@ ft_writesimple(double *xlims, double *ylims, char *filename, char *title, char * appendwrite = cp_getvar("appendwrite", CP_BOOL, NULL); /* Sanity checking. */ - for ( v = vecs, numVecs = 0; v; v = v->v_link2 ) { + for (v = vecs, numVecs = 0; v; v = v->v_link2) numVecs++; - } - if (numVecs == 0) { + + if (numVecs == 0) return; - } /* Open the output data file. */ if ((file_data = fopen(filename_data, appendwrite ? "a" : "w")) == NULL) { @@ -263,27 +256,26 @@ ft_writesimple(double *xlims, double *ylims, char *filename, char *title, char * } i = 0; - for ( v = vecs; v; v = v->v_link2 ) { + for (v = vecs; v; v = v->v_link2) scale = v->v_scale; - } /* Write out the data as simple arrays */ - for ( i = 0; i < scale->v_length; i++ ) { - for ( v = vecs; v; v = v->v_link2 ) { + for (i = 0; i < scale->v_length; i++) { + for (v = vecs; v; v = v->v_link2) { scale = v->v_scale; xval = isreal(scale) ? scale->v_realdata[i] : realpart(scale->v_compdata[i]); if (isreal(v)) - fprintf( file_data, "% e % e ", xval, v->v_realdata[i] ); + fprintf(file_data, "% e % e ", xval, v->v_realdata[i]); else - fprintf( file_data, "% e % e % e ", xval, realpart(v->v_compdata[i]), imagpart(v->v_compdata[i]) ); + fprintf(file_data, "% e % e % e ", xval, realpart(v->v_compdata[i]), imagpart(v->v_compdata[i])); } - fprintf( file_data, "\n"); + fprintf(file_data, "\n"); } - (void) fclose( file_data ); + (void) fclose(file_data); return; } diff --git a/src/frontend/plotting/gnuplot.h b/src/frontend/plotting/gnuplot.h index 30c5f0033..4ce93eda1 100644 --- a/src/frontend/plotting/gnuplot.h +++ b/src/frontend/plotting/gnuplot.h @@ -6,14 +6,13 @@ #ifndef GNUPLOT_H_INCLUDED #define GNUPLOT_H_INCLUDED -void ft_gnuplot(double *xlims, double *ylims, char *filename, char *title, - char *xlabel, char *ylabel, GRIDTYPE gridtype, PLOTTYPE plottype, - struct dvec *vecs); +void ft_gnuplot(double *xlims, double *ylims, char *filename, char *title, + char *xlabel, char *ylabel, GRIDTYPE gridtype, PLOTTYPE plottype, + struct dvec *vecs); -void ft_writesimple(double *xlims, double *ylims, char *filename, char *title, - char *xlabel, char *ylabel, GRIDTYPE gridtype, PLOTTYPE plottype, - struct dvec *vecs); - +void ft_writesimple(double *xlims, double *ylims, char *filename, char *title, + char *xlabel, char *ylabel, GRIDTYPE gridtype, PLOTTYPE plottype, + struct dvec *vecs); #endif diff --git a/src/frontend/plotting/graf.c b/src/frontend/plotting/graf.c index 5339136c6..6ded83487 100644 --- a/src/frontend/plotting/graf.c +++ b/src/frontend/plotting/graf.c @@ -10,12 +10,12 @@ Author: 1988 Jeffrey M. Hsu */ #include "ngspice/ngspice.h" -#include "ngspice/cpdefs.h" /* for CP_ */ +#include "ngspice/cpdefs.h" /* for CP_ */ #include "ngspice/cpextern.h" #include "ngspice/plot.h" -#include "ngspice/ftedebug.h" /* for iplot */ -#include "ngspice/dvec.h" /* for struct dvec */ -#include "ngspice/ftedefs.h" /* for FTEextern.h and IPOINT{MIN,MAX} */ +#include "ngspice/ftedebug.h" /* for iplot */ +#include "ngspice/dvec.h" /* for struct dvec */ +#include "ngspice/ftedefs.h" /* for FTEextern.h and IPOINT{MIN,MAX} */ #include "ngspice/fteinput.h" #include "ngspice/graph.h" #include "ngspice/ftedbgra.h" @@ -29,11 +29,11 @@ Author: 1988 Jeffrey M. Hsu #include "../display.h" #include "../runcoms.h" -/* static declarations */ + static void gr_start_internal(struct dvec *dv, bool copyvec); static int iplot(struct plot *pl, int id); static void set(struct plot *plot, struct dbcomm *db, bool unset, short mode); -static char * getitright(char *buf, double num); +static char *getitright(char *buf, double num); /* for legends, set in gr_start, reset in gr_iplot and gr_init */ static int plotno; @@ -54,6 +54,7 @@ static char *ticlist = ticbuf; #define XFACTOR 1 /* How much to expand the X scale during iplot. */ #define YFACTOR 0.2 /* How much to expand the Y scale during iplot. */ + /* * Start of a new graph. * Fill in the data that gets displayed. @@ -65,63 +66,61 @@ static char *ticlist = ticbuf; int gr_init(double *xlims, double *ylims, /* The size of the screen. */ - char *xname, char *plotname, /* What to label things. */ - char *hcopy, /* The raster file. */ - int nplots, /* How many plots there will be. */ - double xdelta, double ydelta, /* Line increments for the scale. */ - GRIDTYPE gridtype, /* The grid type */ - PLOTTYPE plottype, /* and the plot type. */ - char *xlabel, char *ylabel, /* Labels for axes. */ - int xtype, int ytype, /* The types of the data graphed. */ - char *pname, - char *commandline) /* For xi_zoomdata() */ + char *xname, char *plotname, /* What to label things. */ + char *hcopy, /* The raster file. */ + int nplots, /* How many plots there will be. */ + double xdelta, double ydelta, /* Line increments for the scale. */ + GRIDTYPE gridtype, /* The grid type */ + PLOTTYPE plottype, /* and the plot type. */ + char *xlabel, char *ylabel, /* Labels for axes. */ + int xtype, int ytype, /* The types of the data graphed. */ + char *pname, + char *commandline) /* For xi_zoomdata() */ { - GRAPH *graph; wordlist *wl; char *comb_title; NG_IGNORE(nplots); - if ((graph = NewGraph()) == NULL) { - return(FALSE); - } + if ((graph = NewGraph()) == NULL) + return (FALSE); - /* - The global currentgraph will always be the current graph. + /* + The global currentgraph will always be the current graph. */ SetGraphContext(graph->graphid); graph->onevalue = (xname ? FALSE : TRUE); /* communicate filename to plot 5 driver */ - if (hcopy) { - graph->devdep = hcopy; - } + if (hcopy) + graph->devdep = hcopy; plotno = 0; /* note: should do only once, maybe in gr_init_once */ if (!cp_getvar("pointchars", CP_STRING, pointchars)) - (void) strcpy(pointchars, DEFPOINTCHARS); + (void) strcpy(pointchars, DEFPOINTCHARS); if (!cp_getvar("ticmarks", CP_NUM, &graph->ticmarks)) { - if (cp_getvar("ticmarks", CP_BOOL, NULL)) - graph->ticmarks = 10; - else - graph->ticmarks = 0; + if (cp_getvar("ticmarks", CP_BOOL, NULL)) + graph->ticmarks = 10; + else + graph->ticmarks = 0; } if (cp_getvar("ticlist", CP_LIST, ticlist)) { - wl = vareval("ticlist"); - ticlist = wl_flatten(wl); - graph->ticdata = readtics(ticlist); - } else - graph->ticdata = NULL; + wl = vareval("ticlist"); + ticlist = wl_flatten(wl); + graph->ticdata = readtics(ticlist); + } else { + graph->ticdata = NULL; + } if (!xlims || !ylims) { - internalerror("gr_init: no range specified"); - return(FALSE); + internalerror("gr_init: no range specified"); + return (FALSE); } /* save upper and lower limits */ @@ -129,27 +128,29 @@ gr_init(double *xlims, double *ylims, /* The size of the screen. */ graph->data.xmax = xlims[1]; graph->data.ymin = ylims[0]; graph->data.ymax = ylims[1]; -/* get title into plot window */ + + /* get title into plot window */ if (!pname) - pname = "(unknown)"; + pname = "(unknown)"; if (!plotname) - plotname = "(unknown)"; + plotname = "(unknown)"; + comb_title = TMALLOC(char, strlen(plotname) + strlen(pname) + 3); sprintf(comb_title, "%s: %s", pname, plotname); graph->plotname = comb_title; /* note: have enum here or some better convention */ if (NewViewport(graph) == 1) { - /* note: where is the error message generated? */ - /* note: undo tmallocs */ - fprintf(cp_err, "Can't open viewport for graphics.\n"); - return(FALSE); + /* note: where is the error message generated? */ + /* note: undo tmallocs */ + fprintf(cp_err, "Can't open viewport for graphics.\n"); + return (FALSE); } /* layout decisions */ /* note: have to do before gr_fixgrid and after NewViewport */ - graph->viewportxoff = graph->fontwidth * 8; /* 8 lines on left */ - graph->viewportyoff = graph->fontheight * 4; /* 4 on bottom */ + graph->viewportxoff = graph->fontwidth * 8; /* 8 lines on left */ + graph->viewportyoff = graph->fontheight * 4; /* 4 on bottom */ DevClear(); @@ -163,25 +164,23 @@ gr_init(double *xlims, double *ylims, /* The size of the screen. */ graph->grid.xsized = 0; if (!graph->onevalue) { - if (xlabel) { + if (xlabel) graph->grid.xlabel = xlabel; - } else { + else graph->grid.xlabel = xname; - } - if (ylabel) { + + if (ylabel) graph->grid.ylabel = ylabel; - } } else { - if (xlabel) { + if (xlabel) graph->grid.xlabel = xlabel; - } else { + else graph->grid.xlabel = "real"; - } - if (ylabel) { + + if (ylabel) graph->grid.ylabel = ylabel; - } else { + else graph->grid.ylabel = "imag"; - } } gr_resize_internal(graph); @@ -192,20 +191,23 @@ gr_init(double *xlims, double *ylims, /* The size of the screen. */ curlst = 0; /* Use the same one all the time. */ else curlst = 1; + /* XXX Special exception for SMITH */ - if (dispdev->numcolors > 2 && (graph->grid.gridtype == GRID_SMITH - || graph->grid.gridtype == GRID_SMITHGRID)) + if (dispdev->numcolors > 2 && + (graph->grid.gridtype == GRID_SMITH || + graph->grid.gridtype == GRID_SMITHGRID)) { curcolor = 3; - } else + } else { curcolor = 1; + } graph->commandline = copy(commandline); - return(TRUE); - + return (TRUE); } + /* * Add a point to the curve we're currently drawing. * Should be in between a gr_init() and a gr_end() @@ -219,9 +221,9 @@ gr_init(double *xlims, double *ylims, /* The size of the screen. */ */ void gr_point(struct dvec *dv, - double newx, double newy, - double oldx, double oldy, - int np) + double newx, double newy, + double oldx, double oldy, + int np) { int oldtox, oldtoy; /* value before clipping */ @@ -236,115 +238,117 @@ gr_point(struct dvec *dv, /* note: we do not particularly want to clip here */ oldtox = tox; oldtoy = toy; if (!currentgraph->grid.circular) { - if (clip_line(&fromx, &fromy, &tox, &toy, - currentgraph->viewportxoff, currentgraph->viewportyoff, - currentgraph->viewport.width + currentgraph->viewportxoff, - currentgraph->viewport.height + currentgraph->viewportyoff)) - return; + if (clip_line(&fromx, &fromy, &tox, &toy, + currentgraph->viewportxoff, currentgraph->viewportyoff, + currentgraph->viewport.width + currentgraph->viewportxoff, + currentgraph->viewport.height + currentgraph->viewportyoff)) + return; } else { - if (clip_to_circle(&fromx, &fromy, &tox, &toy, - currentgraph->grid.xaxis.circular.center, - currentgraph->grid.yaxis.circular.center, - currentgraph->grid.xaxis.circular.radius)) - return; + if (clip_to_circle(&fromx, &fromy, &tox, &toy, + currentgraph->grid.xaxis.circular.center, + currentgraph->grid.yaxis.circular.center, + currentgraph->grid.xaxis.circular.radius)) + return; } if (currentgraph->plottype != PLOT_POINT) { - SetLinestyle(dv->v_linestyle); + SetLinestyle(dv->v_linestyle); } else { - /* if PLOT_POINT, + /* if PLOT_POINT, don't want to plot an endpoint which have been clipped */ - if (tox != oldtox || toy != oldtoy) - return; + if (tox != oldtox || toy != oldtoy) + return; } SetColor(dv->v_color); switch (currentgraph->plottype) { - double *tics; - case PLOT_LIN: + double *tics; + case PLOT_LIN: - /* If it's a linear plot, ignore first point since we don't - want to connect with oldx and oldy. */ - if (np) - DevDrawLine(fromx, fromy, tox, toy); - if ((tics = (double *) currentgraph->ticdata) != NULL) { - for (; *tics < HUGE; tics++) { - if (*tics == (double) np) { - DevDrawText("x", (int) (tox - currentgraph->fontwidth / 2), - (int) (toy - currentgraph->fontheight / 2)); - /* gr_redraw will redraw this w/o our having to save it - Guenther Roehrich 22-Jan-99 */ - /* SaveText(currentgraph, "x", - (int) (tox - currentgraph->fontwidth / 2), - (int) (toy - currentgraph->fontheight / 2)); */ - break; - } - } - } else if ((currentgraph->ticmarks >0) && (np > 0) - && (np % currentgraph->ticmarks == 0)) - { - /* Draw an 'x' */ - DevDrawText("x", (int) (tox - currentgraph->fontwidth / 2), - (int) (toy - currentgraph->fontheight / 2)); - /* gr_redraw will redraw this w/o our having to save it - Guenther Roehrich 22-Jan-99 */ - /* SaveText(currentgraph, "x", - (int) (tox - currentgraph->fontwidth / 2), - (int) (toy - currentgraph->fontheight / 2)); */ - } + /* If it's a linear plot, ignore first point since we don't + want to connect with oldx and oldy. */ + if (np) + DevDrawLine(fromx, fromy, tox, toy); + if ((tics = (double *) currentgraph->ticdata) != NULL) { + for (; *tics < HUGE; tics++) + if (*tics == (double) np) { + DevDrawText("x", (int) (tox - currentgraph->fontwidth / 2), + (int) (toy - currentgraph->fontheight / 2)); + /* gr_redraw will redraw this w/o our having to save it + Guenther Roehrich 22-Jan-99 */ + /* SaveText(currentgraph, "x", + (int) (tox - currentgraph->fontwidth / 2), + (int) (toy - currentgraph->fontheight / 2)); */ + break; + } + } else if ((currentgraph->ticmarks >0) && (np > 0) && + (np % currentgraph->ticmarks == 0)) + { + /* Draw an 'x' */ + DevDrawText("x", (int) (tox - currentgraph->fontwidth / 2), + (int) (toy - currentgraph->fontheight / 2)); + /* gr_redraw will redraw this w/o our having to save it + Guenther Roehrich 22-Jan-99 */ + /* SaveText(currentgraph, "x", + (int) (tox - currentgraph->fontwidth / 2), + (int) (toy - currentgraph->fontheight / 2)); */ + } break; - case PLOT_COMB: + case PLOT_COMB: DatatoScreen(currentgraph, - 0.0, currentgraph->datawindow.ymin, - &dummy, &ymin); + 0.0, currentgraph->datawindow.ymin, + &dummy, &ymin); DevDrawLine(tox, ymin, tox, toy); break; - case PLOT_POINT: + case PLOT_POINT: /* Here, gi_linestyle is the character used for the point. */ pointc[0] = (char) dv->v_linestyle; pointc[1] = '\0'; DevDrawText(pointc, (int) (tox - currentgraph->fontwidth / 2), - (int) (toy - currentgraph->fontheight / 2)); - default: + (int) (toy - currentgraph->fontheight / 2)); + default: break; } - } + static void gr_start_internal(struct dvec *dv, bool copyvec) { - struct dveclist *link; char *s; /* Do something special with poles and zeros. Poles are 'x's, and * zeros are 'o's. */ s = ft_typenames(dv->v_type); - if (eq(s, "pole")) { - dv->v_linestyle = 'x'; - return; - } else if (eq(s, "zero")) { - dv->v_linestyle = 'o'; - return; - } + if (eq(s, "pole")) { + dv->v_linestyle = 'x'; + return; + } else if (eq(s, "zero")) { + dv->v_linestyle = 'o'; + return; + } /* Find a (hopefully) new line style and color. */ if (currentgraph->plottype == PLOT_POINT) { - if (pointchars[curlst - 1]) - curlst++; - else - curlst = 2; - } else if ((curlst > 0) && (++curlst == dispdev->numlinestyles)) - curlst = 2; + if (pointchars[curlst - 1]) + curlst++; + else + curlst = 2; + } else if ((curlst > 0) && (++curlst == dispdev->numlinestyles)) { + curlst = 2; + } + if ((curcolor > 0) && (++curcolor == dispdev->numcolors)) - curcolor = (((currentgraph->grid.gridtype == GRID_SMITH - || currentgraph->grid.gridtype == GRID_SMITHGRID) && - (dispdev->numcolors > 3)) ? 4 : 2); + curcolor = (((currentgraph->grid.gridtype == GRID_SMITH || + currentgraph->grid.gridtype == GRID_SMITHGRID) && + (dispdev->numcolors > 3)) ? 4 : 2); + if (currentgraph->plottype == PLOT_POINT) - dv->v_linestyle = pointchars[curlst - 2]; + dv->v_linestyle = pointchars[curlst - 2]; else - dv->v_linestyle = curlst; + dv->v_linestyle = curlst; + dv->v_color = curcolor; /* save the data so we can refresh */ @@ -352,13 +356,13 @@ gr_start_internal(struct dvec *dv, bool copyvec) link->next = currentgraph->plotdata; if (copyvec) { - link->vector = vec_copy(dv); - /* vec_copy doesn't set v_color or v_linestyle */ - link->vector->v_color = dv->v_color; - link->vector->v_linestyle = dv->v_linestyle; - link->vector->v_flags |= VF_PERMANENT; + link->vector = vec_copy(dv); + /* vec_copy doesn't set v_color or v_linestyle */ + link->vector->v_color = dv->v_color; + link->vector->v_linestyle = dv->v_linestyle; + link->vector->v_flags |= VF_PERMANENT; } else { - link->vector = dv; + link->vector = dv; } currentgraph->plotdata = link; @@ -367,66 +371,62 @@ gr_start_internal(struct dvec *dv, bool copyvec) drawlegend(currentgraph, plotno, dv); plotno++; - } + /* start one plot of a graph */ void gr_start(struct dvec *dv) { - gr_start_internal(dv, TRUE); - } + /* make sure the linestyles in this graph don't exceed the number of linestyles available in the current display device */ void gr_relinestyle(GRAPH *graph) { - struct dveclist *link; for (link = graph->plotdata; link; link = link->next) { - if (graph->plottype == PLOT_POINT) continue; - if (!(link->vector->v_linestyle < dispdev->numlinestyles)) { - link->vector->v_linestyle %= dispdev->numlinestyles; - } - if (!(link->vector->v_color < dispdev->numcolors)) { - link->vector->v_color %= dispdev->numcolors; - } + if (graph->plottype == PLOT_POINT) + continue; + if (!(link->vector->v_linestyle < dispdev->numlinestyles)) + link->vector->v_linestyle %= dispdev->numlinestyles; + if (!(link->vector->v_color < dispdev->numcolors)) + link->vector->v_color %= dispdev->numcolors; } - } - /* PN static */ + +/* PN static */ void drawlegend(GRAPH *graph, int plotno, struct dvec *dv) { - int x, y, i; char buf[16]; x = ((plotno % 2) ? graph->viewportxoff : - ((graph->viewport.width) / 2)); + ((graph->viewport.width) / 2)); y = graph->absolute.height - graph->fontheight - - ((plotno + 2) / 2) * (graph->fontheight); + - ((plotno + 2) / 2) * (graph->fontheight); i = y + graph->fontheight / 2 + 1; SetColor(dv->v_color); if (graph->plottype == PLOT_POINT) { (void) sprintf(buf, "%c : ", dv->v_linestyle); DevDrawText(buf, x + graph->viewport.width / 20 - - 3 * graph->fontwidth, y); + - 3 * graph->fontwidth, y); } else { SetLinestyle(dv->v_linestyle); DevDrawLine(x, i, x + graph->viewport.width / 20, i); } SetColor(1); DevDrawText(dv->v_name, x + graph->viewport.width / 20 - + graph->fontwidth, y); - + + graph->fontwidth, y); } + /* end one plot of a graph */ void gr_end(struct dvec *dv) @@ -435,6 +435,7 @@ gr_end(struct dvec *dv) DevUpdate(); } + /* Print text in the bottom line. */ void @@ -445,24 +446,22 @@ gr_pmsg(char *text) DevUpdate(); - if (cp_getvar("device", CP_STRING, buf) - && !(strcmp("/dev/tty", buf) == 0)) - fprintf(cp_err, "%s", text); + if (cp_getvar("device", CP_STRING, buf) && !(strcmp("/dev/tty", buf) == 0)) + fprintf(cp_err, "%s", text); + else if (currentgraph->grid.xlabel) + /* MW. grid.xlabel may be NULL */ + DevDrawText(text, currentgraph->viewport.width - + (int) (strlen(currentgraph->grid.xlabel) + 3) * + currentgraph->fontwidth, + currentgraph->absolute.height - currentgraph->fontheight); else - - /* MW. grid.xlabel may be NULL */ - if (currentgraph->grid.xlabel) - DevDrawText(text, currentgraph->viewport.width - - (int) (strlen(currentgraph->grid.xlabel) + 3) - * currentgraph->fontwidth, - currentgraph->absolute.height - currentgraph->fontheight); - else - fprintf(cp_err, " %s \n", text); - + fprintf(cp_err, " %s \n", text); + DevUpdate(); return; } + void gr_clean(void) { @@ -470,11 +469,11 @@ gr_clean(void) return; } + /* call this routine after viewport size changes */ void gr_resize(GRAPH *graph) { - double oldxratio, oldyratio; double scalex, scaley; struct _keyed *k; @@ -490,9 +489,10 @@ gr_resize(GRAPH *graph) /* scale keyed text */ scalex = oldxratio / graph->aspectratiox; scaley = oldyratio / graph->aspectratioy; + for (k = graph->keyed; k; k = k->next) { - k->x = (int)((k->x - graph->viewportxoff) * scalex + graph->viewportxoff); - k->y = (int)((k->y - graph->viewportyoff) * scaley + graph->viewportyoff); + k->x = (int)((k->x - graph->viewportxoff) * scalex + graph->viewportxoff); + k->y = (int)((k->y - graph->viewportyoff) * scaley + graph->viewportyoff); } /* X also generates an expose after a resize. @@ -508,42 +508,40 @@ gr_resize(GRAPH *graph) #ifdef X_DISPLAY_MISSING gr_redraw(graph); #endif - } -/* PN static */ + +/* PN static */ void gr_resize_internal(GRAPH *graph) { - if (!graph->grid.xsized) - graph->viewport.width = (int)(graph->absolute.width - - 1.4 * graph->viewportxoff); + graph->viewport.width = (int)(graph->absolute.width - + 1.4 * graph->viewportxoff); if (!graph->grid.ysized) - graph->viewport.height = graph->absolute.height - - 2 * graph->viewportyoff; - + graph->viewport.height = graph->absolute.height - + 2 * graph->viewportyoff; + gr_fixgrid(graph, graph->grid.xdelta, graph->grid.ydelta, - graph->grid.xdatatype, graph->grid.ydatatype); + graph->grid.xdatatype, graph->grid.ydatatype); /* cache width and height info to make DatatoScreen go fast */ /* note: XXX see if this is actually used anywhere */ graph->datawindow.width = graph->datawindow.xmax - - graph->datawindow.xmin; + graph->datawindow.xmin; graph->datawindow.height = graph->datawindow.ymax - - graph->datawindow.ymin; + graph->datawindow.ymin; /* cache (datawindow size) / (viewport size) */ graph->aspectratiox = graph->datawindow.width / graph->viewport.width; graph->aspectratioy = graph->datawindow.height / graph->viewport.height; - } + /* redraw everything in struct graph */ void gr_redraw(GRAPH *graph) { - struct dveclist *link; /* establish current graph so default graphic calls will work right */ @@ -554,44 +552,42 @@ gr_redraw(GRAPH *graph) /* redraw grid */ gr_redrawgrid(graph); - for (link=graph->plotdata, plotno = 0; link; - link = link->next, plotno++) { - /* redraw legend */ - drawlegend(graph, plotno, link->vector); + for (link = graph->plotdata, plotno = 0; link; link = link->next, plotno++) { + /* redraw legend */ + drawlegend(graph, plotno, link->vector); - /* replot data - if onevalue, pass it a NULL scale - otherwise, if vec has its own scale, pass that - else pass vec's plot's scale - */ - ft_graf(link->vector, - graph->onevalue ? NULL : - (link->vector->v_scale ? - link->vector->v_scale : - link->vector->v_plot->pl_scale), - TRUE); + /* replot data + if onevalue, pass it a NULL scale + otherwise, if vec has its own scale, pass that + else pass vec's plot's scale + */ + ft_graf(link->vector, + graph->onevalue ? NULL : + (link->vector->v_scale ? + link->vector->v_scale : + link->vector->v_plot->pl_scale), + TRUE); } gr_restoretext(graph); PopGraphContext(); - } + void gr_restoretext(GRAPH *graph) { - struct _keyed *k; /* restore text */ - for (k=graph->keyed; k; k = k->next) { - SetColor(k->colorindex); - DevDrawText(k->text, k->x, k->y); + for (k = graph->keyed; k; k = k->next) { + SetColor(k->colorindex); + DevDrawText(k->text, k->x, k->y); } - } + /* Do some incremental plotting. There are 3 cases: * * First, if length < IPOINTMIN, don't do anything. @@ -628,13 +624,13 @@ iplot(struct plot *pl, int id) if (v->v_flags & VF_PLOT) j++; if (!j) - return(0); + return (0); if (ft_grdb) fprintf(cp_err, "Entering iplot, len = %d\n", len); if (len < IPOINTMIN) { /* Nothing yet */ - return(0); + return (0); } else if (len == IPOINTMIN || !id) { resumption = FALSE; /* Draw the grid for the first time, and plot everything. */ @@ -647,11 +643,11 @@ iplot(struct plot *pl, int id) if (v->v_flags & VF_PLOT) { lims = ft_minmax(v, TRUE); if (lims[0] < ylims[0]) - ylims[0] = lims[0]; + ylims[0] = lims[0]; if (lims[1] > ylims[1]) - ylims[1] = lims[1]; + ylims[1] = lims[1]; if (!yl) - yl = v->v_name; + yl = v->v_name; } /* generate a small difference between ymin and ymax to catch the y=const case */ @@ -659,44 +655,43 @@ iplot(struct plot *pl, int id) ylims[1] += 1e-9; if (ft_grdb) - fprintf(cp_err, - "iplot: after 5, xlims = %G, %G, ylims = %G, %G\n", - xlims[0], - xlims[1], - ylims[0], - ylims[1]); - for (yt = pl->pl_dvecs->v_type, v = pl->pl_dvecs->v_next; v; - v = v->v_next) + fprintf(cp_err, + "iplot: after 5, xlims = %G, %G, ylims = %G, %G\n", + xlims[0], xlims[1], ylims[0], ylims[1]); + + for (yt = pl->pl_dvecs->v_type, v = pl->pl_dvecs->v_next; v; v = v->v_next) if ((v->v_flags & VF_PLOT) && (v->v_type != yt)) { yt = 0; break; } - /* note: have command options for iplot to specify xdelta, - etc. So don't need static variables hack. Assume default - values for now. */ + /* note: have command options for iplot to specify xdelta, + etc. So don't need static variables hack. Assume default + values for now. */ sprintf(commandline, "plot %s", yl); (void) gr_init(xlims, ylims, xs->v_name, - pl->pl_title, NULL, j, 0.0, 0.0, - GRID_LIN, PLOT_LIN, xs->v_name, yl, xs->v_type, yt, - plot_cur->pl_typename, commandline); + pl->pl_title, NULL, j, 0.0, 0.0, + GRID_LIN, PLOT_LIN, xs->v_name, yl, xs->v_type, yt, + plot_cur->pl_typename, commandline); + for (v = pl->pl_dvecs; v; v = v->v_next) if (v->v_flags & VF_PLOT) { - gr_start_internal(v, FALSE); - ft_graf(v, xs, TRUE); + gr_start_internal(v, FALSE); + ft_graf(v, xs, TRUE); } inited = 1; + } else { - /* plot the last points and resize if needed */ + /* plot the last points and resize if needed */ Input(&reqst, 0); /* First see if we have to make the screen bigger */ dy = (isreal(xs) ? xs->v_realdata[len - 1] : - realpart(xs->v_compdata[len - 1])); + realpart(xs->v_compdata[len - 1])); if (ft_grdb) fprintf(cp_err, "x = %G\n", dy); if (!if_tranparams(ft_curckt, &start, &stop, &step) || - !ciprefix("tran", pl->pl_typename)) { + !ciprefix("tran", pl->pl_typename)) { stop = HUGE; start = - stop; } @@ -704,40 +699,35 @@ iplot(struct plot *pl, int id) while (dy < currentgraph->data.xmin) { changed = TRUE; if (ft_grdb) - fprintf(cp_err, "resize: xlo %G -> %G\n", - currentgraph->data.xmin, - currentgraph->data.xmin - - (currentgraph->data.xmax - - currentgraph->data.xmin) - * XFACTOR); + fprintf(cp_err, "resize: xlo %G -> %G\n", + currentgraph->data.xmin, + currentgraph->data.xmin - + (currentgraph->data.xmax - currentgraph->data.xmin) + * XFACTOR); /* set the new x lo value */ currentgraph->data.xmin -= - (currentgraph->data.xmax - - currentgraph->data.xmin) - * XFACTOR; + (currentgraph->data.xmax - currentgraph->data.xmin) + * XFACTOR; if (currentgraph->data.xmin < start) { currentgraph->data.xmin = start; break; } } - if (currentgraph->data.xmax < - currentgraph->data.xmin) - currentgraph->data.xmax = - currentgraph->data.xmin; + if (currentgraph->data.xmax < currentgraph->data.xmin) + currentgraph->data.xmax = currentgraph->data.xmin; /* checking for x hi */ while (dy > currentgraph->data.xmax) { changed = TRUE; if (ft_grdb) fprintf(cp_err, "resize: xhi %G -> %G\n", - currentgraph->data.xmax, - currentgraph->data.xmax + - (currentgraph->data.xmax - - currentgraph->data.xmin) * XFACTOR); + currentgraph->data.xmax, + currentgraph->data.xmax + + (currentgraph->data.xmax - currentgraph->data.xmin) + * XFACTOR); /* set the new x hi value */ currentgraph->data.xmax += - (currentgraph->data.xmax - - currentgraph->data.xmin) * - XFACTOR; + (currentgraph->data.xmax - currentgraph->data.xmin) * + XFACTOR; if (currentgraph->data.xmax > stop) { currentgraph->data.xmax = stop; break; @@ -748,50 +738,49 @@ iplot(struct plot *pl, int id) if (!(v->v_flags & VF_PLOT)) continue; dy = (isreal(v) ? v->v_realdata[len - 1] : - realpart(v->v_compdata[len - 1])); + realpart(v->v_compdata[len - 1])); if (ft_grdb) fprintf(cp_err, "y = %G\n", dy); /* checking for y lo */ while (dy < currentgraph->data.ymin) { changed = TRUE; if (ft_grdb) - fprintf(cp_err, "resize: ylo %G -> %G\n", - currentgraph->data.ymin, - currentgraph->data.ymin - - (currentgraph->data.ymax - - currentgraph->data.ymin) * YFACTOR); + fprintf(cp_err, "resize: ylo %G -> %G\n", + currentgraph->data.ymin, + currentgraph->data.ymin - + (currentgraph->data.ymax - currentgraph->data.ymin) + * YFACTOR); /* set the new y lo value */ currentgraph->data.ymin -= - (currentgraph->data.ymax - - currentgraph->data.ymin) * YFACTOR; -/* currentgraph->data.ymin += + (currentgraph->data.ymax - currentgraph->data.ymin) + * YFACTOR; + /* currentgraph->data.ymin += (dy - currentgraph->data.ymin) * YFACTOR;*/ -/* currentgraph->data.ymin = dy; - currentgraph->data.ymin *= (1 + YFACTOR); */ + /* currentgraph->data.ymin = dy; + currentgraph->data.ymin *= (1 + YFACTOR); */ } - if (currentgraph->data.ymax < - currentgraph->data.ymin) - currentgraph->data.ymax = - currentgraph->data.ymin; + if (currentgraph->data.ymax < currentgraph->data.ymin) + currentgraph->data.ymax = currentgraph->data.ymin; /* checking for y hi */ while (dy > currentgraph->data.ymax) { changed = TRUE; if (ft_grdb) - fprintf(cp_err, "resize: yhi %G -> %G\n", - currentgraph->data.ymax, - currentgraph->data.ymax + - (currentgraph->data.ymax - - currentgraph->data.ymin) * YFACTOR); + fprintf(cp_err, "resize: yhi %G -> %G\n", + currentgraph->data.ymax, + currentgraph->data.ymax + + (currentgraph->data.ymax - currentgraph->data.ymin) + * YFACTOR); /* set the new y hi value */ currentgraph->data.ymax += - (currentgraph->data.ymax - - currentgraph->data.ymin) * YFACTOR; -/* currentgraph->data.ymax += + (currentgraph->data.ymax - currentgraph->data.ymin) + * YFACTOR; + /* currentgraph->data.ymax += (dy - currentgraph->data.ymax) * YFACTOR;*/ -/* currentgraph->data.ymax = dy; - currentgraph->data.ymax *= (1 + YFACTOR); */ + /* currentgraph->data.ymax = dy; + currentgraph->data.ymax *= (1 + YFACTOR); */ } } + if (changed) { /* Redraw everything. */ gr_pmsg("Resizing screen"); @@ -804,57 +793,58 @@ iplot(struct plot *pl, int id) * with curve interpolation, so it might look funny. */ for (v = pl->pl_dvecs; v; v = v->v_next) if (v->v_flags & VF_PLOT) { - gr_point(v, - (isreal(xs) ? xs->v_realdata[len - 1] : - realpart(xs->v_compdata[len - 1])), - (isreal(v) ? v->v_realdata[len - 1] : - realpart(v->v_compdata[len - 1])), - (isreal(xs) ? xs->v_realdata[len - 2] : - realpart(xs->v_compdata[len - 2])), - (isreal(v) ? v->v_realdata[len - 2] : - realpart(v->v_compdata[len - 2])), - len - 1); + gr_point(v, + (isreal(xs) ? xs->v_realdata[len - 1] : + realpart(xs->v_compdata[len - 1])), + (isreal(v) ? v->v_realdata[len - 1] : + realpart(v->v_compdata[len - 1])), + (isreal(xs) ? xs->v_realdata[len - 2] : + realpart(xs->v_compdata[len - 2])), + (isreal(v) ? v->v_realdata[len - 2] : + realpart(v->v_compdata[len - 2])), + len - 1); } } } DevUpdate(); - return(inited); + return (inited); } + static void set(struct plot *plot, struct dbcomm *db, bool unset, short mode) { - struct dvec *v; struct dbcomm *dc; if (db->db_type == DB_IPLOTALL || db->db_type == DB_TRACEALL) { - for (v = plot->pl_dvecs; v; v = v->v_next) { - if (unset) - v->v_flags &= (short) ~mode; - else - v->v_flags |= mode; - } - return; + for (v = plot->pl_dvecs; v; v = v->v_next) + if (unset) + v->v_flags &= (short) ~mode; + else + v->v_flags |= mode; + return; } + for (dc = db; dc; dc = dc->db_also) { - v = vec_fromplot(dc->db_nodename1, plot); + v = vec_fromplot(dc->db_nodename1, plot); if (!v || v->v_plot != plot) { - if (!eq(dc->db_nodename1, "0") && !unset) { - fprintf(cp_err, "Warning: node %s non-existent in %s.\n", - dc->db_nodename1, plot->pl_name); - /* note: XXX remove it from dbs, so won't get further errors */ - } - continue; + if (!eq(dc->db_nodename1, "0") && !unset) { + fprintf(cp_err, "Warning: node %s non-existent in %s.\n", + dc->db_nodename1, plot->pl_name); + /* note: XXX remove it from dbs, so won't get further errors */ + } + continue; } if (unset) - v->v_flags &= (short) ~mode; + v->v_flags &= (short) ~mode; else - v->v_flags |= mode; + v->v_flags |= mode; } return; } + static char * getitright(char *buf, double num) { @@ -862,120 +852,121 @@ getitright(char *buf, double num) int k; sprintf(buf, " % .5g", num); - p =strchr(buf, '.'); + p = strchr(buf, '.'); if (p) { - return p - 4; + return p - 4; } else { - k = (int) strlen(buf); - if (k > 8) - return buf + 4; - else /* k >= 4 */ - return buf + k - 4; + k = (int) strlen(buf); + if (k > 8) + return buf + 4; + else /* k >= 4 */ + return buf + k - 4; } } + static int hit, hit2; -void reset_trace(void) + +void +reset_trace(void) { - hit = -1; - hit2 = -1; + hit = -1; + hit2 = -1; } + void gr_iplot(struct plot *plot) { - struct dbcomm *db; int dontpop; /* So we don't pop w/o push. */ char buf[30]; hit = 0; for (db = dbs; db; db = db->db_next) { - if (db->db_type == DB_IPLOT || db->db_type == DB_IPLOTALL) { + if (db->db_type == DB_IPLOT || db->db_type == DB_IPLOTALL) { - if (db->db_graphid) PushGraphContext(FindGraph(db->db_graphid)); + if (db->db_graphid) + PushGraphContext(FindGraph(db->db_graphid)); - set(plot, db, FALSE, VF_PLOT); + set(plot, db, FALSE, VF_PLOT); - dontpop = 0; - if (iplot(plot, db->db_graphid)) { - /* graph just assigned */ - db->db_graphid = currentgraph->graphid; - dontpop = 1; + dontpop = 0; + if (iplot(plot, db->db_graphid)) { + /* graph just assigned */ + db->db_graphid = currentgraph->graphid; + dontpop = 1; + } + + set(plot, db, TRUE, VF_PLOT); + + if (!dontpop && db->db_graphid) + PopGraphContext(); + + } else if (db->db_type == DB_TRACENODE || db->db_type == DB_TRACEALL) { + + struct dvec *v, *u; + int len; + + set(plot, db, FALSE, VF_PRINT); + + len = plot->pl_scale->v_length; + + dontpop = 0; + for (v = plot->pl_dvecs; v; v = v->v_next) { + if (v->v_flags & VF_PRINT) { + u = plot->pl_scale; + if (len <= 1 || hit <= 0 || hit2 < 0) { + if (len <= 1 || hit2 < 0) + term_clear(); + else + term_home(); + hit = 1; + hit2 = 1; + printf( + "\tExecution trace (remove with the \"delete\" command)"); + term_cleol(); + printf("\n"); + + if (u) { + printf("%12s:", u->v_name); + if (isreal(u)) { + printf("%s", + getitright(buf, u->v_realdata[len - 1])); + } else { + /* MW. Complex data here, realdata is NULL + (why someone use realdata here again) */ + printf("%s", + getitright(buf, u->v_compdata[len - 1].cx_real)); + printf(", %s", + getitright(buf, u->v_compdata[len - 1].cx_imag)); + } + term_cleol(); + printf("\n"); + } + } + if (v == u) + continue; + printf("%12s:", v->v_name); + if (isreal(v)) { + printf("%s", getitright(buf, v->v_realdata[len - 1])); + } else { + /* MW. Complex data again */ + printf("%s", getitright(buf, v->v_compdata[len - 1].cx_real)); + printf(", %s", getitright(buf, v->v_compdata[len - 1].cx_imag)); + } + term_cleol(); + printf("\n"); + } + } + set(plot, db, TRUE, VF_PRINT); } - - set(plot, db, TRUE, VF_PLOT); - - if (!dontpop && db->db_graphid) PopGraphContext(); - - } else if (db->db_type == DB_TRACENODE || db->db_type == DB_TRACEALL) { - - struct dvec *v, *u; - int len; - - set(plot, db, FALSE, VF_PRINT); - - len = plot->pl_scale->v_length; - - dontpop = 0; - for (v = plot->pl_dvecs; v; v = v->v_next) { - if (v->v_flags & VF_PRINT) { - u = plot->pl_scale; - if (len <= 1 || hit <= 0 || hit2 < 0) { - if (len <= 1 || hit2 < 0) - term_clear( ); - else - term_home( ); - hit = 1; - hit2 = 1; - printf( - "\tExecution trace (remove with the \"delete\" command)"); - term_cleol( ); - printf("\n"); - - if (u) { - printf("%12s:", u->v_name); - if (isreal(u)) { - printf("%s", - getitright(buf, u->v_realdata[len - 1])); - } else { - - /* MW. Complex data here, realdata is NULL - (why someone use realdata here again) */ - printf("%s", - getitright(buf, u->v_compdata[len - 1].cx_real)); - printf(", %s", - getitright(buf, u->v_compdata[len - 1].cx_imag)); - } - term_cleol( ); - printf("\n"); - } - } - if (v == u) - continue; - printf("%12s:", v->v_name); - if (isreal(v)) { - printf("%s", getitright(buf, v->v_realdata[len - 1])); - } else { - - /* MW. Complex data again */ - printf("%s", getitright(buf, v->v_compdata[len - 1].cx_real)); - printf(", %s", getitright(buf, v->v_compdata[len - 1].cx_imag)); - } - term_cleol( ); - printf("\n"); - } - } - set(plot, db, TRUE, VF_PRINT); - - } - } - } + /* This gets called after iplotting is done. We clear out the * db_graphid fields. Copy the dvecs, which we referenced by * reference, so DestroyGraph gets to free its own copy. @@ -986,7 +977,6 @@ gr_iplot(struct plot *plot) void gr_end_iplot(void) { - struct dbcomm *db, *prev, *next; GRAPH *graph; struct dveclist *link; @@ -994,75 +984,75 @@ gr_end_iplot(void) prev = NULL; for (db = dbs; db; prev = db, db = next) { - next = db->db_next; - if (db->db_type == DB_DEADIPLOT) { - if (db->db_graphid) { - DestroyGraph(db->db_graphid); - if (prev) - prev->db_next = next; - else - dbs = next; - dbfree(db); - } - } else if (db->db_type == DB_IPLOT || db->db_type == DB_IPLOTALL) { - if (db->db_graphid) { + next = db->db_next; + if (db->db_type == DB_DEADIPLOT) { + if (db->db_graphid) { + DestroyGraph(db->db_graphid); + if (prev) + prev->db_next = next; + else + dbs = next; + dbfree(db); + } + } else if (db->db_type == DB_IPLOT || db->db_type == DB_IPLOTALL) { + if (db->db_graphid) { - /* get private copy of dvecs */ - graph = FindGraph(db->db_graphid); + /* get private copy of dvecs */ + graph = FindGraph(db->db_graphid); - link = graph->plotdata; + link = graph->plotdata; - while (link) { - dv = link->vector; - link->vector = vec_copy(dv); - /* vec_copy doesn't set v_color or v_linestyle */ - link->vector->v_color = dv->v_color; - link->vector->v_linestyle = dv->v_linestyle; - link->vector->v_flags |= VF_PERMANENT; - link = link->next; - } + while (link) { + dv = link->vector; + link->vector = vec_copy(dv); + /* vec_copy doesn't set v_color or v_linestyle */ + link->vector->v_color = dv->v_color; + link->vector->v_linestyle = dv->v_linestyle; + link->vector->v_flags |= VF_PERMANENT; + link = link->next; + } - db->db_graphid = 0; - } else { - /* warn that this wasn't plotted */ - fprintf(cp_err, "Warning: iplot %d was not executed.\n", - db->db_number); + db->db_graphid = 0; + } else { + /* warn that this wasn't plotted */ + fprintf(cp_err, "Warning: iplot %d was not executed.\n", + db->db_number); + } } - } } - return; } + double * readtics(char *string) { - int i, k; - char *words, *worde; - double *tics, *ticsk; + int i, k; + char *words, *worde; + double *tics, *ticsk; - tics = TMALLOC(double, MAXTICS); - ticsk = tics; - words = string; + tics = TMALLOC(double, MAXTICS); + ticsk = tics; + words = string; - for (i = k = 0; *words && k < MAXTICS; words = worde) { + for (i = k = 0; *words && k < MAXTICS; words = worde) { - while (isspace(*words)) - words++; + while (isspace(*words)) + words++; - worde = words; - while (isalpha(*worde) || isdigit(*worde)) - worde++; + worde = words; + while (isalpha(*worde) || isdigit(*worde)) + worde++; - if (*worde) - *worde++ = '\0'; + if (*worde) + *worde++ = '\0'; - sscanf(words, "%lf", ticsk++); + sscanf(words, "%lf", ticsk++); - k++; + k++; - } - *ticsk = HUGE; - return(tics); + } + *ticsk = HUGE; + return (tics); } diff --git a/src/frontend/plotting/graf.h b/src/frontend/plotting/graf.h index bd730150b..9c798820e 100644 --- a/src/frontend/plotting/graf.h +++ b/src/frontend/plotting/graf.h @@ -9,18 +9,18 @@ #include "ngspice/graph.h" int gr_init(double *xlims, double *ylims, - char *xname, char *plotname, - char *hcopy, - int nplots, - double xdelta, double ydelta, - GRIDTYPE gridtype, - PLOTTYPE plottype, - char *xlabel, char *ylabel, - int xtype, int ytype, - char *pname, char *commandline); + char *xname, char *plotname, + char *hcopy, + int nplots, + double xdelta, double ydelta, + GRIDTYPE gridtype, + PLOTTYPE plottype, + char *xlabel, char *ylabel, + int xtype, int ytype, + char *pname, char *commandline); void gr_point(struct dvec *dv, - double newx, double newy, - double oldx, double oldy, int np); + double newx, double newy, + double oldx, double oldy, int np); void gr_start(struct dvec *dv); void gr_relinestyle(GRAPH *graph); void drawlegend(GRAPH *graph, int plotno, struct dvec *dv); @@ -34,6 +34,6 @@ void gr_restoretext(GRAPH *graph); void reset_trace(void); void gr_iplot(struct plot *plot); void gr_end_iplot(void); -double * readtics(char *string); +double *readtics(char *string); -#endif /* GRAF_H */ +#endif diff --git a/src/frontend/plotting/graphdb.c b/src/frontend/plotting/graphdb.c index dbf75f1d8..c81cea78d 100644 --- a/src/frontend/plotting/graphdb.c +++ b/src/frontend/plotting/graphdb.c @@ -3,7 +3,7 @@ Copyright 1990 Regents of the University of California. All rights reserved. **********/ /* - Manage graph data structure. + Manage graph data structure. */ #include "ngspice/ngspice.h" @@ -28,10 +28,11 @@ GRAPH *currentgraph; /* linked list of graphs */ typedef struct listgraph { - /* we use GRAPH here instead of a pointer to save a tmalloc */ + /* we use GRAPH here instead of a pointer to save a tmalloc */ GRAPH graph; struct listgraph *next; } LISTGRAPH; + #define NEWLISTGRAPH TMALLOC(LISTGRAPH, 1) #define NUMGBUCKETS 16 @@ -56,57 +57,56 @@ static int RunningId = 1; /* returns NULL on error */ -GRAPH *NewGraph(void) +GRAPH * +NewGraph(void) { - GRAPH *pgraph; LISTGRAPH *list; int BucketId = RunningId % NUMGBUCKETS; if ((list = NEWLISTGRAPH) == NULL) { - internalerror("can't allocate a listgraph"); - return(NULL); + internalerror("can't allocate a listgraph"); + return (NULL); } pgraph = &list->graph; SETGRAPH(pgraph, RunningId); if (!GBucket[BucketId].list) { - GBucket[BucketId].list = list; + GBucket[BucketId].list = list; } else { - /* insert at front of current list */ - list->next = GBucket[BucketId].list; - GBucket[BucketId].list = list; + /* insert at front of current list */ + list->next = GBucket[BucketId].list; + GBucket[BucketId].list = list; } - RunningId++ ; - - return(pgraph); + RunningId++; + return (pgraph); } -/* Given graph id, return graph */ -GRAPH *FindGraph(int id) -{ +/* Given graph id, return graph */ +GRAPH * +FindGraph(int id) +{ LISTGRAPH *list; for (list = GBucket[id % NUMGBUCKETS].list; - list && list->graph.graphid != id; - list = list->next) - - ; + list && list->graph.graphid != id; + list = list->next) + ; if (list) - return(&list->graph); + return (&list->graph); else - return(NULL); - + return (NULL); } -GRAPH *CopyGraph(GRAPH *graph) -{ +GRAPH * +CopyGraph(GRAPH *graph) +{ GRAPH *ret; struct _keyed *k; struct dveclist *link, *newlink; @@ -117,34 +117,32 @@ GRAPH *CopyGraph(GRAPH *graph) ret->graphid = RunningId - 1; /* restore id */ /* copy keyed */ - for (ret->keyed = NULL, k = graph->keyed; k; k = k->next) { - SaveText(ret, k->text, k->x, k->y); - } + for (ret->keyed = NULL, k = graph->keyed; k; k = k->next) + SaveText(ret, k->text, k->x, k->y); /* copy dvecs */ ret->plotdata = NULL; for (link = graph->plotdata; link; link = link->next) { - newlink = TMALLOC(struct dveclist, 1); - newlink->next = ret->plotdata; - newlink->vector = vec_copy(link->vector); - /* vec_copy doesn't set v_color or v_linestyle */ - newlink->vector->v_color = link->vector->v_color; - newlink->vector->v_linestyle = link->vector->v_linestyle; - newlink->vector->v_flags |= VF_PERMANENT; - ret->plotdata = newlink; + newlink = TMALLOC(struct dveclist, 1); + newlink->next = ret->plotdata; + newlink->vector = vec_copy(link->vector); + /* vec_copy doesn't set v_color or v_linestyle */ + newlink->vector->v_color = link->vector->v_color; + newlink->vector->v_linestyle = link->vector->v_linestyle; + newlink->vector->v_flags |= VF_PERMANENT; + ret->plotdata = newlink; } ret->commandline = copy(graph->commandline); ret->plotname = copy(graph->plotname); - return(ret); - + return (ret); } + int DestroyGraph(int id) { - LISTGRAPH *list, *lastlist; struct _keyed *k, *nextk; struct dveclist *d, *nextd; @@ -153,129 +151,126 @@ DestroyGraph(int id) list = GBucket[id % NUMGBUCKETS].list; lastlist = NULL; while (list) { - if (list->graph.graphid == id) { /* found it */ + if (list->graph.graphid == id) { /* found it */ - /* Fix the iplot/trace dbs list */ - for (db = dbs; db && db->db_graphid != id; db = db->db_next) - ; + /* Fix the iplot/trace dbs list */ + for (db = dbs; db && db->db_graphid != id; db = db->db_next) + ; - if (db && (db->db_type == DB_IPLOT - || db->db_type == DB_IPLOTALL)) { - db->db_type = DB_DEADIPLOT; - /* Delete this later */ - return(0); - } + if (db && (db->db_type == DB_IPLOT || + db->db_type == DB_IPLOTALL)) + { + db->db_type = DB_DEADIPLOT; + /* Delete this later */ + return (0); + } - /* adjust bucket pointers */ - if (lastlist) { - lastlist->next = list->next; - } else { - GBucket[id % NUMGBUCKETS].list = list->next; + /* adjust bucket pointers */ + if (lastlist) + lastlist->next = list->next; + else + GBucket[id % NUMGBUCKETS].list = list->next; + + /* run through and de-allocate dynamically allocated keyed list */ + k = list->graph.keyed; + while (k) { + nextk = k->next; + tfree(k->text); + tfree(k); + k = nextk; + } + + /* de-allocate dveclist */ + d = list->graph.plotdata; + while (d) { + nextd = d->next; + tfree(d->vector->v_name); + if (isreal(d->vector)) + tfree(d->vector->v_realdata); + else + tfree(d->vector->v_compdata); + tfree(d->vector); + tfree(d); + d = nextd; + } + + tfree(list->graph.commandline); + tfree(list->graph.plotname); + + /* If device dependent space allocated, free it. */ + if (list->graph.devdep) + tfree(list->graph.devdep); + tfree(list); + + return (1); } - - /* run through and de-allocate dynamically allocated keyed list */ - k=list->graph.keyed; - while (k) { - nextk = k->next; - tfree(k->text); - tfree(k); - k = nextk; - } - - /* de-allocate dveclist */ - d = list->graph.plotdata; - while (d) { - nextd = d->next; - tfree(d->vector->v_name); - if (isreal(d->vector)) { - tfree(d->vector->v_realdata); - } else { - tfree(d->vector->v_compdata); - } - tfree(d->vector); - tfree(d); - d = nextd; - } - - tfree(list->graph.commandline); - tfree(list->graph.plotname); - - /* If device dependent space allocated, free it. */ - if (list->graph.devdep) - tfree(list->graph.devdep); - tfree(list); - - return(1); - } - lastlist = list; - list = list->next; + lastlist = list; + list = list->next; } internalerror("tried to destroy non-existent graph"); return (0); - } + /* free up all dynamically allocated data structures */ void FreeGraphs(void) { - GBUCKET *gbucket; LISTGRAPH *list, *deadl; for (gbucket = GBucket; gbucket < &GBucket[NUMGBUCKETS]; gbucket++) { - list = gbucket->list; - while (list) { - deadl = list; - list = list->next; - tfree(deadl); - } + list = gbucket->list; + while (list) { + deadl = list; + list = list->next; + tfree(deadl); + } } - } + void SetGraphContext(int graphid) { - currentgraph = FindGraph(graphid); - } + typedef struct gcstack { GRAPH *pgraph; struct gcstack *next; } GCSTACK; + GCSTACK *gcstacktop; #define NEWGCSTACK TMALLOC(GCSTACK, 1) + /* note: This Push and Pop has tricky semantics. - Push(graph) will push the currentgraph onto the stack - and set currentgraph to graph. - Pop() simply sets currentgraph to the top of the stack and pops stack. + Push(graph) will push the currentgraph onto the stack + and set currentgraph to graph. + Pop() simply sets currentgraph to the top of the stack and pops stack. */ void PushGraphContext(GRAPH *graph) { - GCSTACK *gcstack = NEWGCSTACK; if (!gcstacktop) { - gcstacktop = gcstack; + gcstacktop = gcstack; } else { - gcstack->next = gcstacktop; - gcstacktop = gcstack; + gcstack->next = gcstacktop; + gcstacktop = gcstack; } gcstacktop->pgraph = currentgraph; currentgraph = graph; - } + void PopGraphContext(void) { - GCSTACK *dead; currentgraph = gcstacktop->pgraph; diff --git a/src/frontend/plotting/graphdb.h b/src/frontend/plotting/graphdb.h index e57aec3e1..d2a9ba13e 100644 --- a/src/frontend/plotting/graphdb.h +++ b/src/frontend/plotting/graphdb.h @@ -12,6 +12,4 @@ void SetGraphContext(int graphid); void PushGraphContext(GRAPH *graph); void PopGraphContext(void); - - #endif diff --git a/src/frontend/plotting/grid.c b/src/frontend/plotting/grid.c index d5333de7d..a97a07d6a 100644 --- a/src/frontend/plotting/grid.c +++ b/src/frontend/plotting/grid.c @@ -4,8 +4,7 @@ Modified: 2001 AlansFixes **********/ /* - - Routines to draw the various sorts of grids -- linear, log, polar. + Routines to draw the various sorts of grids -- linear, log, polar. */ #include "ngspice/ngspice.h" @@ -16,34 +15,33 @@ Modified: 2001 AlansFixes #include "ngspice/grid.h" #include "../display.h" -#define RAD_TO_DEG (180.0 / M_PI) -#define LABEL_CHARS 20 +#define RAD_TO_DEG (180.0 / M_PI) +#define LABEL_CHARS 20 typedef enum { x_axis, y_axis } Axis; -/* static declarations */ -static double * lingrid(GRAPH *graph, double lo, double hi, double delta, int type, Axis axis); -static double * loggrid(GRAPH *graph, double lo, double hi, int type, Axis axis); +static double *lingrid(GRAPH *graph, double lo, double hi, double delta, int type, Axis axis); +static double *loggrid(GRAPH *graph, double lo, double hi, int type, Axis axis); static void polargrid(GRAPH *graph); static void drawpolargrid(GRAPH *graph); static void adddeglabel(GRAPH *graph, int deg, int x, int y, int cx, int cy, int lx, int ly); static void addradlabel(GRAPH *graph, int lab, double theta, int x, int y); static void smithgrid(GRAPH *graph); static void drawsmithgrid(GRAPH *graph); -static void arcset(GRAPH *graph, double rad, double prevrad, double irad, double iprevrad, - double radoff, int maxrad, int centx, int centy, int xoffset, int yoffset, - char *plab, char *nlab, int pdeg, int ndeg, int pxmin, int pxmax); -static double cliparc(double cx, double cy, double rad, double start, double end, int iclipx, - int iclipy, int icliprad, int flag); +static void arcset(GRAPH *graph, double rad, double prevrad, double irad, double iprevrad, + double radoff, int maxrad, int centx, int centy, int xoffset, int yoffset, + char *plab, char *nlab, int pdeg, int ndeg, int pxmin, int pxmax); +static double cliparc(double cx, double cy, double rad, double start, double end, int iclipx, + int iclipy, int icliprad, int flag); -static void drawlingrid(GRAPH *graph, char *units, int spacing, int nsp, double dst, double lmt, - double hmt, bool onedec, int mult, double mag, int digits, Axis axis); -static void drawloggrid(GRAPH *graph, char *units, int hmt, int lmt, int decsp, int subs, - int pp, Axis axis); +static void drawlingrid(GRAPH *graph, char *units, int spacing, int nsp, double dst, double lmt, + double hmt, bool onedec, int mult, double mag, int digits, Axis axis); +static void drawloggrid(GRAPH *graph, char *units, int hmt, int lmt, int decsp, int subs, + int pp, Axis axis); /* note: scaleunits is static and never changed in this file - ie, can get rid of it */ + ie, can get rid of it */ static bool scaleunits = TRUE; @@ -52,28 +50,28 @@ gr_fixgrid(GRAPH *graph, double xdelta, double ydelta, int xtype, int ytype) { double *dd; - if (graph->grid.gridtype == GRID_NONE) { + if (graph->grid.gridtype == GRID_NONE) graph->grid.gridtype = GRID_LIN; - } SetColor(1); SetLinestyle(1); - if ((graph->data.xmin > graph->data.xmax) - || (graph->data.ymin > graph->data.ymax)) { - fprintf(cp_err, - "gr_fixgrid: Internal Error - bad limits: %g, %g, %g, %g\n", - graph->data.xmin, graph->data.xmax, - graph->data.ymin, graph->data.ymax); - return; + if ((graph->data.xmin > graph->data.xmax) || + (graph->data.ymin > graph->data.ymax)) + { + fprintf(cp_err, + "gr_fixgrid: Internal Error - bad limits: %g, %g, %g, %g\n", + graph->data.xmin, graph->data.xmax, + graph->data.ymin, graph->data.ymax); + return; } if (graph->grid.gridtype == GRID_POLAR) { graph->grid.circular = TRUE; polargrid(graph); return; - } else if (graph->grid.gridtype == GRID_SMITH - || graph->grid.gridtype == GRID_SMITHGRID) + } else if (graph->grid.gridtype == GRID_SMITH || + graph->grid.gridtype == GRID_SMITHGRID) { graph->grid.circular = TRUE; smithgrid(graph); @@ -81,43 +79,48 @@ gr_fixgrid(GRAPH *graph, double xdelta, double ydelta, int xtype, int ytype) } graph->grid.circular = FALSE; - if ((graph->grid.gridtype == GRID_YLOG) - || (graph->grid.gridtype == GRID_LOGLOG)) + if ((graph->grid.gridtype == GRID_YLOG) || + (graph->grid.gridtype == GRID_LOGLOG)) + { dd = loggrid(graph, graph->data.ymin, graph->data.ymax, - ytype, y_axis); - else + ytype, y_axis); + } else { dd = lingrid(graph, graph->data.ymin, graph->data.ymax, - ydelta, ytype, y_axis); + ydelta, ytype, y_axis); + } graph->datawindow.ymin = dd[0]; graph->datawindow.ymax = dd[1]; - if ((graph->grid.gridtype == GRID_XLOG) - || (graph->grid.gridtype == GRID_LOGLOG)) + if ((graph->grid.gridtype == GRID_XLOG) || + (graph->grid.gridtype == GRID_LOGLOG)) + { dd = loggrid(graph, graph->data.xmin, graph->data.xmax, - xtype, x_axis); - else + xtype, x_axis); + } else { dd = lingrid(graph, graph->data.xmin, graph->data.xmax, - xdelta, xtype, x_axis); + xdelta, xtype, x_axis); + } graph->datawindow.xmin = dd[0]; graph->datawindow.xmax = dd[1]; -/* do we really need this? */ -/* - SetLinestyle(0); - DevDrawLine(graph->viewportxoff, graph->viewportyoff, - graph->viewport.width + graph->viewportxoff, - graph->viewportyoff); - DevDrawLine(graph->viewportxoff, graph->viewportyoff, - graph->viewportxoff, - graph->viewport.height + graph->viewportyoff); - SetLinestyle(1); -*/ + /* do we really need this? */ + /* + SetLinestyle(0); + DevDrawLine(graph->viewportxoff, graph->viewportyoff, + graph->viewport.width + graph->viewportxoff, + graph->viewportyoff); + DevDrawLine(graph->viewportxoff, graph->viewportyoff, + graph->viewportxoff, + graph->viewport.height + graph->viewportyoff); + SetLinestyle(1); + */ return; } + void gr_redrawgrid(GRAPH *graph) { @@ -126,98 +129,96 @@ gr_redrawgrid(GRAPH *graph) SetLinestyle(1); /* draw labels */ if (graph->grid.xlabel) { - DevDrawText(graph->grid.xlabel, - (int) (graph->absolute.width * 0.35), - graph->fontheight); + DevDrawText(graph->grid.xlabel, + (int) (graph->absolute.width * 0.35), + graph->fontheight); } if (graph->grid.ylabel) { - if (graph->grid.gridtype == GRID_POLAR - || graph->grid.gridtype == GRID_SMITH - || graph->grid.gridtype == GRID_SMITHGRID) { - DevDrawText(graph->grid.ylabel, - graph->fontwidth, - (graph->absolute.height * 3) / 4 ); - } else { - DevDrawText(graph->grid.ylabel, - graph->fontwidth, - graph->absolute.height / 2 ); - } + if (graph->grid.gridtype == GRID_POLAR || + graph->grid.gridtype == GRID_SMITH || + graph->grid.gridtype == GRID_SMITHGRID) + { + DevDrawText(graph->grid.ylabel, + graph->fontwidth, + (graph->absolute.height * 3) / 4); + } else { + DevDrawText(graph->grid.ylabel, + graph->fontwidth, + graph->absolute.height / 2); + } } - switch( graph->grid.gridtype ) { - case GRID_POLAR: - drawpolargrid(graph); - break; - case GRID_SMITH: - drawsmithgrid(graph); - break; - case GRID_SMITHGRID: - drawsmithgrid(graph); - break; - - - case GRID_XLOG: - case GRID_LOGLOG: - drawloggrid(graph, - graph->grid.xaxis.log.units, - graph->grid.xaxis.log.hmt, - graph->grid.xaxis.log.lmt, - graph->grid.xaxis.log.decsp, - graph->grid.xaxis.log.subs, - graph->grid.xaxis.log.pp, x_axis); - break; - default: - drawlingrid(graph, - graph->grid.xaxis.lin.units, - graph->grid.xaxis.lin.spacing, - graph->grid.xaxis.lin.numspace, - graph->grid.xaxis.lin.distance, - graph->grid.xaxis.lin.lowlimit, - graph->grid.xaxis.lin.highlimit, - graph->grid.xaxis.lin.onedec, - graph->grid.xaxis.lin.mult, - graph->grid.xaxis.lin.tenpowmag - / graph->grid.xaxis.lin.tenpowmagx, - graph->grid.xaxis.lin.digits, - x_axis); - break; - } - - switch( graph->grid.gridtype ) { - case GRID_POLAR: - case GRID_SMITH: - case GRID_SMITHGRID: - break; - - case GRID_YLOG: - case GRID_LOGLOG: - drawloggrid(graph, - graph->grid.yaxis.log.units, - graph->grid.yaxis.log.hmt, - graph->grid.yaxis.log.lmt, - graph->grid.yaxis.log.decsp, - graph->grid.yaxis.log.subs, - graph->grid.yaxis.log.pp, y_axis); - break; - default: - drawlingrid(graph, - graph->grid.yaxis.lin.units, - graph->grid.yaxis.lin.spacing, - graph->grid.yaxis.lin.numspace, - graph->grid.yaxis.lin.distance, - graph->grid.yaxis.lin.lowlimit, - graph->grid.yaxis.lin.highlimit, - graph->grid.yaxis.lin.onedec, - graph->grid.yaxis.lin.mult, - graph->grid.yaxis.lin.tenpowmag - / graph->grid.yaxis.lin.tenpowmagx, - graph->grid.yaxis.lin.digits, - y_axis); - break; - } + switch (graph->grid.gridtype) { + case GRID_POLAR: + drawpolargrid(graph); + break; + case GRID_SMITH: + drawsmithgrid(graph); + break; + case GRID_SMITHGRID: + drawsmithgrid(graph); + break; + case GRID_XLOG: + case GRID_LOGLOG: + drawloggrid(graph, + graph->grid.xaxis.log.units, + graph->grid.xaxis.log.hmt, + graph->grid.xaxis.log.lmt, + graph->grid.xaxis.log.decsp, + graph->grid.xaxis.log.subs, + graph->grid.xaxis.log.pp, x_axis); + break; + default: + drawlingrid(graph, + graph->grid.xaxis.lin.units, + graph->grid.xaxis.lin.spacing, + graph->grid.xaxis.lin.numspace, + graph->grid.xaxis.lin.distance, + graph->grid.xaxis.lin.lowlimit, + graph->grid.xaxis.lin.highlimit, + graph->grid.xaxis.lin.onedec, + graph->grid.xaxis.lin.mult, + graph->grid.xaxis.lin.tenpowmag + / graph->grid.xaxis.lin.tenpowmagx, + graph->grid.xaxis.lin.digits, + x_axis); + break; + } + switch (graph->grid.gridtype) { + case GRID_POLAR: + case GRID_SMITH: + case GRID_SMITHGRID: + break; + case GRID_YLOG: + case GRID_LOGLOG: + drawloggrid(graph, + graph->grid.yaxis.log.units, + graph->grid.yaxis.log.hmt, + graph->grid.yaxis.log.lmt, + graph->grid.yaxis.log.decsp, + graph->grid.yaxis.log.subs, + graph->grid.yaxis.log.pp, y_axis); + break; + default: + drawlingrid(graph, + graph->grid.yaxis.lin.units, + graph->grid.yaxis.lin.spacing, + graph->grid.yaxis.lin.numspace, + graph->grid.yaxis.lin.distance, + graph->grid.yaxis.lin.lowlimit, + graph->grid.yaxis.lin.highlimit, + graph->grid.yaxis.lin.onedec, + graph->grid.yaxis.lin.mult, + graph->grid.yaxis.lin.tenpowmag + / graph->grid.yaxis.lin.tenpowmagx, + graph->grid.yaxis.lin.digits, + y_axis); + break; + } } + /* Plot a linear grid. Returns the new hi and lo limits. */ static double * lingrid(GRAPH *graph, double lo, double hi, double delta, int type, Axis axis) @@ -235,21 +236,21 @@ lingrid(GRAPH *graph, double lo, double hi, double delta, int type, Axis axis) int slim, digits; if (axis == y_axis && graph->grid.ysized) { - lmt = graph->grid.yaxis.lin.lowlimit; - hmt = graph->grid.yaxis.lin.highlimit; - tenpowmag = graph->grid.yaxis.lin.tenpowmag; - dd[0] = lmt * tenpowmag; - dd[1] = hmt * tenpowmag; - return dd; + lmt = graph->grid.yaxis.lin.lowlimit; + hmt = graph->grid.yaxis.lin.highlimit; + tenpowmag = graph->grid.yaxis.lin.tenpowmag; + dd[0] = lmt * tenpowmag; + dd[1] = hmt * tenpowmag; + return dd; } if (axis == x_axis && graph->grid.xsized) { - lmt = graph->grid.xaxis.lin.lowlimit; - hmt = graph->grid.xaxis.lin.highlimit; - tenpowmag = graph->grid.xaxis.lin.tenpowmag; - dd[0] = lmt * tenpowmag; - dd[1] = hmt * tenpowmag; - return dd; + lmt = graph->grid.xaxis.lin.lowlimit; + hmt = graph->grid.xaxis.lin.highlimit; + tenpowmag = graph->grid.xaxis.lin.tenpowmag; + dd[0] = lmt * tenpowmag; + dd[1] = hmt * tenpowmag; + return dd; } if (delta < 0.0) { @@ -274,24 +275,24 @@ lingrid(GRAPH *graph, double lo, double hi, double delta, int type, Axis axis) hi = hmt * tenpowmag2; if (fabs(hi) > fabs(lo)) - mag = (int)floor(log10(fabs(hi))); + mag = (int)floor(log10(fabs(hi))); else - mag = (int)floor(log10(fabs(lo))); + mag = (int)floor(log10(fabs(lo))); if (mag >= 0) - mag3 = ((int) (mag / 3)) * 3; + mag3 = ((int) (mag / 3)) * 3; else - mag3 = - ((int) ((2 - mag) / 3)) * 3; + mag3 = - ((int) ((2 - mag) / 3)) * 3; - if (scaleunits) - digits = mag3 - mag2; - else { - digits = mag - mag2; - mag3 = mag; + if (scaleunits) { + digits = mag3 - mag2; + } else { + digits = mag - mag2; + mag3 = mag; } if (digits < 1) - digits = 0; + digits = 0; if (digits > 15) { dd[0] = 1; @@ -302,14 +303,14 @@ lingrid(GRAPH *graph, double lo, double hi, double delta, int type, Axis axis) } if (axis == x_axis) { - margin = graph->viewportxoff; - /*max = graph->viewport.width + graph->viewportxoff;*/ - max = graph->absolute.width - graph->viewportxoff; + margin = graph->viewportxoff; + /*max = graph->viewport.width + graph->viewportxoff;*/ + max = graph->absolute.width - graph->viewportxoff; } else { - graph->viewportxoff = (digits + 5 + mag - mag3) * graph->fontwidth; - margin = graph->viewportyoff; - /*max = graph->viewport.height + graph->viewportyoff;*/ - max = graph->absolute.height - graph->viewportyoff; + graph->viewportxoff = (digits + 5 + mag - mag3) * graph->fontwidth; + margin = graph->viewportyoff; + /*max = graph->viewport.height + graph->viewportyoff;*/ + max = graph->absolute.height - graph->viewportyoff; } /* Express the difference between the high and low values as @@ -325,120 +326,118 @@ lingrid(GRAPH *graph, double lo, double hi, double delta, int type, Axis axis) */ if (scaleunits) { - static char scaleletters[ ] = "afpnum\0kMGT"; - char *p; - int i, j; + static char scaleletters[ ] = "afpnum\0kMGT"; + char *p; + int i, j; tenpowmag = pow(10.0, (double) mag3); - i = (mag3 + 18) / 3; + i = (mag3 + 18) / 3; - if (i < 0) - i = 6; /* No scale units */ - else if (i >= (int) sizeof(scaleletters) - 1) { - /* sizeof includes '\0' at end, which is useless */ - /* i = sizeof(scaleletters) - 2; */ - i = 6; /* No scale units */ - } + if (i < 0) + i = 6; /* No scale units */ + else if (i >= (int) sizeof(scaleletters) - 1) { + /* sizeof includes '\0' at end, which is useless */ + /* i = sizeof(scaleletters) - 2; */ + i = 6; /* No scale units */ + } - j = mag3 - i * 3 + 18; - if (j == 1) - (void) sprintf(buf, "x10 "); - else if (j == 2) - (void) sprintf(buf, "x100 "); - else if (j) - (void) snprintf(buf, sizeof(buf) - 1, "x10^%d ", j); - else - buf[0] = '\0'; + j = mag3 - i * 3 + 18; + if (j == 1) + (void) sprintf(buf, "x10 "); + else if (j == 2) + (void) sprintf(buf, "x100 "); + else if (j) + (void) snprintf(buf, sizeof(buf) - 1, "x10^%d ", j); + else + buf[0] = '\0'; - if (scaleletters[i]) { - for (p = buf; *p; p++) - ; - *p++ = scaleletters[i]; - *p++ = '\0'; - } + if (scaleletters[i]) { + for (p = buf; *p; p++) + ; + *p++ = scaleletters[i]; + *p++ = '\0'; + } } else if (mag > 1) { tenpowmag = pow(10.0, (double) mag); - (void) snprintf(buf, sizeof(buf), "x10^%d ", mag); + (void) snprintf(buf, sizeof(buf), "x10^%d ", mag); } else { - buf[0] = '\0'; + buf[0] = '\0'; } - if ((s = ft_typabbrev(type)) != NULL) { - (void) strncat(buf, s, sizeof(buf) - 1); - } else { - (void) strncat(buf, "Units", sizeof(buf) - 1); - } + if ((s = ft_typabbrev(type)) != NULL) + (void) strncat(buf, s, sizeof(buf) - 1); + else + (void) strncat(buf, "Units", sizeof(buf) - 1); if (delta == 0.0) { - int i; - double step; + int i; + double step; - static struct { double div_lim, step; } div_list[ ] = { - { 100.0, 10.0 }, - { 50.0, 5.0 }, - { 20.0, 2.0 }, - { 6.0, 1.0 }, - { 3.0, 0.5 }, - { 1.0, 0.2 }, - { 0.5, 0.1 }, - { 0.0, 0.05 }, - { 0.0, 0.01 } - }; + static struct { double div_lim, step; } div_list[] = { + { 100.0, 10.0 }, + { 50.0, 5.0 }, + { 20.0, 2.0 }, + { 6.0, 1.0 }, + { 3.0, 0.5 }, + { 1.0, 0.2 }, + { 0.5, 0.1 }, + { 0.0, 0.05 }, + { 0.0, 0.01 } + }; - for (i = 0; (size_t) i < NUMELEMS(div_list); i++) { - if (dst > div_list[i].div_lim) { - break; - } - } + for (i = 0; (size_t) i < NUMELEMS(div_list); i++) + if (dst > div_list[i].div_lim) + break; - do { - step = div_list[i].step; - nsp = (int)((dst + step - 0.0001) / step); - spacing = (max - margin) / nsp; - i += 1; - } while ((size_t) i < NUMELEMS(div_list) && spacing > 50); + do { + step = div_list[i].step; + nsp = (int)((dst + step - 0.0001) / step); + spacing = (max - margin) / nsp; + i += 1; + } while ((size_t) i < NUMELEMS(div_list) && spacing > 50); - if (axis == x_axis) { - slim = digits + 5 + mag - mag3; - slim = graph->fontwidth * (slim + 1); - } else - slim = graph->fontheight * 3; + if (axis == x_axis) { + slim = digits + 5 + mag - mag3; + slim = graph->fontwidth * (slim + 1); + } else { + slim = graph->fontheight * 3; + } - while (i > 0 && spacing < slim + 3) { - i -= 1; - step = div_list[i].step; - nsp = (int)((dst + step - 0.0001) / step); - spacing = (max - margin) / nsp; - } + while (i > 0 && spacing < slim + 3) { + i -= 1; + step = div_list[i].step; + nsp = (int)((dst + step - 0.0001) / step); + spacing = (max - margin) / nsp; + } - if (lmt < 0) - lmt = - ceil(-lmt / step) * step; - else - lmt = floor(lmt / step) * step; + if (lmt < 0) + lmt = - ceil(-lmt / step) * step; + else + lmt = floor(lmt / step) * step; - if (hmt < 0) - hmt = - floor(-hmt / step) * step; - else - hmt = ceil(hmt / step) * step; + if (hmt < 0) + hmt = - floor(-hmt / step) * step; + else + hmt = ceil(hmt / step) * step; - dst = hmt - lmt; + dst = hmt - lmt; - lo = lmt * tenpowmag2; - hi = hmt * tenpowmag2; + lo = lmt * tenpowmag2; + hi = hmt * tenpowmag2; - nsp = (int)((dst + step - 0.0001) / step); + nsp = (int)((dst + step - 0.0001) / step); } else { - /* The user told us where to put the grid lines. They will - * not be equally spaced in this case (i.e, the right edge - * won't be a line). - */ - nsp = (int)((hi - lo) / delta); - if (nsp > 100) - nsp = 100; - step = (max - margin) * delta / (hi - lo); + /* The user told us where to put the grid lines. They will + * not be equally spaced in this case (i.e, the right edge + * won't be a line). + */ + nsp = (int)((hi - lo) / delta); + if (nsp > 100) + nsp = 100; + step = (max - margin) * delta / (hi - lo); } spacing = (max - margin) / nsp; @@ -447,53 +446,53 @@ lingrid(GRAPH *graph, double lo, double hi, double delta, int type, Axis axis) /* Reset the max coordinate to deal with round-off error. */ if (nsp && (delta == 0.0)) { - if (axis == x_axis) - graph->viewport.width = (int)(spacing * nsp); - else - graph->viewport.height = (int)(spacing * nsp); + if (axis == x_axis) + graph->viewport.width = (int)(spacing * nsp); + else + graph->viewport.height = (int)(spacing * nsp); } else if (!nsp) { - nsp = 1; + nsp = 1; } /* have to save non-intuitive variables left over - from old algorithms for redraws */ + from old algorithms for redraws */ if (axis == x_axis) { - graph->grid.xsized = 1; - graph->grid.xaxis.lin.onedec = onedec; - graph->grid.xaxis.lin.mult = mult; - graph->grid.xaxis.lin.tenpowmag = tenpowmag2; - graph->grid.xaxis.lin.tenpowmagx = tenpowmag; - graph->grid.xaxis.lin.digits = digits; - (void) strcpy(graph->grid.xaxis.lin.units, buf); - graph->grid.xaxis.lin.distance = dst; - graph->grid.xaxis.lin.lowlimit = lmt; - graph->grid.xaxis.lin.highlimit = hmt; - graph->grid.xaxis.lin.spacing = (int)spacing; - graph->grid.xaxis.lin.numspace = nsp; + graph->grid.xsized = 1; + graph->grid.xaxis.lin.onedec = onedec; + graph->grid.xaxis.lin.mult = mult; + graph->grid.xaxis.lin.tenpowmag = tenpowmag2; + graph->grid.xaxis.lin.tenpowmagx = tenpowmag; + graph->grid.xaxis.lin.digits = digits; + (void) strcpy(graph->grid.xaxis.lin.units, buf); + graph->grid.xaxis.lin.distance = dst; + graph->grid.xaxis.lin.lowlimit = lmt; + graph->grid.xaxis.lin.highlimit = hmt; + graph->grid.xaxis.lin.spacing = (int)spacing; + graph->grid.xaxis.lin.numspace = nsp; } else { - graph->grid.ysized = 1; - graph->grid.yaxis.lin.onedec = onedec; - graph->grid.yaxis.lin.mult = mult; - graph->grid.yaxis.lin.tenpowmag = tenpowmag2; - graph->grid.yaxis.lin.tenpowmagx = tenpowmag; - graph->grid.yaxis.lin.digits = digits; - (void) strcpy(graph->grid.yaxis.lin.units, buf); - graph->grid.yaxis.lin.distance = dst; - graph->grid.yaxis.lin.lowlimit = lmt; - graph->grid.yaxis.lin.highlimit = hmt; - graph->grid.yaxis.lin.spacing = (int)spacing; - graph->grid.yaxis.lin.numspace = nsp; + graph->grid.ysized = 1; + graph->grid.yaxis.lin.onedec = onedec; + graph->grid.yaxis.lin.mult = mult; + graph->grid.yaxis.lin.tenpowmag = tenpowmag2; + graph->grid.yaxis.lin.tenpowmagx = tenpowmag; + graph->grid.yaxis.lin.digits = digits; + (void) strcpy(graph->grid.yaxis.lin.units, buf); + graph->grid.yaxis.lin.distance = dst; + graph->grid.yaxis.lin.lowlimit = lmt; + graph->grid.yaxis.lin.highlimit = hmt; + graph->grid.yaxis.lin.spacing = (int)spacing; + graph->grid.yaxis.lin.numspace = nsp; } return (dd); } + /* PN static */ void drawlingrid(GRAPH *graph, char *units, int spacing, int nsp, double dst, double lmt, double hmt, bool onedec, int mult, double mag, int digits, Axis axis) { - int i, j; double m, step; char buf[LABEL_CHARS]; @@ -506,37 +505,38 @@ drawlingrid(GRAPH *graph, char *units, int spacing, int nsp, double dst, double */ SetLinestyle(1); step = floor((double) dst / nsp * 100.0 + 0.000001); - for (i = 0, m = lmt * 100.0; m - 0.001 <= hmt * 100.0; - i += spacing, m += step) + for (i = 0, m = lmt * 100.0; + m - 0.001 <= hmt * 100.0; + i += spacing, m += step) { - j = (int)m; + j = (int)m; if (j == 0) SetLinestyle(0); if (graph->grid.gridtype != GRID_NONE) { if (axis == x_axis) DevDrawLine(graph->viewportxoff + i, - graph->viewportyoff, graph->viewportxoff + i, - graph->viewport.height + graph->viewportyoff); + graph->viewportyoff, graph->viewportxoff + i, + graph->viewport.height + graph->viewportyoff); else DevDrawLine(graph->viewportxoff, - graph->viewportyoff + i, - graph->viewport.width + graph->viewportxoff, - graph->viewportyoff + i); + graph->viewportyoff + i, + graph->viewport.width + graph->viewportxoff, + graph->viewportyoff + i); } if (j == 0) SetLinestyle(1); - (void) sprintf(buf, "%.*f", digits + 1, m * mag / 100.0); + (void) sprintf(buf, "%.*f", digits + 1, m * mag / 100.0); - if (axis == x_axis) - DevDrawText(buf, graph->viewportxoff + i - - ((int) strlen(buf) * graph->fontwidth) / 2 , - (int) (graph->fontheight * 2.5)); - else - DevDrawText(buf, graph->viewportxoff - - graph->fontwidth * (int) strlen(buf), - graph->viewportyoff + i - - graph->fontheight / 2); + if (axis == x_axis) + DevDrawText(buf, graph->viewportxoff + i - + ((int) strlen(buf) * graph->fontwidth) / 2, + (int) (graph->fontheight * 2.5)); + else + DevDrawText(buf, graph->viewportxoff - + graph->fontwidth * (int) strlen(buf), + graph->viewportyoff + i - + graph->fontheight / 2); /* This is to make sure things work when delta > hi - lo. */ if (nsp == 1) @@ -544,14 +544,14 @@ drawlingrid(GRAPH *graph, char *units, int spacing, int nsp, double dst, double } if (axis == x_axis) DevDrawText(units, (int) (graph->absolute.width * 0.6), - graph->fontheight); + graph->fontheight); else DevDrawText(units, graph->fontwidth, - (int) (graph->absolute.height - 2 * graph->fontheight)); + (int) (graph->absolute.height - 2 * graph->fontheight)); DevUpdate(); - } + /* Plot a log grid. Note that we pay no attention to x- and y-delta here. */ static double * loggrid(GRAPH *graph, double lo, double hi, int type, Axis axis) @@ -566,25 +566,25 @@ loggrid(GRAPH *graph, double lo, double hi, int type, Axis axis) char buf[LABEL_CHARS], *s; if (axis == x_axis && graph->grid.xsized) { - lmt = graph->grid.xaxis.log.lmt; - hmt = graph->grid.xaxis.log.hmt; - dd[0] = pow(10.0, (double) lmt); - dd[1] = pow(10.0, (double) hmt); - return dd; + lmt = graph->grid.xaxis.log.lmt; + hmt = graph->grid.xaxis.log.hmt; + dd[0] = pow(10.0, (double) lmt); + dd[1] = pow(10.0, (double) hmt); + return dd; } else if (axis == y_axis && graph->grid.ysized) { - lmt = graph->grid.yaxis.log.lmt; - hmt = graph->grid.yaxis.log.hmt; - dd[0] = pow(10.0, (double) lmt); - dd[1] = pow(10.0, (double) hmt); - return dd; + lmt = graph->grid.yaxis.log.lmt; + hmt = graph->grid.yaxis.log.hmt; + dd[0] = pow(10.0, (double) lmt); + dd[1] = pow(10.0, (double) hmt); + return dd; } if (axis == x_axis) { - margin = graph->viewportxoff; - max = graph->absolute.width - graph->viewportxoff; + margin = graph->viewportxoff; + max = graph->absolute.width - graph->viewportxoff; } else { - margin = graph->viewportyoff; - max = graph->absolute.height - graph->viewportyoff; + margin = graph->viewportyoff; + max = graph->absolute.height - graph->viewportyoff; } /* How many orders of magnitude. We are already guaranteed that hi @@ -600,24 +600,25 @@ loggrid(GRAPH *graph, double lo, double hi, int type, Axis axis) decsp = (int)((max - margin) / decs); if (decsp < 20) { - pp = (int)ceil(20.0 / decsp); - decsp *= pp; - subs = 1; + pp = (int)ceil(20.0 / decsp); + decsp *= pp; + subs = 1; } else if (decsp > 50) { - static int divs[ ] = { 20, 10, 5, 4, 2, 1 }; + static int divs[ ] = { 20, 10, 5, 4, 2, 1 }; - k = 5.0 / decsp; + k = 5.0 / decsp; - for (i = 0; (size_t) i < NUMELEMS(divs) - 1; i++) { - j = divs[i]; - if (-log10(((double) j - 1.0) / j) > k) - break; - } + for (i = 0; (size_t) i < NUMELEMS(divs) - 1; i++) { + j = divs[i]; + if (-log10(((double) j - 1.0) / j) > k) + break; + } - subs = divs[i]; + subs = divs[i]; - } else - subs = 1; + } else { + subs = 1; + } /* Start at a line */ lmt = (int)(floor((double) lmt / pp) * pp); @@ -627,36 +628,35 @@ loggrid(GRAPH *graph, double lo, double hi, int type, Axis axis) dd[0] = pow(10.0, (double) lmt); dd[1] = pow(10.0, (double) hmt); - if ((s = ft_typabbrev(type)) != NULL) { - (void) strcpy(buf, s); - } else { - (void) strcpy(buf, "Units"); - } + if ((s = ft_typabbrev(type)) != NULL) + (void) strcpy(buf, s); + else + (void) strcpy(buf, "Units"); if (axis == x_axis) { - (void) strcpy(graph->grid.xaxis.log.units, buf); - graph->viewport.width = (int)(decs * decsp); - graph->grid.xaxis.log.hmt = hmt; - graph->grid.xaxis.log.lmt = lmt; - graph->grid.xaxis.log.decsp = decsp; - graph->grid.xaxis.log.subs = subs; - graph->grid.xaxis.log.pp = pp; - graph->grid.xsized = 1; + (void) strcpy(graph->grid.xaxis.log.units, buf); + graph->viewport.width = (int)(decs * decsp); + graph->grid.xaxis.log.hmt = hmt; + graph->grid.xaxis.log.lmt = lmt; + graph->grid.xaxis.log.decsp = decsp; + graph->grid.xaxis.log.subs = subs; + graph->grid.xaxis.log.pp = pp; + graph->grid.xsized = 1; } else { - (void) strcpy(graph->grid.yaxis.log.units, buf); - graph->viewport.height = (int)(decs * decsp); - graph->grid.yaxis.log.hmt = hmt; - graph->grid.yaxis.log.lmt = lmt; - graph->grid.yaxis.log.decsp = decsp; - graph->grid.yaxis.log.subs = subs; - graph->grid.yaxis.log.pp = pp; - graph->grid.ysized = 1; + (void) strcpy(graph->grid.yaxis.log.units, buf); + graph->viewport.height = (int)(decs * decsp); + graph->grid.yaxis.log.hmt = hmt; + graph->grid.yaxis.log.lmt = lmt; + graph->grid.yaxis.log.decsp = decsp; + graph->grid.yaxis.log.subs = subs; + graph->grid.yaxis.log.pp = pp; + graph->grid.ysized = 1; } return (dd); - } + /* PN static */ void drawloggrid(GRAPH *graph, char *units, int hmt, int lmt, int decsp, int subs, int pp, Axis axis) @@ -667,81 +667,87 @@ drawloggrid(GRAPH *graph, char *units, int hmt, int lmt, int decsp, int subs, in /* Now plot every pp'th decade line, with subs lines between them. */ if (subs > 1) - SetLinestyle(0); + SetLinestyle(0); + for (i = 0, j = lmt; j <= hmt; i += decsp * pp, j += pp) { /* Draw the decade line */ - if (graph->grid.gridtype != GRID_NONE) { - if (axis == x_axis) - DevDrawLine(graph->viewportxoff + i, - graph->viewportyoff, - graph->viewportxoff + i, - graph->viewport.height - +graph->viewportyoff); - else - DevDrawLine(graph->viewportxoff, - graph->viewportyoff + i, - graph->viewport.width - + graph->viewportxoff, - graph->viewportyoff + i); - } - if (j == -2) - (void) sprintf(buf, "0.01"); - else if (j == -1) - (void) sprintf(buf, "0.1"); - else if (j == 0) - (void) sprintf(buf, "1"); - else if (j == 1) - (void) sprintf(buf, "10"); - else if (j == 2) - (void) sprintf(buf, "100"); - else - (void) sprintf(buf, "10^%d", j); - if (axis == x_axis) - DevDrawText(buf, graph->viewportxoff + i - - ((int) strlen(buf) * graph->fontwidth) / 2, - (int) (graph->fontheight * 2.5)); - else - DevDrawText(buf, graph->viewportxoff - graph->fontwidth * - (int) (strlen(buf) + 1), - graph->viewportyoff + i - - graph->fontheight / 2); + if (graph->grid.gridtype != GRID_NONE) { + if (axis == x_axis) + DevDrawLine(graph->viewportxoff + i, + graph->viewportyoff, + graph->viewportxoff + i, + graph->viewport.height + +graph->viewportyoff); + else + DevDrawLine(graph->viewportxoff, + graph->viewportyoff + i, + graph->viewport.width + + graph->viewportxoff, + graph->viewportyoff + i); + } - if (j >= hmt) - break; + if (j == -2) + (void) sprintf(buf, "0.01"); + else if (j == -1) + (void) sprintf(buf, "0.1"); + else if (j == 0) + (void) sprintf(buf, "1"); + else if (j == 1) + (void) sprintf(buf, "10"); + else if (j == 2) + (void) sprintf(buf, "100"); + else + (void) sprintf(buf, "10^%d", j); + + if (axis == x_axis) + DevDrawText(buf, graph->viewportxoff + i - + ((int) strlen(buf) * graph->fontwidth) / 2, + (int) (graph->fontheight * 2.5)); + else + DevDrawText(buf, graph->viewportxoff - graph->fontwidth * + (int) (strlen(buf) + 1), + graph->viewportyoff + i - + graph->fontheight / 2); + + if (j >= hmt) + break; /* Now draw the subdivision lines */ - if (subs > 1) { + if (subs > 1) { SetLinestyle(1); - t = 10.0 / subs; - for (k = (int)ceil(subs / 10.0) + 1; k < subs; k++) { - m = (int)(i + decsp * log10((double) t * k)); - if (graph->grid.gridtype != GRID_NONE) { - if (axis == x_axis) - DevDrawLine(graph->viewportxoff + m, - graph->viewportyoff, - graph->viewportxoff + m, - graph->viewport.height - + graph->viewportyoff); - else - DevDrawLine(graph->viewportxoff, - graph->viewportyoff + m, - graph->viewport.width - + graph->viewportxoff, - graph->viewportyoff + m); - } - } + t = 10.0 / subs; + for (k = (int)ceil(subs / 10.0) + 1; k < subs; k++) { + m = (int)(i + decsp * log10((double) t * k)); + if (graph->grid.gridtype != GRID_NONE) { + if (axis == x_axis) + DevDrawLine(graph->viewportxoff + m, + graph->viewportyoff, + graph->viewportxoff + m, + graph->viewport.height + + graph->viewportyoff); + else + DevDrawLine(graph->viewportxoff, + graph->viewportyoff + m, + graph->viewport.width + + graph->viewportxoff, + graph->viewportyoff + m); + } + } SetLinestyle(0); - } + } } + if (axis == x_axis) DevDrawText(units, (int) (graph->absolute.width * 0.6), - graph->fontheight); + graph->fontheight); else DevDrawText(units, graph->fontwidth, - (int) (graph->absolute.height - 2 * graph->fontheight)); + (int) (graph->absolute.height - 2 * graph->fontheight)); + DevUpdate(); } + /* Polar grids */ static void @@ -753,21 +759,20 @@ polargrid(GRAPH *graph) bool centered = FALSE; /* Make sure that our area is square. */ - if (graph->viewport.width > graph->viewport.height) { + if (graph->viewport.width > graph->viewport.height) graph->viewport.width = graph->viewport.height; - } else { + else graph->viewport.height = graph->viewport.width; - } /* Make sure that the borders are even */ if (graph->viewport.width & 1) { - graph->viewport.width += 1; - graph->viewport.height += 1; + graph->viewport.width += 1; + graph->viewport.height += 1; } graph->grid.xaxis.circular.center = graph->viewport.width / 2 - + graph->viewportxoff; + + graph->viewportxoff; graph->grid.yaxis.circular.center = graph->viewport.height / 2 - + graph->viewportyoff; + + graph->viewportyoff; graph->grid.xaxis.circular.radius = graph->viewport.width / 2; @@ -782,12 +787,14 @@ polargrid(GRAPH *graph) fprintf(cp_err, "Error: 0 radius in polargrid\n"); return; } - if ((graph->data.xmin < 0) && (graph->data.ymin < 0) && - (graph->data.xmax > 0) && (graph->data.ymax > 0)) + + if ((graph->data.xmin < 0) && (graph->data.ymin < 0) && + (graph->data.xmax > 0) && (graph->data.ymax > 0)) minrad = 0; - if ((graph->data.xmin == - graph->data.xmax) - && (graph->data.ymin == -graph->data.ymax) - && (graph->data.xmin == graph->data.ymin)) + + if ((graph->data.xmin == - graph->data.xmax) && + (graph->data.ymin == -graph->data.ymax) && + (graph->data.xmin == graph->data.ymin)) centered = TRUE; mag = (int)floor(mylog10(maxrad)); @@ -809,11 +816,11 @@ polargrid(GRAPH *graph) graph->datawindow.ymin = graph->data.ymin; graph->datawindow.ymax = graph->data.ymax; if (mx > my) { - graph->datawindow.ymin -= (mx - my) / 2; - graph->datawindow.ymax += (mx - my) / 2; + graph->datawindow.ymin -= (mx - my) / 2; + graph->datawindow.ymax += (mx - my) / 2; } else if (mx < my) { - graph->datawindow.xmin -= (my - mx) / 2; - graph->datawindow.xmax += (my - mx) / 2; + graph->datawindow.xmin -= (my - mx) / 2; + graph->datawindow.xmax += (my - mx) / 2; } /* Range is square with upper bound maxrad */ @@ -839,24 +846,25 @@ drawpolargrid(GRAPH *graph) mag = graph->grid.xaxis.circular.mag; tenpowmag = pow(10.0, (double) mag); maxrad = hmt * tenpowmag; - minrad = lmt * tenpowmag; + minrad = lmt * tenpowmag; if ((minrad == 0) && ((hmt - lmt) > 5)) { - if (!((hmt - lmt) % 2)) - step = 2; - else if (!((hmt - lmt) % 3)) - step = 3; - else - step = 1; - } else - step = 1; + if (!((hmt - lmt) % 2)) + step = 2; + else if (!((hmt - lmt) % 3)) + step = 3; + else + step = 1; + } else { + step = 1; + } pixperunit = graph->grid.xaxis.circular.radius * 2 / - (graph->datawindow.xmax - graph->datawindow.xmin); + (graph->datawindow.xmax - graph->datawindow.xmin); relcx = - (int)((graph->datawindow.xmin + graph->datawindow.xmax) / 2 - * pixperunit); + * pixperunit); relcy = - (int)((graph->datawindow.ymin + graph->datawindow.ymax) / 2 - * pixperunit); + * pixperunit); /* The distance from the center of the plotting area to the center of * the logical area. @@ -865,16 +873,16 @@ drawpolargrid(GRAPH *graph) SetLinestyle(0); DevDrawArc(graph->grid.xaxis.circular.center, - graph->grid.yaxis.circular.center, - graph->grid.xaxis.circular.radius, - 0.0, 2*M_PI); + graph->grid.yaxis.circular.center, + graph->grid.xaxis.circular.radius, + 0.0, 2*M_PI); SetLinestyle(1); /* Now draw the circles. */ for (i = lmt; - (relrad = (int)(i * tenpowmag * pixperunit)) - <= dist + graph->grid.xaxis.circular.radius; - i += step) + (relrad = (int)(i * tenpowmag * pixperunit)) + <= dist + graph->grid.xaxis.circular.radius; + i += step) { cliparc((double) graph->grid.xaxis.circular.center + relcx, (double) graph->grid.yaxis.circular.center + relcy, @@ -889,47 +897,48 @@ drawpolargrid(GRAPH *graph) theta = M_PI; if (i && (relrad > dist - graph->grid.xaxis.circular.radius)) addradlabel(graph, i, theta, - (int) (graph->grid.xaxis.circular.center - - (relrad - dist) * cos(theta)), - (int) (graph->grid.yaxis.circular.center - - (relrad - dist) * sin(theta))); + (int) (graph->grid.xaxis.circular.center - + (relrad - dist) * cos(theta)), + (int) (graph->grid.yaxis.circular.center + - (relrad - dist) * sin(theta))); } /* Now draw the spokes. We have two possible cases -- first, the * origin may be inside the area -- in this case draw 12 spokes. * Otherwise, draw several spokes at convenient places. */ - if ((graph->datawindow.xmin <= 0.0) - && (graph->datawindow.xmax >= 0.0) - && (graph->datawindow.ymin <= 0.0) - && (graph->datawindow.ymax >= 0.0)) { + if ((graph->datawindow.xmin <= 0.0) && + (graph->datawindow.xmax >= 0.0) && + (graph->datawindow.ymin <= 0.0) && + (graph->datawindow.ymax >= 0.0)) + { for (i = 0; i < 12; i++) { x1 = graph->grid.xaxis.circular.center + relcx; y1 = graph->grid.yaxis.circular.center + relcy; x2 = (int)(x1 + graph->grid.xaxis.circular.radius * 2 - * cos(i * M_PI / 6)); + * cos(i * M_PI / 6)); y2 = (int)(y1 + graph->grid.xaxis.circular.radius * 2 - * sin(i * M_PI / 6)); + * sin(i * M_PI / 6)); if (!clip_to_circle(&x1, &y1, &x2, &y2, - graph->grid.xaxis.circular.center, - graph->grid.yaxis.circular.center, - graph->grid.xaxis.circular.radius)) + graph->grid.xaxis.circular.center, + graph->grid.yaxis.circular.center, + graph->grid.xaxis.circular.radius)) { - DevDrawLine(x1, y1, x2, y2); + DevDrawLine(x1, y1, x2, y2); /* Add a label here */ - /*XXXX*/ + /*XXXX*/ adddeglabel(graph, i * 30, x2, y2, x1, y1, - graph->grid.xaxis.circular.center, - graph->grid.yaxis.circular.center); + graph->grid.xaxis.circular.center, + graph->grid.yaxis.circular.center); } } } else { /* Figure out the angle that we have to fill up */ theta = 2 * asin((double) graph->grid.xaxis.circular.radius - / dist); + / dist); theta = theta * 180 / M_PI; /* Convert to degrees. */ - - /* See if we should put lines at 30, 15, 5, or 1 degree + + /* See if we should put lines at 30, 15, 5, or 1 degree * increments. */ if (theta / 30 > 3) @@ -942,33 +951,34 @@ drawpolargrid(GRAPH *graph) degs = 1; /* We'll be cheap */ - for (i = 0; i < 360; i+= degs) { + for (i = 0; i < 360; i += degs) { x1 = graph->grid.xaxis.circular.center + relcx; y1 = graph->grid.yaxis.circular.center + relcy; x2 = (int)(x1 + dist * 2 * cos(i * M_PI / 180)); y2 = (int)(y1 + dist * 2 * sin(i * M_PI / 180)); if (!clip_to_circle(&x1, &y1, &x2, &y2, - graph->grid.xaxis.circular.center, - graph->grid.yaxis.circular.center, - graph->grid.xaxis.circular.radius)) { + graph->grid.xaxis.circular.center, + graph->grid.yaxis.circular.center, + graph->grid.xaxis.circular.radius)) { DevDrawLine(x1, y1, x2, y2); /* Put on the label */ adddeglabel(graph, i, x2, y2, x1, y1, - graph->grid.xaxis.circular.center, - graph->grid.yaxis.circular.center); + graph->grid.xaxis.circular.center, + graph->grid.yaxis.circular.center); } } } (void) sprintf(buf, "e%d", mag); DevDrawText(buf, graph->grid.xaxis.circular.center - + graph->grid.xaxis.circular.radius, - graph->grid.yaxis.circular.center - - graph->grid.xaxis.circular.radius); + + graph->grid.xaxis.circular.radius, + graph->grid.yaxis.circular.center + - graph->grid.xaxis.circular.radius); DevUpdate(); return; } + /* Put a degree label on the screen, with 'deg' as the label, near point (x, y) * such that the perpendicular to (cx, cy) and (x, y) doesn't overwrite the * label. If the distance between the center and the point is @@ -998,10 +1008,11 @@ adddeglabel(GRAPH *graph, int deg, int x, int y, int cx, int cy, int lx, int ly) DevDrawText(buf, x, y); DevDrawText("o", x + (int) strlen(buf) * graph->fontwidth, - y + graph->fontheight / 2); + y + graph->fontheight / 2); return; } + /* This is kind of wierd. If dist = 0, then this is the normal case, where * the labels should go along the positive X-axis. Otherwise, to make * sure that all circles drawn have labels, put the label near the circle @@ -1027,14 +1038,14 @@ addradlabel(GRAPH *graph, int lab, double theta, int x, int y) /* Smith charts. */ -#define gr_xcenter graph->grid.xaxis.circular.center -#define gr_ycenter graph->grid.yaxis.circular.center -#define gr_radius graph->grid.xaxis.circular.radius -#define gi_fntwidth graph->fontwidth -#define gi_fntheight graph->fontheight -#define gi_maxx graph->viewport.width+graph->viewportxoff -#define gr_xmargin graph->viewportxoff -#define gr_ymargin graph->viewportyoff +#define gr_xcenter graph->grid.xaxis.circular.center +#define gr_ycenter graph->grid.yaxis.circular.center +#define gr_radius graph->grid.xaxis.circular.radius +#define gi_fntwidth graph->fontwidth +#define gi_fntheight graph->fontheight +#define gi_maxx graph->viewport.width+graph->viewportxoff +#define gr_xmargin graph->viewportxoff +#define gr_ymargin graph->viewportyoff static void smithgrid(GRAPH *graph) @@ -1045,22 +1056,21 @@ smithgrid(GRAPH *graph) SetLinestyle(0); /* Make sure that our area is square. */ - if (graph->viewport.width > graph->viewport.height) { + if (graph->viewport.width > graph->viewport.height) graph->viewport.width = graph->viewport.height; - } else { + else graph->viewport.height = graph->viewport.width; - } /* Make sure that the borders are even */ if (graph->viewport.width & 1) { - graph->viewport.width += 1; - graph->viewport.height += 1; + graph->viewport.width += 1; + graph->viewport.height += 1; } graph->grid.xaxis.circular.center = graph->viewport.width / 2 - + graph->viewportxoff; + + graph->viewportxoff; graph->grid.yaxis.circular.center = graph->viewport.height / 2 - + graph->viewportyoff; + + graph->viewportyoff; graph->grid.xaxis.circular.radius = graph->viewport.width / 2; @@ -1071,14 +1081,14 @@ smithgrid(GRAPH *graph) graph->datawindow.ymax = graph->data.ymax; if (graph->datawindow.ymin > 0) - graph->datawindow.ymin *= -1; + graph->datawindow.ymin *= -1; if (graph->datawindow.xmin > 0) - graph->datawindow.xmin *= -1; + graph->datawindow.xmin *= -1; if (graph->datawindow.ymax < 0) - graph->datawindow.ymax *= -1; + graph->datawindow.ymax *= -1; if (graph->datawindow.xmax < 0) - graph->datawindow.xmax *= -1; + graph->datawindow.xmax *= -1; if (fabs(graph->datawindow.ymin) > fabs(graph->datawindow.ymax)) graph->datawindow.ymax = - graph->datawindow.ymin; @@ -1100,20 +1110,19 @@ smithgrid(GRAPH *graph) graph->datawindow.xmax += (my - mx) / 2; } - if ((graph->datawindow.xmin == - graph->datawindow.xmax) && - (graph->datawindow.ymin == - - graph->datawindow.ymax) && (graph->datawindow.xmin == - graph->datawindow.ymin)) - centered = TRUE; + if ((graph->datawindow.xmin == - graph->datawindow.xmax) && + (graph->datawindow.ymin == - graph->datawindow.ymax) && + (graph->datawindow.xmin == graph->datawindow.ymin)) + centered = TRUE; /* Issue a warning if our data range is not normalized */ if (graph->datawindow.ymax > 1.1) { - printf("\nwarning: exceeding range for smith chart"); - printf("\nplease normalize your data to -1 < r < +1\n"); + printf("\nwarning: exceeding range for smith chart"); + printf("\nplease normalize your data to -1 < r < +1\n"); } - } + /* maximum number of circles */ #define CMAX 50 @@ -1138,8 +1147,8 @@ drawsmithgrid(GRAPH *graph) mag = (int)floor(mylog10(maxrad)); tenpowmag = pow(10.0, (double) mag); - pixperunit = graph->viewport.width / (graph->datawindow.xmax - - graph->datawindow.xmin); + pixperunit = graph->viewport.width / (graph->datawindow.xmax - + graph->datawindow.xmin); xoff = - (int)(pixperunit * (graph->datawindow.xmin + graph->datawindow.xmax) / 2); yoff = - (int)(pixperunit * (graph->datawindow.ymin + graph->datawindow.ymax) / 2); @@ -1167,7 +1176,7 @@ drawsmithgrid(GRAPH *graph) SetLinestyle(0); /* Now plot all the arc sets. Go as high as 5 times the radius that - * will fit on the screen. The base magnitude is one more than + * will fit on the screen. The base magnitude is one more than * the least magnitude that will fit... */ if (i > 20) @@ -1181,101 +1190,101 @@ drawsmithgrid(GRAPH *graph) i = (int)(j * pow(10.0, (double) mag) * pixperunit / 2); if (i / 5 > gr_radius + ((xoff > 0) ? xoff : - xoff)) break; - rnorm[k] = j * pow(10.0, (double) (mag - basemag)); - dphi[k] = 2.0 * atan(rnorm[k]); - ir[k] = pixperunit * (1 + cos(dphi[k])) / sin(dphi[k]); - rr[k] = pixperunit * 0.5 * (((1 - rnorm[k]) / (1 + rnorm[k])) + 1); + rnorm[k] = j * pow(10.0, (double) (mag - basemag)); + dphi[k] = 2.0 * atan(rnorm[k]); + ir[k] = pixperunit * (1 + cos(dphi[k])) / sin(dphi[k]); + rr[k] = pixperunit * 0.5 * (((1 - rnorm[k]) / (1 + rnorm[k])) + 1); (void) sprintf(plab, "%g", rnorm[k]); - plen = (int) strlen(plab); + plen = (int) strlen(plab); - /* See if the label will fit on the upper xaxis */ - /* wait for some k, so we don't get fooled */ - if (k > 6) { - if ((int) (gr_radius - xoff - pixperunit + 2 * rr[k]) < - plen * gi_fntwidth + 2) - break; - } - /* See if the label will fit on the lower xaxis */ - /* First look at the leftmost circle possible*/ - if ((int) (pixperunit - 2 * rr[k] + gr_radius + xoff + - fabs((double) yoff)) < plen * gi_fntwidth + 4) { - if (j == 95) { - j = 10; - mag++; - } else { - if (j < 20) - j += 1; - else - j += 5; - } - continue; - } - /* Then look at the circles following in the viewport */ - if (k>1 && (int) 2 * (rr[k-1] - rr[k]) < plen * gi_fntwidth + 4) { + /* See if the label will fit on the upper xaxis */ + /* wait for some k, so we don't get fooled */ + if (k > 6) { + if ((int) (gr_radius - xoff - pixperunit + 2 * rr[k]) < + plen * gi_fntwidth + 2) + break; + } + /* See if the label will fit on the lower xaxis */ + /* First look at the leftmost circle possible*/ + if ((int) (pixperunit - 2 * rr[k] + gr_radius + xoff + + fabs((double) yoff)) < plen * gi_fntwidth + 4) { + if (j == 95) { + j = 10; + mag++; + } else { + if (j < 20) + j += 1; + else + j += 5; + } + continue; + } + /* Then look at the circles following in the viewport */ + if (k>1 && (int) 2 * (rr[k-1] - rr[k]) < plen * gi_fntwidth + 4) { + if (j == 95) { + j = 10; + mag++; + } else { + if (j < 20) + j += 1; + else + j += 5; + } + continue; + } if (j == 95) { j = 10; mag++; } else { - if (j < 20) - j += 1; - else - j += 5; - } - continue; - } - if (j == 95) { - j = 10; - mag++; - } else { - if (j < 20) - j += 1; - else - j += 5; - } - ki[k-1] = ir[k]; + if (j < 20) + j += 1; + else + j += 5; + } + ki[k-1] = ir[k]; kr[k-1] = rr[k]; - k++; - if (k == CMAX) { - printf("drawsmithgrid: grid too complex\n"); - break; - } + k++; + if (k == CMAX) { + printf("drawsmithgrid: grid too complex\n"); + break; + } } k--; /* Now adjust the clipping radii */ for (i = 0; i < k; i++) - ks[i] = ki[i]; + ks[i] = ki[i]; for (i = k-1, j = k-1; i >= 0; i -= 2, j--) { - ki[i] = ks[j]; - if (i > 0) - ki[i-1] = ks[j]; + ki[i] = ks[j]; + if (i > 0) + ki[i-1] = ks[j]; } for (i = 0; i < k; i++) - ks[i] = kr[i]; + ks[i] = kr[i]; for (i = k-1, j = k-1; (i >= 0) && (dphi[i] > M_PI / 2); i -= 2, j--) { - kr[i] = ks[j]; - if (i > 0) - kr[i-1] = ks[j]; + kr[i] = ks[j]; + if (i > 0) + kr[i-1] = ks[j]; } - for ( ; i >= 0; i--, j--) - kr[i] = ks[j]; + for (; i >= 0; i--, j--) + kr[i] = ks[j]; if ((yoff > - gr_radius) && (yoff < gr_radius)) { zheight = (int)(gr_radius * cos(asin((double) yoff / gr_radius))); - zheight = (zheight > 0) ? zheight : - zheight; + zheight = (zheight > 0) ? zheight : - zheight; } else { - zheight = gr_radius; + zheight = gr_radius; } for (ki[k] = kr[k] = 0.0; k > 0; k--) { (void) sprintf(plab, "%g", rnorm[k]); (void) sprintf(nlab, "-%g", rnorm[k]); arcset(graph, rr[k], kr[k], ir[k], ki[k], pixperunit, - gr_radius, gr_xcenter, gr_ycenter, - xoff, yoff, plab, nlab, - (int) (0.5 + RAD_TO_DEG * (M_PI - dphi[k])), - (int) (0.5 + RAD_TO_DEG * (M_PI + dphi[k])), - gr_xcenter - zheight, - gr_xcenter + zheight); + gr_radius, gr_xcenter, gr_ycenter, + xoff, yoff, plab, nlab, + (int) (0.5 + RAD_TO_DEG * (M_PI - dphi[k])), + (int) (0.5 + RAD_TO_DEG * (M_PI + dphi[k])), + gr_xcenter - zheight, + gr_xcenter + zheight); } if (mag == 20) { fprintf(cp_err, "smithgrid: Internal Error: screwed up\n"); @@ -1285,30 +1294,32 @@ drawsmithgrid(GRAPH *graph) SetLinestyle(0); DevDrawArc(gr_xcenter, gr_ycenter, gr_radius, 0.0, 2*M_PI); -/* - if ((xoff > - gr_radius) && (xoff < gr_radius)) { - zheight = gr_radius * sin(acos((double) xoff / gr_radius)); - if (zheight < 0) - zheight = - zheight; - DevDrawLine(gr_xcenter + xoff, gr_ycenter - zheight, - gr_xcenter + xoff, gr_ycenter + zheight); - } - */ + + /* + * if ((xoff > - gr_radius) && (xoff < gr_radius)) { + * zheight = gr_radius * sin(acos((double) xoff / gr_radius)); + * if (zheight < 0) + * zheight = - zheight; + * DevDrawLine(gr_xcenter + xoff, gr_ycenter - zheight, + * gr_xcenter + xoff, gr_ycenter + zheight); + * } + */ + if ((yoff > - gr_radius) && (yoff < gr_radius)) { zheight = (int)(gr_radius * cos(asin((double) yoff / gr_radius))); if (zheight < 0) zheight = - zheight; DevDrawLine(gr_xcenter - zheight, gr_ycenter + yoff, - gr_xcenter + zheight, gr_ycenter + yoff); - DevDrawText("0", gr_xcenter + zheight + gi_fntwidth, gr_ycenter + yoff - - gi_fntheight / 2); - DevDrawText("o", gr_xcenter + zheight + gi_fntwidth * 2, gr_ycenter + yoff); - DevDrawText("180", gr_xcenter - zheight - gi_fntwidth * 5, gr_ycenter - + yoff - gi_fntheight / 2); - DevDrawText("o", gr_xcenter - zheight - gi_fntwidth * 2, gr_ycenter + yoff); + gr_xcenter + zheight, gr_ycenter + yoff); + DevDrawText("0", gr_xcenter + zheight + gi_fntwidth, gr_ycenter + yoff - + gi_fntheight / 2); + DevDrawText("o", gr_xcenter + zheight + gi_fntwidth * 2, gr_ycenter + yoff); + DevDrawText("180", gr_xcenter - zheight - gi_fntwidth * 5, gr_ycenter + + yoff - gi_fntheight / 2); + DevDrawText("o", gr_xcenter - zheight - gi_fntwidth * 2, gr_ycenter + yoff); } -/* (void) sprintf(buf, "e%d", basemag); */ + /* (void) sprintf(buf, "e%d", basemag); */ (void) sprintf(buf, "e%d", 0); DevDrawText(buf, gr_xcenter + gr_radius, gr_ycenter - gr_radius); @@ -1316,6 +1327,7 @@ drawsmithgrid(GRAPH *graph) return; } + /* Draw one arc set. The arcs should have radius rad. The outermost circle is * described by (centx, centy) and maxrad, and the distance from the right side * of the bounding circle to the logical center of the other circles in pixels @@ -1341,77 +1353,77 @@ arcset(GRAPH *graph, double rad, double prevrad, double irad, double iprevrad, d SetColor(18); cliparc((double) (centx + xoffset + radoff - rad), - (double) (centy + yoffset), rad, 2*angle, + (double) (centy + yoffset), rad, 2*angle, 2 * M_PI - 2 * angle, centx, centy, maxrad, 0); - /* These circles are not part of the smith chart * Let's draw them anyway */ cliparc((double) (centx + xoffset + radoff + rad), - (double) (centy + yoffset), rad, M_PI + 2 * angle, + (double) (centy + yoffset), rad, M_PI + 2 * angle, M_PI - 2 * angle, centx, centy, maxrad, 0); /* Draw the upper and lower circles. */ SetColor(19); aclip = cliparc((double) (centx + xoffset + radoff), - (double) (centy + yoffset + irad), irad, - (double) (M_PI * 1.5 + 2 * iangle), - (double) (M_PI * 1.5 - 2 * iangle), centx, centy, maxrad, 1); + (double) (centy + yoffset + irad), irad, + (double) (M_PI * 1.5 + 2 * iangle), + (double) (M_PI * 1.5 - 2 * iangle), centx, centy, maxrad, 1); if ((aclip > M_PI / 180) && (pdeg > 1)) { - xlab = (int)(centx + xoffset + radoff + irad * cos(aclip)); - ylab = (int)(centy + yoffset + irad * (1 + sin(aclip))); - if ((ylab - gr_ycenter) > graph->fontheight) { - SetColor(1); - adddeglabel(graph, pdeg, xlab, ylab, - gr_xcenter, gr_ycenter, gr_xcenter, gr_ycenter); -/* - ylab = centy + yoffset - irad * (1 + sin(aclip)); - adddeglabel(graph, ndeg, xlab, ylab, - gr_xcenter, gr_ycenter, gr_xcenter, gr_ycenter); - */ - SetColor(19); - } + xlab = (int)(centx + xoffset + radoff + irad * cos(aclip)); + ylab = (int)(centy + yoffset + irad * (1 + sin(aclip))); + if ((ylab - gr_ycenter) > graph->fontheight) { + SetColor(1); + adddeglabel(graph, pdeg, xlab, ylab, + gr_xcenter, gr_ycenter, gr_xcenter, gr_ycenter); + /* + ylab = centy + yoffset - irad * (1 + sin(aclip)); + adddeglabel(graph, ndeg, xlab, ylab, + gr_xcenter, gr_ycenter, gr_xcenter, gr_ycenter); + */ + SetColor(19); + } } aclip = cliparc((double) (centx + xoffset + radoff), - (double) (centy + yoffset - irad), irad, - (double) (M_PI / 2 + 2 * iangle), - (double) (M_PI / 2 - 2 * iangle), centx, centy, maxrad, - (iangle == 0)?2:0); + (double) (centy + yoffset - irad), irad, + (double) (M_PI / 2 + 2 * iangle), + (double) (M_PI / 2 - 2 * iangle), centx, centy, maxrad, + (iangle == 0) ? 2 : 0); if ((aclip >= 0 && aclip < 2*M_PI - M_PI/180) && (pdeg < 359)) { - xlab = (int)(centx + xoffset + radoff + irad * cos(aclip)); - ylab = (int)(centy + yoffset + irad * (sin(aclip) - 1)); - SetColor(1); - adddeglabel(graph, ndeg, xlab, ylab, - gr_xcenter, gr_ycenter, gr_xcenter, gr_ycenter); - SetColor(19); + xlab = (int)(centx + xoffset + radoff + irad * cos(aclip)); + ylab = (int)(centy + yoffset + irad * (sin(aclip) - 1)); + SetColor(1); + adddeglabel(graph, ndeg, xlab, ylab, + gr_xcenter, gr_ycenter, gr_xcenter, gr_ycenter); + SetColor(19); } - + /* Now toss the labels on... */ SetColor(1); x = centx + xoffset + (int)radoff - 2 * (int)rad - - gi_fntwidth * (int) strlen(plab) - 2; + gi_fntwidth * (int) strlen(plab) - 2; if ((x > pxmin) && (x < pxmax)) { - if ((yoffset > - gr_radius) && (yoffset < gr_radius)) - DevDrawText(plab, x, centy + yoffset - gi_fntheight - 1); - else - DevDrawText(plab, x, gr_ymargin - 3 * gi_fntheight - 2); + if ((yoffset > - gr_radius) && (yoffset < gr_radius)) + DevDrawText(plab, x, centy + yoffset - gi_fntheight - 1); + else + DevDrawText(plab, x, gr_ymargin - 3 * gi_fntheight - 2); } -/* - x = centx + xoffset + (int) radoff + 2 * (int)rad - - gi_fntwidth * strlen(nlab) - 2; - if ((x > gr_xmargin) && (x < gi_maxx)) - DevDrawText(nlab, x, centy + yoffset - gi_fntheight - 1); - */ + /* + * x = centx + xoffset + (int) radoff + 2 * (int)rad - + * gi_fntwidth * strlen(nlab) - 2; + * if ((x > gr_xmargin) && (x < gi_maxx)) + * DevDrawText(nlab, x, centy + yoffset - gi_fntheight - 1); + */ return; } + /* This routine draws an arc and clips it to a circle. It's hard to figure * out how it works without looking at the piece of scratch paaper I have * in front of me, so let's hope it doesn't break... - * Converted to all doubles for CRAYs + * Converted to all doubles for CRAYs */ static double @@ -1431,14 +1443,14 @@ cliparc(double cx, double cy, double rad, double start, double end, int iclipx, dist = sqrt((double) (x * x + y * y)); if (!rad || !cliprad) - return(-1); + return (-1); if (dist + rad < cliprad) { /* The arc is entirely in the boundary. */ DevDrawArc((int)cx, (int)cy, (int)rad, start, end-start); - return(flag?start:end); + return (flag?start:end); } else if ((dist - rad >= cliprad) || (rad - dist >= cliprad)) { /* The arc is outside of the boundary. */ - return(-1); + return (-1); } /* Now let's figure out the angles at which the arc crosses the * circle. We know dist != 0. @@ -1455,13 +1467,13 @@ cliparc(double cx, double cy, double rad, double start, double end, int iclipx, theta = phi; alpha = (double) (dist * dist + rad * rad - cliprad * cliprad) / - (2 * dist * rad); + (2 * dist * rad); /* Sanity check */ if (alpha > 1.0) - alpha = 0.0; + alpha = 0.0; else if (alpha < -1.0) - alpha = M_PI; + alpha = M_PI; else alpha = acos(alpha); @@ -1500,18 +1512,20 @@ cliparc(double cx, double cy, double rad, double start, double end, int iclipx, } if (in) { - if (start > d) { - double tmp; - tmp = start; - start = d; - d = tmp; - } + if (start > d) { + double tmp; + tmp = start; + start = d; + d = tmp; + } DevDrawArc((int)cx, (int)cy, (int)rad, start, d-start); - sclip = start; - eclip = d; + sclip = start; + eclip = d; } + if (d == end) - return(flag?sclip:eclip); + return (flag?sclip:eclip); + if (a1 != a2) in = in ? FALSE : TRUE; @@ -1534,21 +1548,24 @@ cliparc(double cx, double cy, double rad, double start, double end, int iclipx, if (in) { DevDrawArc((int)cx, (int)cy, (int)rad, l, d-l); - sclip = l; - eclip = d; + sclip = l; + eclip = d; } + if (d == end) - return(flag?sclip:eclip); + return (flag?sclip:eclip); + in = in ? FALSE : TRUE; - + /* And from here to the end. */ if (in) { DevDrawArc((int)cx, (int)cy, (int)rad, d, end-d); - /* special case */ - if (flag != 2) { - sclip = d; - eclip = end; - } + /* special case */ + if (flag != 2) { + sclip = d; + eclip = end; + } } - return(flag%2?sclip:eclip); + + return (flag % 2 ? sclip : eclip); } diff --git a/src/frontend/plotting/plot5.c b/src/frontend/plotting/plot5.c index c4046254d..90e973e3a 100644 --- a/src/frontend/plotting/plot5.c +++ b/src/frontend/plotting/plot5.c @@ -10,6 +10,7 @@ Copyright 1990 Regents of the University of California. All rights reserved. #include "graf.h" #include "ngspice/fteext.h" + static FILE *plotfile; #define putsi(a) \ @@ -20,14 +21,16 @@ static FILE *plotfile; #define SOLID 0 -static char *linestyle[] = { "solid", "dotted", "longdashed", "shortdashed", - "dotdashed" }; + +static char *linestyle[] = { + "solid", "dotted", "longdashed", "shortdashed", "dotdashed" }; + static int currentlinestyle = SOLID; -int + +int Plt5_Init(void) { - dispdev->numlinestyles = 4; dispdev->numcolors = 2; @@ -35,113 +38,114 @@ Plt5_Init(void) dispdev->width = 1000; dispdev->height = 1000; - return(0); - + return (0); } + int Plt5_NewViewport(GRAPH *graph) { - if ((plotfile = fopen((char*) graph->devdep, "w")) == NULL) { - graph->devdep = NULL; - perror((char*) graph->devdep); - return(1); + graph->devdep = NULL; + perror((char*) graph->devdep); + return (1); } if (graph->absolute.width) { - /* hardcopying from the scree, - ie, we are passed a copy of an existing graph */ - putc('s', plotfile); - putsi(0); - putsi(0); - putsi(graph->absolute.width); - putsi(graph->absolute.height); + /* hardcopying from the scree, + ie, we are passed a copy of an existing graph */ + putc('s', plotfile); + putsi(0); + putsi(0); + putsi(graph->absolute.width); + putsi(graph->absolute.height); - /* re-scale linestyles */ - gr_relinestyle(graph); + /* re-scale linestyles */ + gr_relinestyle(graph); } else { - /* scale space */ - putc('s', plotfile); - putsi(0); - putsi(0); - putsi(dispdev->width); - putsi(dispdev->height); + /* scale space */ + putc('s', plotfile); + putsi(0); + putsi(0); + putsi(dispdev->width); + putsi(dispdev->height); - /* reasonable values, used in gr_ for placement */ - graph->fontwidth = 12; - graph->fontheight = 24; + /* reasonable values, used in gr_ for placement */ + graph->fontwidth = 12; + graph->fontheight = 24; - graph->absolute.width = dispdev->width; - graph->absolute.height = dispdev->height; + graph->absolute.width = dispdev->width; + graph->absolute.height = dispdev->height; } /* set to NULL so graphdb doesn't incorrectly de-allocate it */ graph->devdep = NULL; - return(0); - + return (0); } + int Plt5_Close(void) { - /* in case Plt5_Close is called as part of an abort, - w/o having reached Plt5_NewViewport */ + w/o having reached Plt5_NewViewport */ if (plotfile) fclose(plotfile); + return 0; } + int Plt5_Clear(void) { - /* do nothing */ return 0; } + int Plt5_DrawLine(int x1, int y1, int x2, int y2) { - putc('l', plotfile); putsi(x1); putsi(y1); putsi(x2); putsi(y2); + return 0; } + int Plt5_Arc(int xc, int yc, int radius, double theta, double delta_theta) { - int x0,y0,x1,y1; + int x0, y0, x1, y1; - if(delta_theta < 0) { + if (delta_theta < 0) { theta += delta_theta; delta_theta = -delta_theta; } - if((2*M_PI - delta_theta)*radius < 0.5) { + if ((2*M_PI - delta_theta)*radius < 0.5) { - putc('c', plotfile); - putsi(xc); - putsi(yc); - putsi(radius); + putc('c', plotfile); + putsi(xc); + putsi(yc); + putsi(radius); - return 0; + return 0; } - while(delta_theta*radius > 0.5) { + while (delta_theta*radius > 0.5) { double delta_phi = M_PI/2; - if(delta_phi > delta_theta) + if (delta_phi > delta_theta) delta_phi = delta_theta; x0 = xc + (int)(radius * cos(theta)); @@ -164,14 +168,14 @@ Plt5_Arc(int xc, int yc, int radius, double theta, double delta_theta) return 0; } + int Plt5_Text(char *text, int x, int y) { - int savedlstyle; /* set linestyle to solid - or may get funny color text on some plotters */ + or may get funny color text on some plotters */ savedlstyle = currentlinestyle; Plt5_SetLinestyle(SOLID); @@ -185,23 +189,26 @@ Plt5_Text(char *text, int x, int y) /* restore old linestyle */ Plt5_SetLinestyle(savedlstyle); + return 0; } + int Plt5_SetLinestyle(int linestyleid) { - if (linestyleid < 0 || linestyleid > dispdev->numlinestyles) { - internalerror("bad linestyleid"); - return 0; + internalerror("bad linestyleid"); + return 0; } putc('f', plotfile); fprintf(plotfile, "%s\n", linestyle[linestyleid]); currentlinestyle = linestyleid; + return 0; } + /* ARGSUSED */ int Plt5_SetColor(int colorid) @@ -212,11 +219,10 @@ Plt5_SetColor(int colorid) return 0; } + int Plt5_Update(void) { - fflush(plotfile); return 0; } - diff --git a/src/frontend/plotting/plot5.h b/src/frontend/plotting/plot5.h index 94584f5ee..6c2a346b9 100644 --- a/src/frontend/plotting/plot5.h +++ b/src/frontend/plotting/plot5.h @@ -17,4 +17,4 @@ disp_fn_SetLinestyle_t Plt5_SetLinestyle; disp_fn_SetColor_t Plt5_SetColor; disp_fn_Update_t Plt5_Update; -#endif /* PLOT5_H_INCLUDED */ +#endif diff --git a/src/frontend/plotting/plotcurv.c b/src/frontend/plotting/plotcurv.c index 8e73dead6..b7a7ea378 100644 --- a/src/frontend/plotting/plotcurv.c +++ b/src/frontend/plotting/plotcurv.c @@ -1,6 +1,6 @@ /********** Copyright 1990 Regents of the University of California. All rights reserved. -Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group +Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group **********/ /* @@ -18,8 +18,8 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group #include "plotcurv.h" -static void plotinterval(struct dvec *v, double lo, double hi, register double *coeffs, - int degree, bool rotated); +static void plotinterval(struct dvec *v, double lo, double hi, register double *coeffs, + int degree, bool rotated); /* Plot the vector v, with scale xs. If we are doing curve-fitting, then @@ -35,18 +35,20 @@ ft_graf(struct dvec *v, struct dvec *xs, bool nostart) register double *xdata, *ydata; bool rot, increasing = FALSE; double dx = 0.0, dy = 0.0, lx = 0.0, ly = 0.0; - int dir; + int dir; /* if already started, use saved degree */ if (nostart) { - degree = currentgraph->degree; + degree = currentgraph->degree; } else { if (!cp_getvar("polydegree", CP_NUM, °ree)) degree = 1; currentgraph->degree = degree; } + if (degree > v->v_length) degree = v->v_length; + if (degree < 1) { fprintf(cp_err, "Error: polydegree is %d, can't plot...\n", degree); @@ -55,33 +57,32 @@ ft_graf(struct dvec *v, struct dvec *xs, bool nostart) if (!cp_getvar("gridsize", CP_NUM, &gridsize)) gridsize = 0; + if ((gridsize < 0) || (gridsize > 10000)) { fprintf(cp_err, "Error: bad grid size %d\n", gridsize); return; } + if (gridsize && xs) { - if( isreal(xs) ) { - increasing = (xs->v_realdata[0] < xs->v_realdata[1]); - for (i = 0; i < xs->v_length - 1; i++) - if (increasing != (xs->v_realdata[i] < - xs->v_realdata[i + 1])) { - fprintf(cp_err, - "Warning: scale not monotonic, gridsize not relevant.\n"); - gridsize = 0; - break; - } - } else { - increasing = (realpart (xs->v_compdata[0]) < - realpart(xs->v_compdata[1])); - for (i = 0; i < xs->v_length - 1; i++) - if (increasing != (realpart(xs->v_compdata[i]) < - realpart(xs->v_compdata[i + 1]))) { - fprintf(cp_err, - "Warning: scale not monotonic, gridsize not relevant.\n"); - gridsize = 0; - break; - } - } + if (isreal(xs)) { + increasing = (xs->v_realdata[0] < xs->v_realdata[1]); + for (i = 0; i < xs->v_length - 1; i++) + if (increasing != (xs->v_realdata[i] < xs->v_realdata[i + 1])) { + fprintf(cp_err, + "Warning: scale not monotonic, gridsize not relevant.\n"); + gridsize = 0; + break; + } + } else { + increasing = (realpart(xs->v_compdata[0]) < realpart(xs->v_compdata[1])); + for (i = 0; i < xs->v_length - 1; i++) + if (increasing != (realpart(xs->v_compdata[i]) < realpart(xs->v_compdata[i + 1]))) { + fprintf(cp_err, + "Warning: scale not monotonic, gridsize not relevant.\n"); + gridsize = 0; + break; + } + } } if (!nostart) @@ -92,58 +93,58 @@ ft_graf(struct dvec *v, struct dvec *xs, bool nostart) if (!xs) { for (i = 0; i < v->v_length; i++) { -/* We should do the one - point case too! - * Important for pole-zero for example - */ - if( v->v_length == 1 ) { - j = 0; - } else { - j = i-1; - if( i == 0 ) - continue; - } + /* We should do the one - point case too! + * Important for pole-zero for example + */ + if (v->v_length == 1) { + j = 0; + } else { + j = i-1; + if (i == 0) + continue; + } if (isreal(v)) { /* This isn't good but we may as well do * something useful. */ gr_point(v, v->v_realdata[i], - 0.0, /* v->v_realdata[i], */ - v->v_realdata[j], - 0.0, /* v->v_realdata[j], */ - (j==i ? 1 : i)); + 0.0, /* v->v_realdata[i], */ + v->v_realdata[j], + 0.0, /* v->v_realdata[j], */ + (j == i ? 1 : i)); } else { gr_point(v, realpart(v->v_compdata[i]), - imagpart(v->v_compdata[i]), - realpart(v->v_compdata[j]), - imagpart(v->v_compdata[j]), (j==i ? 1 : i)); + imagpart(v->v_compdata[i]), + realpart(v->v_compdata[j]), + imagpart(v->v_compdata[j]), (j == i ? 1 : i)); } - } + } gr_end(v); return; } xs->v_flags |= VF_PERMANENT; - /* First check the simple case, where we don't have to do any + /* First check the simple case, where we don't have to do any * interpolation. */ if ((degree == 1) && (gridsize == 0)) { - dir = 0; + dir = 0; for (i = 0, j = v->v_length; i < j; i++) { - dx = isreal(xs) ? xs->v_realdata[i] : - realpart(xs->v_compdata[i]); - dy = isreal(v) ? v->v_realdata[i] : - realpart(v->v_compdata[i]); - if ((i == 0 || (dir > 0 ? lx > dx : dir < 0 ? lx < dx : 0)) - && xs->v_plot && xs->v_plot->pl_scale == xs) - { - gr_point(v, dx, dy, lx, ly, 0); - } else { - gr_point(v, dx, dy, lx, ly, i); - if (!dir) - dir = lx > dx ? -1 : lx < dx ? 1 : 0; - } + dx = isreal(xs) ? xs->v_realdata[i] : + realpart(xs->v_compdata[i]); + dy = isreal(v) ? v->v_realdata[i] : + realpart(v->v_compdata[i]); + if ((i == 0 || (dir > 0 ? lx > dx : dir < 0 ? lx < dx : 0)) && + xs->v_plot && xs->v_plot->pl_scale == xs) + { + gr_point(v, dx, dy, lx, ly, 0); + } else { + gr_point(v, dx, dy, lx, ly, i); + if (!dir) + dir = lx > dx ? -1 : lx < dx ? 1 : 0; + } lx = dx; ly = dy; } @@ -160,21 +161,22 @@ ft_graf(struct dvec *v, struct dvec *xs, bool nostart) /* This is done quite differently from what we do below... */ gridbuf = TMALLOC(double, gridsize); result = TMALLOC(double, gridsize); - if (isreal(v)) + if (isreal(v)) { ydata = v->v_realdata; - else { + } else { ydata = TMALLOC(double, v->v_length); for (i = 0; i < v->v_length; i++) ydata[i] = realpart(v->v_compdata[i]); } - if (isreal(xs)) + + if (isreal(xs)) { xdata = xs->v_realdata; - else { + } else { xdata = TMALLOC(double, xs->v_length); for (i = 0; i < xs->v_length; i++) xdata[i] = realpart(xs->v_compdata[i]); } - + mm = ft_minmax(xs, TRUE); dx = (mm[1] - mm[0]) / gridsize; if (increasing) @@ -184,7 +186,7 @@ ft_graf(struct dvec *v, struct dvec *xs, bool nostart) for (i = 0, dy = mm[1]; i < gridsize; i++, dy -= dx) gridbuf[i] = dy; if (!ft_interpolate(ydata, result, xdata, v->v_length, gridbuf, - gridsize, degree)) { + gridsize, degree)) { fprintf(cp_err, "Error: can't put %s on gridsize %d\n", v->v_name, gridsize); return; @@ -194,8 +196,8 @@ ft_graf(struct dvec *v, struct dvec *xs, bool nostart) * the actual data... */ for (i = 0; i < gridsize; i++) - gr_point(v, gridbuf[i], result[i], gridbuf[i ? (i - 1) - : i], result[i ? (i - 1) : i], -1); + gr_point(v, gridbuf[i], result[i], + gridbuf[i ? (i - 1) : i], result[i ? (i - 1) : i], -1); gr_end(v); tfree(gridbuf); tfree(result); @@ -206,7 +208,7 @@ ft_graf(struct dvec *v, struct dvec *xs, bool nostart) return; } - /* We need to do curve fitting now. First get some scratch + /* We need to do curve fitting now. First get some scratch * space */ scratch = TMALLOC(double, (degree + 1) * (degree + 2)); @@ -221,6 +223,7 @@ ft_graf(struct dvec *v, struct dvec *xs, bool nostart) else for (i = 0; i <= degree; i++) ydata[i] = realpart(v->v_compdata[i]); + if (isreal(xs)) bcopy(xs->v_realdata, xdata, (size_t)(degree + 1) * sizeof(double)); else @@ -246,13 +249,11 @@ ft_graf(struct dvec *v, struct dvec *xs, bool nostart) /* Plot this part of the curve... */ for (i = 0; i < degree; i++) if (rot) - plotinterval(v, ydata[i], ydata[i + 1], result, degree, - TRUE); + plotinterval(v, ydata[i], ydata[i + 1], result, degree, TRUE); else - plotinterval(v, xdata[i], xdata[i + 1], result, degree, - FALSE); + plotinterval(v, xdata[i], xdata[i + 1], result, degree, FALSE); - /* Now plot the rest, piece by piece... l is the + /* Now plot the rest, piece by piece... l is the * last element under consideration. */ length = v->v_length; @@ -263,10 +264,12 @@ ft_graf(struct dvec *v, struct dvec *xs, bool nostart) xdata[i] = xdata[i + 1]; ydata[i] = ydata[i + 1]; } + if (isreal(v)) ydata[i] = v->v_realdata[l]; else ydata[i] = realpart(v->v_compdata[l]); + if (isreal(xs)) xdata[i] = xs->v_realdata[l]; else @@ -279,26 +282,30 @@ ft_graf(struct dvec *v, struct dvec *xs, bool nostart) break; } if (--degree == 0) { - fprintf(cp_err, - "plotcurve: Internal Error: ack...\n"); + fprintf(cp_err, + "plotcurve: Internal Error: ack...\n"); return; } } + if (rot) - plotinterval(v, ydata[degree - 1], ydata[degree], - result, degree, TRUE); + plotinterval(v, ydata[degree - 1], ydata[degree], + result, degree, TRUE); else plotinterval(v, xdata[degree - 1], xdata[degree], - result, degree, FALSE); + result, degree, FALSE); } + tfree(scratch); tfree(xdata); tfree(ydata); tfree(result); + gr_end(v); return; } + #define GRANULARITY 10 static void @@ -309,10 +316,10 @@ plotinterval(struct dvec *v, double lo, double hi, register double *coeffs, int int steps; /* - fprintf(cp_err, "plotinterval(%s, %G, %G, [ ", v->v_name, lo, hi); - for (i = 0; i <= degree; i++) - fprintf(cp_err, "%G ", coeffs[i]); - fprintf(cp_err, "], %d, %s)\n\r", degree, rotated ? "TRUE" : "FALSE"); + fprintf(cp_err, "plotinterval(%s, %G, %G, [ ", v->v_name, lo, hi); + for (i = 0; i <= degree; i++) + fprintf(cp_err, "%G ", coeffs[i]); + fprintf(cp_err, "], %d, %s)\n\r", degree, rotated ? "TRUE" : "FALSE"); */ /* This is a problem -- how do we know what granularity to use? If @@ -335,5 +342,6 @@ plotinterval(struct dvec *v, double lo, double hi, register double *coeffs, int ly = dy; /* fprintf(cp_err, "plot (%G, %G)\n\r", dx, dy); */ } + return; } diff --git a/src/frontend/plotting/plotit.c b/src/frontend/plotting/plotit.c index 1b4feec08..cf137df95 100644 --- a/src/frontend/plotting/plotit.c +++ b/src/frontend/plotting/plotit.c @@ -34,12 +34,12 @@ getlims(wordlist *wl, char *name, int number) wordlist *beg, *wk; int n; - if(number < 1) + if (number < 1) return NULL; beg = wl_find(name, wl->wl_next); - if(!beg) + if (!beg) return NULL; wk = beg->wl_next; @@ -277,15 +277,15 @@ plotit(wordlist *wl, char *hcopy, char *devname) /* add title, xlabel or ylabel, if available, with quotes '' */ if (nxlabel) { sprintf(cline, "%s xlabel '%s'", cline, nxlabel); - tfree (nxlabel); + tfree(nxlabel); } if (nylabel) { sprintf(cline, "%s ylabel '%s'", cline, nylabel); - tfree (nylabel); + tfree(nylabel); } if (ntitle) { sprintf(cline, "%s title '%s'", cline, ntitle); - tfree (ntitle); + tfree(ntitle); } /* Now extract all the parameters. */ @@ -350,73 +350,73 @@ plotit(wordlist *wl, char *hcopy, char *devname) * here because we want to catch all the grid types. */ if (getflag(wl, "lingrid")) { - if (gfound) + if (gfound) { fprintf(cp_err, "Warning: too many grid types given\n"); - else { + } else { gtype = GRID_LIN; gfound = TRUE; } } if (getflag(wl, "loglog")) { - if (gfound) + if (gfound) { fprintf(cp_err, "Warning: too many grid types given\n"); - else { + } else { gtype = GRID_LOGLOG; gfound = TRUE; } } if (getflag(wl, "nogrid")) { - if (gfound) + if (gfound) { fprintf(cp_err, "Warning: too many grid types given\n"); - else { + } else { gtype = GRID_NONE; gfound = TRUE; } } if (getflag(wl, "linear")) { - if (gfound) + if (gfound) { fprintf(cp_err, "Warning: too many grid types given\n"); - else { + } else { gtype = GRID_LIN; gfound = TRUE; } } if (getflag(wl, "xlog")) { - if (gfound) + if (gfound) { fprintf(cp_err, "Warning: too many grid types given\n"); - else { + } else { gtype = GRID_XLOG; gfound = TRUE; } } if (getflag(wl, "ylog")) { - if (gfound) + if (gfound) { fprintf(cp_err, "Warning: too many grid types given\n"); - else { + } else { gtype = GRID_YLOG; gfound = TRUE; } } if (getflag(wl, "polar")) { - if (gfound) + if (gfound) { fprintf(cp_err, "Warning: too many grid types given\n"); - else { + } else { gtype = GRID_POLAR; gfound = TRUE; } } if (getflag(wl, "smith")) { - if (gfound) + if (gfound) { fprintf(cp_err, "Warning: too many grid types given\n"); - else { + } else { gtype = GRID_SMITH; gfound = TRUE; } } if (getflag(wl, "smithgrid")) { - if (gfound) + if (gfound) { fprintf(cp_err, "Warning: too many grid types given\n"); - else { + } else { gtype = GRID_SMITHGRID; gfound = TRUE; } @@ -445,32 +445,33 @@ plotit(wordlist *wl, char *hcopy, char *devname) gtype = GRID_LIN; } gfound = TRUE; - } else + } else { gtype = GRID_LIN; + } } /* Now get the point type. */ if (getflag(wl, "linplot")) { - if (pfound) + if (pfound) { fprintf(cp_err, "Warning: too many plot types given\n"); - else { + } else { ptype = PLOT_LIN; pfound = TRUE; } } if (getflag(wl, "combplot")) { - if (pfound) + if (pfound) { fprintf(cp_err, "Warning: too many plot types given\n"); - else { + } else { ptype = PLOT_COMB; pfound = TRUE; } } if (getflag(wl, "pointplot")) { - if (pfound) + if (pfound) { fprintf(cp_err, "Warning: too many plot types given\n"); - else { + } else { ptype = PLOT_POINT; pfound = TRUE; } @@ -489,8 +490,9 @@ plotit(wordlist *wl, char *hcopy, char *devname) ptype = PLOT_LIN; } pfound = TRUE; - } else + } else { ptype = PLOT_LIN; + } } if (!sameflag || !xlabel) @@ -634,8 +636,9 @@ plotit(wordlist *wl, char *hcopy, char *devname) gtype = GRID_YLOG; } for (d = vecs; d; d = d->v_link2) - if (d->v_gridtype == GRID_SMITH || d->v_gridtype == GRID_SMITHGRID - || d->v_gridtype == GRID_POLAR) + if (d->v_gridtype == GRID_SMITH || + d->v_gridtype == GRID_SMITHGRID || + d->v_gridtype == GRID_POLAR) { gtype = d->v_gridtype; break; @@ -667,11 +670,8 @@ plotit(wordlist *wl, char *hcopy, char *devname) goto quit; } - if ((gtype == GRID_POLAR) || (gtype == GRID_SMITH - || gtype == GRID_SMITHGRID)) - { + if ((gtype == GRID_POLAR) || (gtype == GRID_SMITH || gtype == GRID_SMITHGRID)) oneval = TRUE; - } /* If we are plotting scalars, make sure there is enough * data to fit on the screen. @@ -881,8 +881,7 @@ plotit(wordlist *wl, char *hcopy, char *devname) xlims[1] = rad; ylims[0] = - rad; ylims[1] = rad; - } else if ((!xlim || !ylim) && (gtype == GRID_SMITH - || gtype == GRID_SMITHGRID)) + } else if ((!xlim || !ylim) && (gtype == GRID_SMITH || gtype == GRID_SMITHGRID)) { xlims[0] = -1.0; xlims[1] = 1.0; @@ -890,9 +889,9 @@ plotit(wordlist *wl, char *hcopy, char *devname) ylims[1] = 1.0; } - if(xlim) + if (xlim) tfree(xlim); - if(ylim) + if (ylim) tfree(ylim); /* We don't want to try to deal with smith plots for asciiplot. */ @@ -925,7 +924,7 @@ plotit(wordlist *wl, char *hcopy, char *devname) for (i = 0, ttime = tstart; i < newlen; i++, ttime += tstep) newscale[i] = ttime; - for (v = vecs; v; v= v->v_link2) { + for (v = vecs; v; v = v->v_link2) { double *newdata = TMALLOC(double, newlen); if (!ft_interpolate(v->v_realdata, newdata, diff --git a/src/frontend/plotting/plotting.c b/src/frontend/plotting/plotting.c index 75cdab9ef..8410a898a 100644 --- a/src/frontend/plotting/plotting.c +++ b/src/frontend/plotting/plotting.c @@ -7,10 +7,11 @@ struct plot constantplot = { "Constant values", Spice_Build_Date, "constants", "const", NULL, NULL, NULL, NULL, NULL, NULL, TRUE, 0 -} ; +}; struct plot *plot_cur = &constantplot; struct plot *plot_list = &constantplot; + int plotl_changed; /* TRUE after a load */ int plot_num = 1; diff --git a/src/frontend/plotting/pvec.c b/src/frontend/plotting/pvec.c index 3ac6fb302..9cde59e99 100644 --- a/src/frontend/plotting/pvec.c +++ b/src/frontend/plotting/pvec.c @@ -6,24 +6,28 @@ #include "pvec.h" #include "dimens.h" + void pvec(struct dvec *d) { char buf[BSIZE_SP], buf2[BSIZE_SP], buf3[BSIZE_SP]; sprintf(buf, " %-20s: %s, %s, %d long", - d->v_name, - ft_typenames(d->v_type), - isreal(d) ? "real" : "complex", - d->v_length); + d->v_name, + ft_typenames(d->v_type), + isreal(d) ? "real" : "complex", + d->v_length); + if (d->v_flags & VF_MINGIVEN) { sprintf(buf2, ", min = %g", d->v_minsignal); strcat(buf, buf2); } + if (d->v_flags & VF_MAXGIVEN) { sprintf(buf2, ", max = %g", d->v_maxsignal); strcat(buf, buf2); } + switch (d->v_gridtype) { case GRID_LOGLOG: strcat(buf, ", grid = loglog"); @@ -48,7 +52,7 @@ pvec(struct dvec *d) case GRID_SMITHGRID: strcat(buf, ", grid = smithgrid (not xformed)"); break; - + default: /* va: GRID_NONE or GRID_LIN */ break; } @@ -66,25 +70,28 @@ pvec(struct dvec *d) default: /* va: PLOT_LIN, */ break; } - + if (d->v_defcolor) { sprintf(buf2, ", color = %s", d->v_defcolor); strcat(buf, buf2); } + if (d->v_scale) { sprintf(buf2, ", scale = %s", d->v_scale->v_name); strcat(buf, buf2); } + if (d->v_numdims > 1) { - dimstring(d->v_dims, d->v_numdims, buf3); - sprintf(buf2, ", dims = [%s]", buf3); + dimstring(d->v_dims, d->v_numdims, buf3); + sprintf(buf2, ", dims = [%s]", buf3); strcat(buf, buf2); } - if (d->v_plot->pl_scale == d) { + + if (d->v_plot->pl_scale == d) strcat(buf, " [default scale]\n"); - } else { + else strcat(buf, "\n"); - } + out_send(buf); return; } diff --git a/src/frontend/plotting/x11.c b/src/frontend/plotting/x11.c index 11b227180..2aea3ab65 100644 --- a/src/frontend/plotting/x11.c +++ b/src/frontend/plotting/x11.c @@ -4,7 +4,7 @@ Author: 1988 Jeffrey M. Hsu **********/ /* - X11 drivers. + X11 drivers. */ #include "ngspice/ngspice.h" @@ -46,7 +46,7 @@ Author: 1988 Jeffrey M. Hsu #include "display.h" #include "graf.h" -#define RAD_TO_DEG (180.0 / M_PI) +#define RAD_TO_DEG (180.0 / M_PI) /* X dependent default parameters */ #define DEF_FONT "10x14" @@ -59,7 +59,7 @@ Author: 1988 Jeffrey M. Hsu typedef struct x11info { Window window; - int isopen; + int isopen; Widget shell, form, view, buttonbox, buttons[2]; XFontStruct *font; GC gc; @@ -72,14 +72,14 @@ typedef struct x11info { static Display *display; static GC xorgc; -static char *xlinestyles[NUMLINESTYLES] = { /* test patterns XXX */ - "\001\001\001\001", /* solid */ - "\001\002\001\002", /* dots */ - "\007\007\007\007", /* longdash */ - "\003\003\003\003", /* shortdash */ - "\007\002\002\002", /* dots longdash */ - "\003\002\001\002", /* dots shortdash */ - "\003\003\007\003", /* short/longdash */ +static char *xlinestyles[NUMLINESTYLES] = { /* test patterns XXX */ + "\001\001\001\001", /* solid */ + "\001\002\001\002", /* dots */ + "\007\007\007\007", /* longdash */ + "\003\003\003\003", /* shortdash */ + "\007\002\002\002", /* dots longdash */ + "\003\002\001\002", /* dots shortdash */ + "\003\003\007\003", /* short/longdash */ }; /* atoms for catching window delet by WM x-button */ @@ -93,9 +93,9 @@ static int X11_Open = 0; static int numdispplanes; /* static functions */ -static void initlinestyles (void); -static void initcolors (GRAPH *graph); -static void X_ScreentoData (GRAPH *graph, int x, int y, double *fx, double *fy); +static void initlinestyles(void); +static void initcolors(GRAPH *graph); +static void X_ScreentoData(GRAPH *graph, int x, int y, double *fx, double *fy); static void linear_arc(int x0, int y0, int radius, double theta, double delta_theta); static void slopelocation(GRAPH *graph, int x0, int y0); static void zoomin(GRAPH *graph); @@ -120,11 +120,9 @@ errorhandler(Display *display, XErrorEvent *errorev) } - int X11_Init(void) { - char buf[512]; char *displayname; @@ -135,10 +133,10 @@ X11_Init(void) int argc = 2; if (cp_getvar("display", CP_STRING, buf)) { - displayname = buf; + displayname = buf; } else if (!(displayname = getenv("DISPLAY"))) { - internalerror("Can't open X display."); - return (1); + internalerror("Can't open X display."); + return (1); } # ifdef DEBUG @@ -148,8 +146,8 @@ X11_Init(void) argv[0] = "ngspice"; argv[1] = displayname; /* - argv[2] = "-geometry"; - argv[3] = "=1x1+2+2"; + argv[2] = "-geometry"; + argv[3] = "=1x1+2+2"; */ /* initialize X toolkit */ @@ -164,15 +162,15 @@ X11_Init(void) /* xor gc should be a function of the pixels that are written on */ /* gcvalues.function = GXxor; */ /* this patch makes lines visible on true color displays - Guenther Roehrich 22-Jan-99 */ + Guenther Roehrich 22-Jan-99 */ gcvalues.function = GXinvert; gcvalues.line_width = 1; gcvalues.foreground = 1; gcvalues.background = 0; xorgc = XCreateGC(display, DefaultRootWindow(display), - GCLineWidth | GCFunction | GCForeground | GCBackground, - &gcvalues); + GCLineWidth | GCFunction | GCForeground | GCBackground, + &gcvalues); /* set correct information */ dispdev->numlinestyles = NUMLINESTYLES; @@ -187,90 +185,86 @@ X11_Init(void) numdispplanes = DisplayPlanes(display, DefaultScreen(display)); return (0); - } + static void initlinestyles(void) { - int i; - if (numdispplanes > 1) { - /* Dotted lines are a distraction when we have colors. */ - for (i = 2; i < NUMLINESTYLES; i++) { - xlinestyles[i] = xlinestyles[0]; - } - } - + if (numdispplanes > 1) + /* Dotted lines are a distraction when we have colors. */ + for (i = 2; i < NUMLINESTYLES; i++) + xlinestyles[i] = xlinestyles[0]; } + static void initcolors(GRAPH *graph) { int i; static char *colornames[] = { "black", /* white */ - "white", "red", "blue", - "orange", "green", "pink", - "brown", "khaki", "plum", - "orchid", "violet", "maroon", - "turquoise", "sienna", "coral", - "cyan", "magenta", "gold", - "yellow", "" - }; + "white", "red", "blue", + "orange", "green", "pink", + "brown", "khaki", "plum", + "orchid", "violet", "maroon", + "turquoise", "sienna", "coral", + "cyan", "magenta", "gold", + "yellow", "" + }; XColor visualcolor, exactcolor; char buf[BSIZE_SP], colorstring[BSIZE_SP]; int xmaxcolors = NUMCOLORS; /* note: can we get rid of this? */ if (numdispplanes == 1) { - /* black and white */ - xmaxcolors = 2; - DEVDEP(graph).colors[0] = DEVDEP(graph).view->core.background_pixel; - if (DEVDEP(graph).colors[0] == WhitePixel(display, DefaultScreen(display))) - DEVDEP(graph).colors[1] = BlackPixel(display, DefaultScreen(display)); - else - DEVDEP(graph).colors[1] = WhitePixel(display, DefaultScreen(display)); + /* black and white */ + xmaxcolors = 2; + DEVDEP(graph).colors[0] = DEVDEP(graph).view->core.background_pixel; + if (DEVDEP(graph).colors[0] == WhitePixel(display, DefaultScreen(display))) + DEVDEP(graph).colors[1] = BlackPixel(display, DefaultScreen(display)); + else + DEVDEP(graph).colors[1] = WhitePixel(display, DefaultScreen(display)); } else { - if (numdispplanes < NXPLANES) - xmaxcolors = 1 << numdispplanes; + if (numdispplanes < NXPLANES) + xmaxcolors = 1 << numdispplanes; - for (i = 0; i < xmaxcolors; i++) { - (void) sprintf(buf, "color%d", i); - if (!cp_getvar(buf, CP_STRING, colorstring)) - (void) strcpy(colorstring, colornames[i]); - if (!XAllocNamedColor(display, - DefaultColormap(display, DefaultScreen(display)), - colorstring, &visualcolor, &exactcolor)) { - (void) sprintf(ErrorMessage, - "can't get color %s\n", colorstring); - externalerror(ErrorMessage); - DEVDEP(graph).colors[i] = i ? BlackPixel(display, - DefaultScreen(display)) - : WhitePixel(display, DefaultScreen(display)); - continue; - } - DEVDEP(graph).colors[i] = visualcolor.pixel; - - - /* MW. I don't need this, everyone must know what he is doing - if (i > 0 && - DEVDEP(graph).colors[i] == DEVDEP(graph).view->core.background_pixel) { - DEVDEP(graph).colors[i] = DEVDEP(graph).colors[0]; - } */ - - } - /* MW. Set Beackgroound here */ - XSetWindowBackground(display, DEVDEP(graph).window, DEVDEP(graph).colors[0]); - -/* if (DEVDEP(graph).colors[0] != DEVDEP(graph).view->core.background_pixel) { - DEVDEP(graph).colors[0] = DEVDEP(graph).view->core.background_pixel; - } */ + for (i = 0; i < xmaxcolors; i++) { + (void) sprintf(buf, "color%d", i); + if (!cp_getvar(buf, CP_STRING, colorstring)) + (void) strcpy(colorstring, colornames[i]); + if (!XAllocNamedColor(display, + DefaultColormap(display, DefaultScreen(display)), + colorstring, &visualcolor, &exactcolor)) { + (void) sprintf(ErrorMessage, + "can't get color %s\n", colorstring); + externalerror(ErrorMessage); + DEVDEP(graph).colors[i] = i ? BlackPixel(display, + DefaultScreen(display)) + : WhitePixel(display, DefaultScreen(display)); + continue; + } + DEVDEP(graph).colors[i] = visualcolor.pixel; + + /* MW. I don't need this, everyone must know what he is doing + if (i > 0 && + DEVDEP(graph).colors[i] == DEVDEP(graph).view->core.background_pixel) { + DEVDEP(graph).colors[i] = DEVDEP(graph).colors[0]; + } */ + + } + /* MW. Set Beackgroound here */ + XSetWindowBackground(display, DEVDEP(graph).window, DEVDEP(graph).colors[0]); + + /* if (DEVDEP(graph).colors[0] != DEVDEP(graph).view->core.background_pixel) { + DEVDEP(graph).colors[0] = DEVDEP(graph).view->core.background_pixel; + } */ } for (i = xmaxcolors; i < NUMCOLORS; i++) { - DEVDEP(graph).colors[i] = DEVDEP(graph).colors[i + 1 - xmaxcolors]; + DEVDEP(graph).colors[i] = DEVDEP(graph).colors[i + 1 - xmaxcolors]; } } @@ -278,7 +272,6 @@ initcolors(GRAPH *graph) static void handlekeypressed(Widget w, XtPointer client_data, XEvent *ev, Boolean *continue_dispatch) { - XKeyEvent *keyev = & ev->xkey; GRAPH *graph = (GRAPH *) client_data; char text[4]; @@ -288,7 +281,8 @@ handlekeypressed(Widget w, XtPointer client_data, XEvent *ev, Boolean *continue_ NG_IGNORE(continue_dispatch); nbytes = XLookupString(keyev, text, 4, NULL, NULL); - if (!nbytes) return; + if (!nbytes) + return; /* write it */ PushGraphContext(graph); text[nbytes] = '\0'; @@ -298,14 +292,12 @@ handlekeypressed(Widget w, XtPointer client_data, XEvent *ev, Boolean *continue_ SaveText(graph, text, keyev->x, graph->absolute.height - keyev->y); /* warp mouse so user can type in sequence */ XWarpPointer(display, None, DEVDEP(graph).window, 0, 0, 0, 0, - keyev->x + XTextWidth(DEVDEP(graph).font, text, nbytes), - keyev->y); + keyev->x + XTextWidth(DEVDEP(graph).font, text, nbytes), + keyev->y); PopGraphContext(); - } - static void handlebuttonev(Widget w, XtPointer client_data, XEvent *ev, Boolean *continue_dispatch) { @@ -315,16 +307,16 @@ handlebuttonev(Widget w, XtPointer client_data, XEvent *ev, Boolean *continue_di NG_IGNORE(continue_dispatch); switch (ev->xbutton.button) { - case Button1: - slopelocation(graph, ev->xbutton.x, ev->xbutton.y); - break; - case Button3: - zoomin(graph); - break; + case Button1: + slopelocation(graph, ev->xbutton.x, ev->xbutton.y); + break; + case Button3: + zoomin(graph); + break; } - } + /* callback function for catching window deletion by WM x-button */ static void handle_wm_messages(Widget w, XtPointer client_data, XEvent *ev, Boolean *cont) @@ -334,10 +326,10 @@ handle_wm_messages(Widget w, XtPointer client_data, XEvent *ev, Boolean *cont) NG_IGNORE(w); NG_IGNORE(cont); - if (ev->type == ClientMessage - && ev->xclient.message_type == atom_wm_protocols - && (Atom) ev->xclient.data.l[0] == atom_wm_delete_window) { - + if (ev->type == ClientMessage && + ev->xclient.message_type == atom_wm_protocols && + (Atom) ev->xclient.data.l[0] == atom_wm_delete_window) + { RemoveWindow(graph); } } @@ -356,115 +348,109 @@ handle_wm_messages(Widget w, XtPointer client_data, XEvent *ev, Boolean *cont) int X11_NewViewport(GRAPH *graph) { - char fontname[513]; /* who knows . . . */ char *p, *q; Cursor cursor; - XSetWindowAttributes w_attrs; + XSetWindowAttributes w_attrs; XGCValues gcvalues; - static Arg formargs[ ] = { - { XtNleft, (XtArgVal) XtChainLeft }, - { XtNresizable, (XtArgVal) TRUE } + { XtNleft, (XtArgVal) XtChainLeft }, + { XtNresizable, (XtArgVal) TRUE } }; static Arg bboxargs[ ] = { - { XtNfromHoriz, (XtArgVal) NULL }, - { XtNbottom, (XtArgVal) XtChainTop }, - { XtNtop, (XtArgVal) XtChainTop }, - { XtNleft, (XtArgVal) XtChainRight }, - { XtNright, (XtArgVal) XtChainRight } + { XtNfromHoriz, (XtArgVal) NULL }, + { XtNbottom, (XtArgVal) XtChainTop }, + { XtNtop, (XtArgVal) XtChainTop }, + { XtNleft, (XtArgVal) XtChainRight }, + { XtNright, (XtArgVal) XtChainRight } }; static Arg buttonargs[ ] = { - { XtNlabel, (XtArgVal) NULL }, - { XtNfromVert, (XtArgVal) NULL }, - { XtNbottom, (XtArgVal) XtChainTop }, - { XtNtop, (XtArgVal) XtChainTop }, - { XtNleft, (XtArgVal) XtRubber }, - { XtNright, (XtArgVal) XtRubber }, - { XtNresizable, (XtArgVal) TRUE } + { XtNlabel, (XtArgVal) NULL }, + { XtNfromVert, (XtArgVal) NULL }, + { XtNbottom, (XtArgVal) XtChainTop }, + { XtNtop, (XtArgVal) XtChainTop }, + { XtNleft, (XtArgVal) XtRubber }, + { XtNright, (XtArgVal) XtRubber }, + { XtNresizable, (XtArgVal) TRUE } }; static Arg viewargs[] = { - { XtNresizable, (XtArgVal) TRUE }, - { XtNwidth, (XtArgVal) 300 }, - { XtNheight, (XtArgVal) 300 }, - { XtNright, (XtArgVal) XtChainRight } + { XtNresizable, (XtArgVal) TRUE }, + { XtNwidth, (XtArgVal) 300 }, + { XtNheight, (XtArgVal) 300 }, + { XtNright, (XtArgVal) XtChainRight } }; - int trys; + int trys; graph->devdep = TMALLOC(X11devdep, 1); /* set up new shell */ - DEVDEP(graph).shell = XtCreateApplicationShell("shell", - topLevelShellWidgetClass, NULL, 0); + DEVDEP(graph).shell = XtCreateApplicationShell + ("shell", topLevelShellWidgetClass, NULL, 0); /* set up form widget */ - DEVDEP(graph).form = XtCreateManagedWidget("form", - formWidgetClass, DEVDEP(graph).shell, formargs, XtNumber(formargs)); + DEVDEP(graph).form = XtCreateManagedWidget + ("form", formWidgetClass, DEVDEP(graph).shell, formargs, XtNumber(formargs)); /* set up viewport */ - DEVDEP(graph).view = XtCreateManagedWidget("viewport", widgetClass, - DEVDEP(graph).form, - viewargs, - XtNumber(viewargs)); + DEVDEP(graph).view = XtCreateManagedWidget + ("viewport", widgetClass, DEVDEP(graph).form, viewargs, XtNumber(viewargs)); XtAddEventHandler(DEVDEP(graph).view, ButtonPressMask, FALSE, - handlebuttonev, graph); + handlebuttonev, graph); XtAddEventHandler(DEVDEP(graph).view, KeyPressMask, FALSE, - handlekeypressed, graph); + handlekeypressed, graph); XtAddEventHandler(DEVDEP(graph).view, StructureNotifyMask, FALSE, - resize, graph); + resize, graph); XtAddEventHandler(DEVDEP(graph).view, ExposureMask, FALSE, redraw, graph); /* set up button box */ XtSetArg(bboxargs[1], XtNfromHoriz, DEVDEP(graph).view); - DEVDEP(graph).buttonbox = XtCreateManagedWidget("buttonbox", - boxWidgetClass, DEVDEP(graph).form, bboxargs, XtNumber(bboxargs)); + DEVDEP(graph).buttonbox = XtCreateManagedWidget + ("buttonbox", boxWidgetClass, DEVDEP(graph).form, bboxargs, XtNumber(bboxargs)); /* set up buttons */ XtSetArg(buttonargs[0], XtNlabel, "quit"); XtSetArg(bboxargs[1], XtNfromVert, NULL); - DEVDEP(graph).buttons[0] = XtCreateManagedWidget("quit", - commandWidgetClass, DEVDEP(graph).buttonbox, - buttonargs, 1); + DEVDEP(graph).buttons[0] = XtCreateManagedWidget + ("quit", commandWidgetClass, DEVDEP(graph).buttonbox, buttonargs, 1); XtAddCallback(DEVDEP(graph).buttons[0], XtNcallback, killwin, graph); XtSetArg(buttonargs[0], XtNlabel, "hardcopy"); XtSetArg(bboxargs[1], XtNfromVert, DEVDEP(graph).buttons[0]); - DEVDEP(graph).buttons[1] = XtCreateManagedWidget("hardcopy", - commandWidgetClass, DEVDEP(graph).buttonbox, - buttonargs, 1); + DEVDEP(graph).buttons[1] = XtCreateManagedWidget + ("hardcopy", commandWidgetClass, DEVDEP(graph).buttonbox, buttonargs, 1); XtAddCallback(DEVDEP(graph).buttons[1], XtNcallback, hardcopy, graph); /* set up fonts */ - if (!cp_getvar("font", CP_STRING, fontname)) { - (void) strcpy(fontname, DEF_FONT); - } + if (!cp_getvar("font", CP_STRING, fontname)) + (void) strcpy(fontname, DEF_FONT); for (p = fontname; *p && *p <= ' '; p++) - ; + ; + if (p != fontname) { - for (q = fontname; *p; *q++ = *p++) - ; - *q = 0; + for (q = fontname; *p; *q++ = *p++) + ; + *q = 0; } trys = 1; while (!(DEVDEP(graph).font = XLoadQueryFont(display, fontname))) { - sprintf(ErrorMessage, "can't open font %s", fontname); - strcpy(fontname, "fixed"); - if (trys > 1) { - internalerror(ErrorMessage); - RECOVERNEWVIEWPORT(); - return(1); - } - trys += 1; + sprintf(ErrorMessage, "can't open font %s", fontname); + strcpy(fontname, "fixed"); + if (trys > 1) { + internalerror(ErrorMessage); + RECOVERNEWVIEWPORT(); + return (1); + } + trys += 1; } graph->fontwidth = DEVDEP(graph).font->max_bounds.rbearing - - DEVDEP(graph).font->min_bounds.lbearing + 1; + DEVDEP(graph).font->min_bounds.lbearing + 1; graph->fontheight = DEVDEP(graph).font->max_bounds.ascent + - DEVDEP(graph).font->max_bounds.descent + 1; + DEVDEP(graph).font->max_bounds.descent + 1; XtRealizeWidget(DEVDEP(graph).shell); @@ -472,14 +458,14 @@ X11_NewViewport(GRAPH *graph) DEVDEP(graph).isopen = 0; w_attrs.bit_gravity = ForgetGravity; XChangeWindowAttributes(display, DEVDEP(graph).window, CWBitGravity, - &w_attrs); + &w_attrs); /* have to note font and set mask GCFont in XCreateGC, p.w.h. */ gcvalues.font = DEVDEP(graph).font->fid; gcvalues.line_width = MW_LINEWIDTH; gcvalues.cap_style = CapNotLast; gcvalues.function = GXcopy; DEVDEP(graph).gc = XCreateGC(display, DEVDEP(graph).window, - GCFont | GCLineWidth | GCCapStyle | GCFunction, &gcvalues); + GCFont | GCLineWidth | GCCapStyle | GCFunction, &gcvalues); /* should absolute.positions really be shell.pos? */ graph->absolute.xpos = DEVDEP(graph).view->core.x; @@ -497,17 +483,15 @@ X11_NewViewport(GRAPH *graph) /* WM_DELETE_WINDOW protocol */ atom_wm_protocols = XInternAtom(display, "WM_PROTOCOLS", False); atom_wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False); - XtAddEventHandler(DEVDEP(graph).shell, NoEventMask, True, handle_wm_messages,graph); + XtAddEventHandler(DEVDEP(graph).shell, NoEventMask, True, handle_wm_messages, graph); XSetWMProtocols(display, XtWindow(DEVDEP(graph).shell), &atom_wm_delete_window, 1); - return (0); } - /* This routine closes the X connection. - It is not to be called for finishing a graph. */ + It is not to be called for finishing a graph. */ int X11_Close(void) { @@ -524,58 +508,56 @@ X11_Close(void) return 0; } + int X11_DrawLine(int x1, int y1, int x2, int y2) { - if (DEVDEP(currentgraph).isopen) - XDrawLine(display, DEVDEP(currentgraph).window, - DEVDEP(currentgraph).gc, - x1, currentgraph->absolute.height - y1, - x2, currentgraph->absolute.height - y2); + XDrawLine(display, DEVDEP(currentgraph).window, + DEVDEP(currentgraph).gc, + x1, currentgraph->absolute.height - y1, + x2, currentgraph->absolute.height - y2); return 0; } int - X11_Arc(int x0, int y0, int radius, double theta, double delta_theta) { + int t1, t2; - int t1, t2; - - if (0 && !cp_getvar("x11lineararcs", CP_BOOL, NULL)) { - linear_arc(x0, y0, radius, theta, delta_theta); - } + if (0 && !cp_getvar("x11lineararcs", CP_BOOL, NULL)) + linear_arc(x0, y0, radius, theta, delta_theta); if (DEVDEP(currentgraph).isopen) { - t1 = (int) (64 * (180.0 / M_PI) * theta); - t2 = (int) (64 * (180.0 / M_PI) * delta_theta); - if (t2 == 0) - return 0; - XDrawArc(display, DEVDEP(currentgraph).window, DEVDEP(currentgraph).gc, - x0 - radius, - currentgraph->absolute.height - radius - y0, - (Dimension) (2 * radius), (Dimension) (2 * radius), t1, t2); + t1 = (int) (64 * (180.0 / M_PI) * theta); + t2 = (int) (64 * (180.0 / M_PI) * delta_theta); + if (t2 == 0) + return 0; + XDrawArc(display, DEVDEP(currentgraph).window, DEVDEP(currentgraph).gc, + x0 - radius, + currentgraph->absolute.height - radius - y0, + (Dimension) (2 * radius), (Dimension) (2 * radius), t1, t2); } + return 0; } + /* note: x and y are the LOWER left corner of text */ int X11_Text(char *text, int x, int y) { - /* We specify text position by lower left corner, so have to adjust for - X11's font nonsense. */ + X11's font nonsense. */ if (DEVDEP(currentgraph).isopen) - XDrawString(display, DEVDEP(currentgraph).window, - DEVDEP(currentgraph).gc, x, - currentgraph->absolute.height - - (y + DEVDEP(currentgraph).font->max_bounds.descent), - text, (int) strlen(text)); + XDrawString(display, DEVDEP(currentgraph).window, + DEVDEP(currentgraph).gc, x, + currentgraph->absolute.height + - (y + DEVDEP(currentgraph).font->max_bounds.descent), + text, (int) strlen(text)); /* note: unlike before, we do not save any text here */ return 0; @@ -605,6 +587,7 @@ X11_DefineLinestyle(int linestyleid, int mask) return 0; } + int X11_SetLinestyle(int linestyleid) { @@ -612,91 +595,92 @@ X11_SetLinestyle(int linestyleid) if (currentgraph->linestyle != linestyleid) { - if ((linestyleid == 0 || numdispplanes > 1) && linestyleid != 1) { - /* solid if linestyle 0 or if has color, allow only one - * dashed linestyle */ - values.line_style = LineSolid; - } else { - values.line_style = LineOnOffDash; - } - XChangeGC(display, DEVDEP(currentgraph).gc, GCLineStyle, &values); + if ((linestyleid == 0 || numdispplanes > 1) && linestyleid != 1) { + /* solid if linestyle 0 or if has color, allow only one + * dashed linestyle */ + values.line_style = LineSolid; + } else { + values.line_style = LineOnOffDash; + } - currentgraph->linestyle = linestyleid; - XSetDashes(display, DEVDEP(currentgraph).gc, 0, - xlinestyles[linestyleid], 4); + XChangeGC(display, DEVDEP(currentgraph).gc, GCLineStyle, &values); + + currentgraph->linestyle = linestyleid; + + XSetDashes(display, DEVDEP(currentgraph).gc, 0, + xlinestyles[linestyleid], 4); } + return 0; } + int X11_SetColor(int colorid) { - currentgraph->currentcolor = colorid; XSetForeground(display, DEVDEP(currentgraph).gc, - DEVDEP(currentgraph).colors[colorid]); + DEVDEP(currentgraph).colors[colorid]); return 0; } + int X11_Update(void) { - if (X11_Open) - XSync(display, 0); + XSync(display, 0); return 0; } + int X11_Clear(void) { - if (!noclear) /* hack so exposures look like they're handled nicely */ - XClearWindow(display, DEVDEP(currentgraph).window); + XClearWindow(display, DEVDEP(currentgraph).window); return 0; } + static void X_ScreentoData(GRAPH *graph, int x, int y, double *fx, double *fy) { - double lmin, lmax; + double lmin, lmax; - if (graph->grid.gridtype == GRID_XLOG - || graph->grid.gridtype == GRID_LOGLOG) + if (graph->grid.gridtype == GRID_XLOG || + graph->grid.gridtype == GRID_LOGLOG) { - lmin = log10(graph->datawindow.xmin); - lmax = log10(graph->datawindow.xmax); - *fx = exp(((x - graph->viewportxoff) - * (lmax - lmin) / graph->viewport.width + lmin) - * M_LN10); + lmin = log10(graph->datawindow.xmin); + lmax = log10(graph->datawindow.xmax); + *fx = exp(((x - graph->viewportxoff) + * (lmax - lmin) / graph->viewport.width + lmin) + * M_LN10); } else { - *fx = (x - graph->viewportxoff) * graph->aspectratiox + - graph->datawindow.xmin; + *fx = (x - graph->viewportxoff) * graph->aspectratiox + + graph->datawindow.xmin; } - if (graph->grid.gridtype == GRID_YLOG - || graph->grid.gridtype == GRID_LOGLOG) + if (graph->grid.gridtype == GRID_YLOG || + graph->grid.gridtype == GRID_LOGLOG) { - lmin = log10(graph->datawindow.ymin); - lmax = log10(graph->datawindow.ymax); - *fy = exp(((graph->absolute.height - y - graph->viewportxoff) - * (lmax - lmin) / graph->viewport.height + lmin) - * M_LN10); + lmin = log10(graph->datawindow.ymin); + lmax = log10(graph->datawindow.ymax); + *fy = exp(((graph->absolute.height - y - graph->viewportxoff) + * (lmax - lmin) / graph->viewport.height + lmin) + * M_LN10); } else { - *fy = ((graph->absolute.height - y) - graph->viewportyoff) - * graph->aspectratioy + graph->datawindow.ymin; + *fy = ((graph->absolute.height - y) - graph->viewportyoff) + * graph->aspectratioy + graph->datawindow.ymin; } - } - static void slopelocation(GRAPH *graph, int x0, int y0) - - /* initial position of mouse */ -{ +/* initial position of mouse */ +{ int x1, y1; int x, y; Window rootwindow, childwindow; @@ -708,22 +692,22 @@ slopelocation(GRAPH *graph, int x0, int y0) x1 = x0; y1 = y0; XQueryPointer(display, DEVDEP(graph).window, &rootwindow, &childwindow, - &rootx, &rooty, &x, &y, &state); + &rootx, &rooty, &x, &y, &state); XDrawLine(display, DEVDEP(graph).window, xorgc, x0, y0, x0, y1-1); XDrawLine(display, DEVDEP(graph).window, xorgc, x0, y1, x1, y1); while (state & Button1Mask) { - if (x != x1 || y != y1) { - XDrawLine(display, DEVDEP(graph).window, xorgc, - x0, y0, x0, y1-1); - XDrawLine(display, DEVDEP(graph).window, xorgc, - x0, y1, x1, y1); - x1 = x; - y1 = y; - XDrawLine(display, DEVDEP(graph).window, xorgc, x0, y0, x0, y1-1); - XDrawLine(display, DEVDEP(graph).window, xorgc, x0, y1, x1, y1); - } - XQueryPointer(display, DEVDEP(graph).window, &rootwindow, - &childwindow, &rootx, &rooty, &x, &y, &state); + if (x != x1 || y != y1) { + XDrawLine(display, DEVDEP(graph).window, xorgc, + x0, y0, x0, y1-1); + XDrawLine(display, DEVDEP(graph).window, xorgc, + x0, y1, x1, y1); + x1 = x; + y1 = y; + XDrawLine(display, DEVDEP(graph).window, xorgc, x0, y0, x0, y1-1); + XDrawLine(display, DEVDEP(graph).window, xorgc, x0, y1, x1, y1); + } + XQueryPointer(display, DEVDEP(graph).window, &rootwindow, + &childwindow, &rootx, &rooty, &x, &y, &state); } XDrawLine(display, DEVDEP(graph).window, xorgc, x0, y0, x0, y1-1); XDrawLine(display, DEVDEP(graph).window, xorgc, x0, y1, x1, y1); @@ -733,36 +717,35 @@ slopelocation(GRAPH *graph, int x0, int y0) /* print it out */ if (x1 == x0 && y1 == y0) { /* only one location */ - fprintf(stdout, "\nx0 = %g, y0 = %g\n", fx0, fy0); - if (graph->grid.gridtype == GRID_POLAR - || graph->grid.gridtype == GRID_SMITH - || graph->grid.gridtype == GRID_SMITHGRID) - { - angle = RAD_TO_DEG * atan2( fy0, fx0 ); - fprintf(stdout, "r0 = %g, a0 = %g\n", - sqrt( fx0*fx0 + fy0*fy0 ), - (angle>0)?angle:360.0+angle); - } - + fprintf(stdout, "\nx0 = %g, y0 = %g\n", fx0, fy0); + if (graph->grid.gridtype == GRID_POLAR || + graph->grid.gridtype == GRID_SMITH || + graph->grid.gridtype == GRID_SMITHGRID) + { + angle = RAD_TO_DEG * atan2(fy0, fx0); + fprintf(stdout, "r0 = %g, a0 = %g\n", + sqrt(fx0*fx0 + fy0*fy0), + (angle>0)?angle:360.0+angle); + } } else { /* need to print info about two points */ - fprintf(stdout, "\nx0 = %g, y0 = %g x1 = %g, y1 = %g\n", - fx0, fy0, fx1, fy1); - fprintf(stdout, "dx = %g, dy = %g\n", fx1-fx0, fy1 - fy0); - if (x1 != x0 && y1 != y0) { - /* add slope info if both dx and dy are zero, - because otherwise either dy/dx or dx/dy is zero, - which is uninteresting - */ - fprintf(stdout, "dy/dx = %g dx/dy = %g\n", - (fy1-fy0)/(fx1-fx0), (fx1-fx0)/(fy1-fy0)); - } + fprintf(stdout, "\nx0 = %g, y0 = %g x1 = %g, y1 = %g\n", + fx0, fy0, fx1, fy1); + fprintf(stdout, "dx = %g, dy = %g\n", fx1-fx0, fy1 - fy0); + if (x1 != x0 && y1 != y0) { + /* add slope info if both dx and dy are zero, + because otherwise either dy/dx or dx/dy is zero, + which is uninteresting + */ + fprintf(stdout, "dy/dx = %g dx/dy = %g\n", + (fy1-fy0)/(fx1-fx0), (fx1-fx0)/(fy1-fy0)); + } } return; - } + /* should be able to do this by sleight of hand on graph parameters */ static void zoomin(GRAPH *graph) @@ -784,7 +767,7 @@ zoomin(GRAPH *graph) /* open box and get area to zoom in on */ XQueryPointer(display, DEVDEP(graph).window, &rootwindow, - &childwindow, &rootx, &rooty, &x0, &y0, &state); + &childwindow, &rootx, &rooty, &x0, &y0, &state); x = x1 = x0 + BOXSIZE; y = y1 = y0 + BOXSIZE; @@ -796,100 +779,100 @@ zoomin(GRAPH *graph) height = BOXSIZE; XDrawRectangle(display, DEVDEP(graph).window, xorgc, - upperx, uppery, width, height); + upperx, uppery, width, height); XWarpPointer(display, None, DEVDEP(graph).window, 0, 0, 0, 0, x1, y1); while (state & Button3Mask) { - if (x != x1 || y != y1) { + if (x != x1 || y != y1) { - x1 = x; - y1 = y; + x1 = x; + y1 = y; - XDrawRectangle(display, DEVDEP(graph).window, xorgc, - upperx, uppery, width, height); + XDrawRectangle(display, DEVDEP(graph).window, xorgc, + upperx, uppery, width, height); - upperx = MIN(x1, x0); - uppery = MIN(y1, y0); + upperx = MIN(x1, x0); + uppery = MIN(y1, y0); - width = (unsigned) ABS(x1 - x0); - height = (unsigned) ABS(y1 - y0); + width = (unsigned) ABS(x1 - x0); + height = (unsigned) ABS(y1 - y0); - XDrawRectangle(display, DEVDEP(graph).window, xorgc, - upperx, uppery, width, height); - } - XQueryPointer(display, DEVDEP(graph).window, &rootwindow, - &childwindow, &rootx, &rooty, &x, &y, &state); + XDrawRectangle(display, DEVDEP(graph).window, xorgc, + upperx, uppery, width, height); + } + XQueryPointer(display, DEVDEP(graph).window, &rootwindow, + &childwindow, &rootx, &rooty, &x, &y, &state); } XDrawRectangle(display, DEVDEP(graph).window, xorgc, - upperx, uppery, width, height); + upperx, uppery, width, height); X_ScreentoData(graph, x0, y0, &fx0, &fy0); X_ScreentoData(graph, x1, y1, &fx1, &fy1); if (fx0 > fx1) { - ftemp = fx0; - fx0 = fx1; - fx1 = ftemp; + ftemp = fx0; + fx0 = fx1; + fx1 = ftemp; } if (fy0 > fy1) { - ftemp = fy0; - fy0 = fy1; - fy1 = ftemp; + ftemp = fy0; + fy0 = fy1; + fy1 = ftemp; } strncpy(buf2, graph->plotname, sizeof(buf2)); if ((t = strchr(buf2, ':')) != NULL) - *t = 0; + *t = 0; if (!eq(plot_cur->pl_typename, buf2)) { - (void) sprintf(buf, -"setplot %s; %s xlimit %.20e %.20e ylimit %.20e %.20e; setplot $curplot\n", - buf2, graph->commandline, fx0, fx1, fy0, fy1); + (void) sprintf(buf, + "setplot %s; %s xlimit %.20e %.20e ylimit %.20e %.20e; setplot $curplot\n", + buf2, graph->commandline, fx0, fx1, fy0, fy1); } else { - (void) sprintf(buf, "%s xlimit %e %e ylimit %e %e\n", - graph->commandline, fx0, fx1, fy0, fy1); + (void) sprintf(buf, "%s xlimit %e %e ylimit %e %e\n", + graph->commandline, fx0, fx1, fy0, fy1); } /* don't use the following if using GNU Readline or BSD EditLine */ #if !defined(HAVE_GNUREADLINE) && !defined(HAVE_BSDEDITLINE) { - wordlist *wl; - - /* hack for Gordon Jacobs */ - /* add to history list if plothistory is set */ - if (cp_getvar("plothistory", CP_BOOL, NULL)) { - wl = cp_parse(buf); - (void) cp_addhistent(cp_event++, wl); - } + wordlist *wl; + + /* hack for Gordon Jacobs */ + /* add to history list if plothistory is set */ + if (cp_getvar("plothistory", CP_BOOL, NULL)) { + wl = cp_parse(buf); + (void) cp_addhistent(cp_event++, wl); + } } #endif /* !defined(HAVE_GNUREADLINE) && !defined(HAVE_BSDEDITLINE) */ (void) cp_evloop(buf); - } + static void hardcopy(Widget w, XtPointer client_data, XtPointer call_data) { - NG_IGNORE(call_data); - NG_IGNORE(w); + NG_IGNORE(call_data); + NG_IGNORE(w); - /* com_hardcopy() -> gr_resize() -> setcolor() dirung postscript - printing will act on currentgraph with a DEVDEP inherited from PSdevdep. - But currentgraph had not changed its devdep, which was derived from - incompatible X11devdep, thus overwriting some variables. Here you find a - temporary remedy, until there will be a cleanup of graph handling. E.g. - CopyGraph() does not make a copy of its devdep, but just copies the pointer, - so keeping the old devdep. */ + /* com_hardcopy() -> gr_resize() -> setcolor() dirung postscript + printing will act on currentgraph with a DEVDEP inherited from PSdevdep. + But currentgraph had not changed its devdep, which was derived from + incompatible X11devdep, thus overwriting some variables. Here you find a + temporary remedy, until there will be a cleanup of graph handling. E.g. + CopyGraph() does not make a copy of its devdep, but just copies the pointer, + so keeping the old devdep. */ lasthardcopy = (GRAPH *) client_data; /* FIXME #1: this should print currentgraph with - * currentgraph dynamically bound to client_data - * FIXME #2: the !currentgraphs case, - * don't bother do call com_hardcopy - */ + * currentgraph dynamically bound to client_data + * FIXME #2: the !currentgraphs case, + * don't bother do call com_hardcopy + */ if (currentgraph) { void *devdep = currentgraph->devdep; @@ -900,10 +883,10 @@ hardcopy(Widget w, XtPointer client_data, XtPointer call_data) } } + static void killwin(Widget w, XtPointer client_data, XtPointer call_data) { - GRAPH *graph = (GRAPH *) client_data; NG_IGNORE(call_data); @@ -912,13 +895,14 @@ killwin(Widget w, XtPointer client_data, XtPointer call_data) RemoveWindow(graph); } -/* called from postcoms.c - In the command 'destroy ac2' Will remove window associated with + +/* called from postcoms.c + In the command 'destroy ac2' Will remove window associated with the plot (e.g. ac2) just before data of the plot are deleted.*/ -void +void RemoveWindow(GRAPH *graph) { - if(graph->devdep) { + if (graph->devdep) { /* Iplots are done asynchronously */ DEVDEP(graph).isopen = 0; /* MW. Not sure but DestroyGraph might free() to much - try Xt...() first */ @@ -939,7 +923,6 @@ RemoveWindow(GRAPH *graph) static void redraw(Widget w, XtPointer client_data, XEvent *event, Boolean *continue_dispatch) { - GRAPH *graph = (GRAPH *) client_data; XExposeEvent *pev = & event->xexpose; XEvent ev; @@ -951,7 +934,6 @@ redraw(Widget w, XtPointer client_data, XEvent *event, Boolean *continue_dispatc DEVDEP(graph).isopen = 1; - rects[0].x = (Position) pev->x; rects[0].y = (Position) pev->y; rects[0].width = (Dimension) pev->width; @@ -960,16 +942,15 @@ redraw(Widget w, XtPointer client_data, XEvent *event, Boolean *continue_dispatc /* XXX */ /* pull out all other expose regions that need to be redrawn */ while (n < 30 && XCheckWindowEvent(display, DEVDEP(graph).window, - ExposureMask, &ev)) { - pev = (XExposeEvent *) &ev; - rects[n].x = (Position) pev->x; - rects[n].y = (Position) pev->y; - rects[n].width = (Dimension) pev->width; - rects[n].height = (Dimension) pev->height; - n++; + ExposureMask, &ev)) { + pev = (XExposeEvent *) &ev; + rects[n].x = (Position) pev->x; + rects[n].y = (Position) pev->y; + rects[n].width = (Dimension) pev->width; + rects[n].height = (Dimension) pev->height; + n++; } - XSetClipRectangles(display, DEVDEP(graph).gc, 0, 0, - rects, n, Unsorted); + XSetClipRectangles(display, DEVDEP(graph).gc, 0, 0, rects, n, Unsorted); noclear = True; { @@ -981,13 +962,12 @@ redraw(Widget w, XtPointer client_data, XEvent *event, Boolean *continue_dispatc noclear = False; XSetClipMask(display, DEVDEP(graph).gc, None); - } + static void resize(Widget w, XtPointer client_data, XEvent *call_data, Boolean *continue_dispatch) { - GRAPH *graph = (GRAPH *) client_data; XEvent ev; @@ -998,8 +978,8 @@ resize(Widget w, XtPointer client_data, XEvent *call_data, Boolean *continue_dis Also, get rid of other StructureNotify events on this window. */ while (XCheckWindowEvent(display, DEVDEP(graph).window, - /* ExposureMask | */ StructureNotifyMask, &ev)) - ; + /* ExposureMask | */ StructureNotifyMask, &ev)) + ; XClearWindow(display, DEVDEP(graph).window); graph->absolute.width = w->core.width; @@ -1010,107 +990,102 @@ resize(Widget w, XtPointer client_data, XEvent *call_data, Boolean *continue_dis gr_resize(graph); currentgraph = tmp; } - } - int X11_Input(REQUEST *request, RESPONSE *response) { - XEvent ev; int nfds; fd_set rfds; switch (request->option) { - - case char_option: - nfds = ConnectionNumber(display) > fileno(request->fp) ? - ConnectionNumber(display) : - fileno(request->fp); - for (;;) { + case char_option: + nfds = ConnectionNumber(display) > fileno(request->fp) ? + ConnectionNumber(display) : + fileno(request->fp); - /* first read off the queue before doing the select */ - while (XtPending()) { - XtNextEvent(&ev); - XtDispatchEvent(&ev); - } + for (;;) { - /* block on ConnectionNumber and request->fp */ - /* PN: added fd_set * casting */ - FD_ZERO(&rfds); - FD_SET(fileno(request->fp), &rfds); - FD_SET(ConnectionNumber(display), &rfds); - select (nfds + 1, - &rfds, - NULL, - NULL, - NULL); - - /* handle X events first */ - if (FD_ISSET (ConnectionNumber(display), &rfds)) { - /* handle ALL X events */ - while (XtPending()) { - XtNextEvent(&ev); - XtDispatchEvent(&ev); - } - } + /* first read off the queue before doing the select */ + while (XtPending()) { + XtNextEvent(&ev); + XtDispatchEvent(&ev); + } - if (FD_ISSET (fileno(request->fp), &rfds)) { - goto out; - } + /* block on ConnectionNumber and request->fp */ + /* PN: added fd_set * casting */ + FD_ZERO(&rfds); + FD_SET(fileno(request->fp), &rfds); + FD_SET(ConnectionNumber(display), &rfds); + select (nfds + 1, + &rfds, + NULL, + NULL, + NULL); - } - break; + /* handle X events first */ + if (FD_ISSET (ConnectionNumber(display), &rfds)) + /* handle ALL X events */ + while (XtPending()) { + XtNextEvent(&ev); + XtDispatchEvent(&ev); + } - case click_option: - /* let's fake this */ - response->reply.graph = lasthardcopy; - break; + if (FD_ISSET (fileno(request->fp), &rfds)) + goto out; - case button_option: - /* sit and handle events until get a button selection */ - internalerror("button_option not implemented"); - response->option = error_option; - return 1; - break; + } + break; - case checkup_option: - /* first read off the queue before doing the select */ - while (XtPending()) { - XtNextEvent(&ev); - XtDispatchEvent(&ev); - } - break; + case click_option: + /* let's fake this */ + response->reply.graph = lasthardcopy; + break; - default: - internalerror("unrecognized input type"); - response->option = error_option; - return 1; - break; + case button_option: + /* sit and handle events until get a button selection */ + internalerror("button_option not implemented"); + response->option = error_option; + return 1; + break; + + case checkup_option: + /* first read off the queue before doing the select */ + while (XtPending()) { + XtNextEvent(&ev); + XtDispatchEvent(&ev); + } + break; + + default: + internalerror("unrecognized input type"); + response->option = error_option; + return 1; + break; } out: if (response) - response->option = request->option; + response->option = request->option; return 0; - } + static void linear_arc(int x0, int y0, int radius, double theta, double delta_theta) - /* x coordinate of center */ - /* y coordinate of center */ - /* radius of arc */ - /* initial angle ( +x axis = 0 rad ) */ - /* delta angle */ - /* - * Notes: - * Draws an arc of radius and center at (x0,y0) beginning at - * angle theta (in rad) and ending at theta + delta_theta - */ +/* x coordinate of center */ +/* y coordinate of center */ +/* radius of arc */ +/* initial angle ( +x axis = 0 rad ) */ +/* delta angle */ +/* + * Notes: + * Draws an arc of radius and center at (x0,y0) beginning at + * angle theta (in rad) and ending at theta + delta_theta + */ { int x1, y1, x2, y2; int i, s = 60; @@ -1121,17 +1096,19 @@ linear_arc(int x0, int y0, int radius, double theta, double delta_theta) dphi = delta_theta / s; - - for(i=1; i<=s; i++) { - x1 = x2; - y1 = y2; - x2 = x0 + (int)(radius * cos(theta + i*dphi)); - y2 = y0 + (int)(radius * sin(theta + i*dphi)); - X11_DrawLine(x1,y1,x2,y2); + for (i = 1; i <= s; i++) { + x1 = x2; + y1 = y2; + x2 = x0 + (int)(radius * cos(theta + i*dphi)); + y2 = y0 + (int)(radius * sin(theta + i*dphi)); + X11_DrawLine(x1, y1, x2, y2); } } -#else + +#else + int x11_dummy_symbol; /* otherwise, some linkers get upset */ + #endif /* X_DISPLAY_MISSING */ diff --git a/src/frontend/plotting/x11.h b/src/frontend/plotting/x11.h index 2d700932b..a6735ac2f 100644 --- a/src/frontend/plotting/x11.h +++ b/src/frontend/plotting/x11.h @@ -23,6 +23,6 @@ disp_fn_Clear_t X11_Clear; int X11_Input(REQUEST *request, RESPONSE *response); -#endif /* X_DISPLAY_MISSING */ +#endif -#endif /* X11_H_INCLUDED */ +#endif diff --git a/src/frontend/plotting/xgraph.c b/src/frontend/plotting/xgraph.c index c34b8f222..403541451 100644 --- a/src/frontend/plotting/xgraph.c +++ b/src/frontend/plotting/xgraph.c @@ -20,7 +20,6 @@ Author: 1992 David A. Gates, U. C. Berkeley CAD Group void ft_xgraph(double *xlims, double *ylims, char *filename, char *title, char *xlabel, char *ylabel, GRIDTYPE gridtype, PLOTTYPE plottype, struct dvec *vecs) { - FILE *file; struct dvec *v, *scale; double xval, yval; @@ -29,138 +28,142 @@ ft_xgraph(double *xlims, double *ylims, char *filename, char *title, char *xlabe char buf[BSIZE_SP], pointstyle[BSIZE_SP], *text; /* Sanity checking. */ - for ( v = vecs, numVecs = 0; v; v = v->v_link2 ) { - numVecs++; - } + for (v = vecs, numVecs = 0; v; v = v->v_link2) + numVecs++; + if (numVecs == 0) { - return; + return; } else if (numVecs > XG_MAXVECTORS) { - fprintf( cp_err, "Error: too many vectors for Xgraph.\n" ); - return; + fprintf(cp_err, "Error: too many vectors for Xgraph.\n"); + return; } + if (!cp_getvar("xbrushwidth", CP_NUM, &linewidth)) linewidth = 1; - if (linewidth < 1) linewidth = 1; + + if (linewidth < 1) + linewidth = 1; if (!cp_getvar("pointstyle", CP_STRING, pointstyle)) { markers = FALSE; } else { - if (cieq(pointstyle,"markers")) { - markers = TRUE; - } else { - markers = FALSE; - } + if (cieq(pointstyle, "markers")) + markers = TRUE; + else + markers = FALSE; } - /* Make sure the gridtype is supported. */ switch (gridtype) { case GRID_LIN: - nogrid = xlog = ylog = FALSE; - break; + nogrid = xlog = ylog = FALSE; + break; case GRID_XLOG: - xlog = TRUE; - nogrid = ylog = FALSE; - break; + xlog = TRUE; + nogrid = ylog = FALSE; + break; case GRID_YLOG: - ylog = TRUE; - nogrid = xlog = FALSE; - break; + ylog = TRUE; + nogrid = xlog = FALSE; + break; case GRID_LOGLOG: - xlog = ylog = TRUE; - nogrid = FALSE; - break; + xlog = ylog = TRUE; + nogrid = FALSE; + break; case GRID_NONE: - nogrid = TRUE; - xlog = ylog = FALSE; - break; + nogrid = TRUE; + xlog = ylog = FALSE; + break; default: - fprintf( cp_err, "Error: grid type unsupported by Xgraph.\n" ); - return; + fprintf(cp_err, "Error: grid type unsupported by Xgraph.\n"); + return; } /* Open the output file. */ if ((file = fopen(filename, "w")) == NULL) { - perror(filename); - return; + perror(filename); + return; } /* Set up the file header. */ if (title) { - text = cp_unquote(title); - fprintf( file, "TitleText: %s\n", text ); - tfree(text); + text = cp_unquote(title); + fprintf(file, "TitleText: %s\n", text); + tfree(text); } if (xlabel) { - text = cp_unquote(xlabel); - fprintf( file, "XUnitText: %s\n", text ); - tfree(text); + text = cp_unquote(xlabel); + fprintf(file, "XUnitText: %s\n", text); + tfree(text); } if (ylabel) { - text = cp_unquote(ylabel); - fprintf( file, "YUnitText: %s\n", text ); - tfree(text); + text = cp_unquote(ylabel); + fprintf(file, "YUnitText: %s\n", text); + tfree(text); } if (nogrid) { - fprintf( file, "Ticks: True\n" ); + fprintf(file, "Ticks: True\n"); } + if (xlog) { - fprintf( file, "LogX: True\n" ); - if (xlims) { - fprintf( file, "XLowLimit: % e\n", log10(xlims[0]) ); - fprintf( file, "XHighLimit: % e\n", log10(xlims[1]) ); - } + fprintf(file, "LogX: True\n"); + if (xlims) { + fprintf(file, "XLowLimit: % e\n", log10(xlims[0])); + fprintf(file, "XHighLimit: % e\n", log10(xlims[1])); + } } else { - if (xlims) { - fprintf( file, "XLowLimit: % e\n", xlims[0] ); - fprintf( file, "XHighLimit: % e\n", xlims[1] ); - } + if (xlims) { + fprintf(file, "XLowLimit: % e\n", xlims[0]); + fprintf(file, "XHighLimit: % e\n", xlims[1]); + } } + if (ylog) { - fprintf( file, "LogY: True\n" ); - if (ylims) { - fprintf( file, "YLowLimit: % e\n", log10(ylims[0]) ); - fprintf( file, "YHighLimit: % e\n", log10(ylims[1]) ); - } + fprintf(file, "LogY: True\n"); + if (ylims) { + fprintf(file, "YLowLimit: % e\n", log10(ylims[0])); + fprintf(file, "YHighLimit: % e\n", log10(ylims[1])); + } } else { - if (ylims) { - fprintf( file, "YLowLimit: % e\n", ylims[0] ); - fprintf( file, "YHighLimit: % e\n", ylims[1] ); - } + if (ylims) { + fprintf(file, "YLowLimit: % e\n", ylims[0]); + fprintf(file, "YHighLimit: % e\n", ylims[1]); + } } - fprintf( file, "LineWidth: %d\n", linewidth ); - fprintf( file, "BoundBox: True\n" ); + + fprintf(file, "LineWidth: %d\n", linewidth); + fprintf(file, "BoundBox: True\n"); + if (plottype == PLOT_COMB) { - fprintf( file, "BarGraph: True\n" ); - fprintf( file, "NoLines: True\n" ); + fprintf(file, "BarGraph: True\n"); + fprintf(file, "NoLines: True\n"); } else if (plottype == PLOT_POINT) { - if (markers) { - fprintf( file, "Markers: True\n" ); - } else { - fprintf( file, "LargePixels: True\n" ); - } - fprintf( file, "NoLines: True\n" ); + if (markers) + fprintf(file, "Markers: True\n"); + else + fprintf(file, "LargePixels: True\n"); + fprintf(file, "NoLines: True\n"); } /* Write out the data. */ - for ( v = vecs; v; v = v->v_link2 ) { - scale = v->v_scale; - if (v->v_name) { - fprintf( file, "\"%s\"\n", v->v_name ); - } - for ( i = 0; i < scale->v_length; i++ ) { - xval = isreal(scale) ? - scale->v_realdata[i] : realpart(scale->v_compdata[i]); - yval = isreal(v) ? - v->v_realdata[i] : realpart(v->v_compdata[i]); - fprintf( file, "% e % e\n", xval, yval ); - } - fprintf( file, "\n" ); - } - (void) fclose( file ); - (void) sprintf( buf, "xgraph %s &", filename ); - (void) system( buf ); + for (v = vecs; v; v = v->v_link2) { + scale = v->v_scale; + if (v->v_name) + fprintf(file, "\"%s\"\n", v->v_name); + for (i = 0; i < scale->v_length; i++) { + xval = isreal(scale) ? + scale->v_realdata[i] : realpart(scale->v_compdata[i]); + yval = isreal(v) ? + v->v_realdata[i] : realpart(v->v_compdata[i]); + fprintf(file, "% e % e\n", xval, yval); + } + fprintf(file, "\n"); + } + + (void) fclose(file); + (void) sprintf(buf, "xgraph %s &", filename); + (void) system(buf); return; } diff --git a/src/frontend/plotting/xgraph.h b/src/frontend/plotting/xgraph.h index 47cdc18c3..a45de05b2 100644 --- a/src/frontend/plotting/xgraph.h +++ b/src/frontend/plotting/xgraph.h @@ -6,11 +6,8 @@ #ifndef XGRAPH_H_INCLUDED #define XGRAPH_H_INCLUDED -void ft_xgraph(double *xlims, double *ylims, char *filename, char *title, - char *xlabel, char *ylabel, GRIDTYPE gridtype, PLOTTYPE plottype, - struct dvec *vecs); - - - +void ft_xgraph(double *xlims, double *ylims, char *filename, char *title, + char *xlabel, char *ylabel, GRIDTYPE gridtype, PLOTTYPE plottype, + struct dvec *vecs); #endif diff --git a/src/frontend/points.c b/src/frontend/points.c index 528a04331..d86309c43 100644 --- a/src/frontend/points.c +++ b/src/frontend/points.c @@ -1,6 +1,6 @@ /********** Copyright 1990 Regents of the University of California. All rights reserved. -Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group +Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group **********/ #include "ngspice/ngspice.h" @@ -18,7 +18,6 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group * the imag parts. */ - double * ft_minmax(struct dvec *v, bool real) { @@ -44,6 +43,7 @@ ft_minmax(struct dvec *v, bool real) return (res); } + /* Figure out where a point should go, given the limits of the plotting * area and the type of scale (log or linear). */ @@ -61,13 +61,14 @@ ft_findpoint(double pt, double *lims, int maxp, int minp, bool islog) tl = mylog10(lims[0]); th = mylog10(lims[1]); return (int)(((mylog10(pt) - tl) / (th - tl)) * - (maxp - minp) + minp); + (maxp - minp) + minp); } else { return (int)(((pt - lims[0]) / (lims[1] - lims[0])) * - (maxp - minp) + minp); + (maxp - minp) + minp); } } + /* Will report the minimum and maximum in "reflection coefficient" space */ @@ -83,14 +84,14 @@ ft_SMITHminmax(struct dvec *v, bool yval) for (i = 0; i < v->v_length; i++) { if (isreal(v)) - SMITH_tfm( v->v_realdata[i], 0.0, &d, &d2 ); - else - SMITH_tfm( realpart(v->v_compdata[i]), imagpart(v->v_compdata[i]), - &d, &d2 ); + SMITH_tfm(v->v_realdata[i], 0.0, &d, &d2); + else + SMITH_tfm(realpart(v->v_compdata[i]), imagpart(v->v_compdata[i]), + &d, &d2); /* Are we are looking for min/max X or Y ralue */ - if( yval ) - d = d2; + if (yval) + d = d2; if (d < res[0]) res[0] = d; @@ -100,14 +101,15 @@ ft_SMITHminmax(struct dvec *v, bool yval) return (res); } + int SMITH_tfm(double re, double im, double *x, double *y) { - double dnom; + double dnom; - dnom = (re + 1) * (re + 1) + im * im; - *x = (re * re + im * im - 1) / dnom; - *y = 2 * im / dnom; + dnom = (re + 1) * (re + 1) + im * im; + *x = (re * re + im * im - 1) / dnom; + *y = 2 * im / dnom; - return 0; + return 0; } diff --git a/src/frontend/postcoms.c b/src/frontend/postcoms.c index c032ec67b..7c5f10489 100644 --- a/src/frontend/postcoms.c +++ b/src/frontend/postcoms.c @@ -1,6 +1,6 @@ /********** Copyright 1990 Regents of the University of California. All rights reserved. -Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group +Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group **********/ /* @@ -23,10 +23,11 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group #include "variable.h" #include "parser/complete.h" /* va: throwaway */ -/* static declarations */ + static void killplot(struct plot *pl); static void DelPlotWindows(struct plot *pl); + void com_unlet(wordlist *wl) { @@ -37,18 +38,19 @@ com_unlet(wordlist *wl) return; } + /* Load in a file. */ void com_load(wordlist *wl) { -char *copypath; + char *copypath; if (!wl) ft_loadfile(ft_rawfile); else while (wl) { /*ft_loadfile(cp_unquote(wl->wl_word)); DG: bad memory leak*/ - copypath=cp_unquote(wl->wl_word);/*DG*/ + copypath = cp_unquote(wl->wl_word);/*DG*/ ft_loadfile(copypath); tfree(copypath); wl = wl->wl_next; @@ -60,6 +62,7 @@ char *copypath; return; } + /* Print out the value of an expression. When we are figuring out what to * print, link the vectors we want with v_link2... This has to be done * because of the way temporary vectors are linked together with permanent @@ -75,7 +78,7 @@ com_print(wordlist *wl) struct plot *p; bool col = TRUE, nobreak = FALSE, noprintscale, plotnames = FALSE; bool optgiven = FALSE; - char *s, *buf, *buf2; /*, buf[BSIZE_SP], buf2[BSIZE_SP];*/ + char *s, *buf, *buf2; /*, buf[BSIZE_SP], buf2[BSIZE_SP];*/ char numbuf[BSIZE_SP], numbuf2[BSIZE_SP]; /* Printnum buffers */ int ngood; @@ -83,8 +86,8 @@ com_print(wordlist *wl) return; buf = TMALLOC(char, BSIZE_SP); - buf2 = TMALLOC(char, BSIZE_SP); - + buf2 = TMALLOC(char, BSIZE_SP); + if (eq(wl->wl_word, "col")) { col = TRUE; optgiven = TRUE; @@ -117,7 +120,7 @@ com_print(wordlist *wl) plotnames = TRUE; break; } - + if (!optgiven) { /* Figure out whether col or line should be used... */ col = FALSE; @@ -125,29 +128,28 @@ com_print(wordlist *wl) if (v->v_length > 1) { col = TRUE; /* Improvement made to print cases @[sin] = (0 12 13 100K) */ - if ( (v->v_plot->pl_scale && v->v_length != v->v_plot->pl_scale->v_length) && ( (*(v->v_name))=='@') ) + if ((v->v_plot->pl_scale && v->v_length != v->v_plot->pl_scale->v_length) && (*(v->v_name) == '@')) { col = FALSE; } break; } - /* With this I have found that the vector has less elements than the SCALE vector - * in the linked PLOT. But now I must make sure in case of a print @vin[sin] or - * @vin[pulse] - * for it appear that the v->v_name begins with '@' - * And then be in this case. - */ + /* With this I have found that the vector has less elements than the SCALE vector + * in the linked PLOT. But now I must make sure in case of a print @vin[sin] or + * @vin[pulse] + * for it appear that the v->v_name begins with '@' + * And then be in this case. + */ } out_init(); if (!col) { for (v = vecs; v; v = v->v_link2) { - if (plotnames) { - (void) sprintf(buf, "%s.%s", v->v_plot->pl_typename, - vec_basename(v)); - } else { + if (plotnames) + (void) sprintf(buf, "%s.%s", v->v_plot->pl_typename, vec_basename(v)); + else (void) strcpy(buf, vec_basename(v)); - } + for (s = buf; *s; s++) ; s--; @@ -157,31 +159,26 @@ com_print(wordlist *wl) } ll = 10; - /* v->v_rlength = 1 when it comes to make a print @ M1 and does not want to come out on screen - * Multiplier factor [m]=1 - * @M1 = 0,00e+00 - * In any other case rlength not used for anything and only applies in the copy of the vectors. - */ - if (v->v_rlength == 0) - { - if (v->v_length == 1) - { - if (isreal(v)) - { + /* v->v_rlength = 1 when it comes to make a print @ M1 and does not want to come out on screen + * Multiplier factor [m]=1 + * @M1 = 0,00e+00 + * In any other case rlength not used for anything and only applies in the copy of the vectors. + */ + if (v->v_rlength == 0) { + if (v->v_length == 1) { + if (isreal(v)) { printnum(numbuf, *v->v_realdata); out_printf("%s = %s\n", buf, numbuf); } else { - printnum(numbuf, realpart(v->v_compdata[0])); + printnum(numbuf, realpart(v->v_compdata[0])); printnum(numbuf2, imagpart(v->v_compdata[0])); - out_printf("%s = %s,%s\n", buf, - numbuf, - numbuf2); + out_printf("%s = %s,%s\n", buf, numbuf, numbuf2); } } else { out_printf("%s = ( ", buf); for (i = 0; i < v->v_length; i++) if (isreal(v)) { - + printnum(numbuf, v->v_realdata[i]); (void) strcpy(buf, numbuf); out_send(buf); @@ -191,15 +188,14 @@ com_print(wordlist *wl) if (ll > 60) { out_send("\n\t"); ll = 9; - } else + } else { out_send("\t"); + } } else { - /*DG*/ - printnum(numbuf, realpart(v->v_compdata[i])); + /*DG*/ + printnum(numbuf, realpart(v->v_compdata[i])); printnum(numbuf2, imagpart(v->v_compdata[i])); - (void) sprintf(buf, "%s,%s", - numbuf, - numbuf2); + (void) sprintf(buf, "%s,%s", numbuf, numbuf2); out_send(buf); ll += (int) strlen(buf); ll = (ll + 7) / 8; @@ -207,10 +203,11 @@ com_print(wordlist *wl) if (ll > 60) { out_send("\n\t"); ll = 9; - } else + } else { out_send("\t"); + } } - out_send(")\n"); + out_send(")\n"); } //end if (v->v_length == 1) } //end if (v->v_rlength == 1) } @@ -219,10 +216,10 @@ com_print(wordlist *wl) width = i; if (width < 40) width = 40; - if (width > BSIZE_SP - 2) { + if (width > BSIZE_SP - 2) { buf = TREALLOC(char, buf, width + 1); - buf2 = TREALLOC(char, buf2, width + 1); - } + buf2 = TREALLOC(char, buf2, width + 1); + } if (cp_getvar("height", CP_NUM, &i)) height = i; if (height < 20) @@ -234,17 +231,17 @@ com_print(wordlist *wl) nobreak = TRUE; noprintscale = cp_getvar("noprintscale", CP_BOOL, NULL); bv = vecs; -nextpage: + nextpage: /* Make the first vector of every page be the scale... */ - /* XXX But what if there is no scale? e.g. op, pz */ - if (!noprintscale && bv->v_plot->pl_ndims) { + /* XXX But what if there is no scale? e.g. op, pz */ + if (!noprintscale && bv->v_plot->pl_ndims) if (bv->v_plot->pl_scale && !vec_eq(bv, bv->v_plot->pl_scale)) { nv = vec_copy(bv->v_plot->pl_scale); vec_new(nv); nv->v_link2 = bv; bv = nv; } - } + ll = 8; for (lv = bv; lv; lv = lv->v_link2) { if (isreal(lv)) @@ -258,7 +255,7 @@ nextpage: /* Print the header on the first page only. */ p = bv->v_plot; - j = (width - (int) strlen(p->pl_title)) / 2; /* Yes, keep "(int)" */ + j = (width - (int) strlen(p->pl_title)) / 2; /* Yes, keep "(int)" */ if (j < 0) j = 0; for (i = 0; i < j; i++) @@ -279,26 +276,22 @@ nextpage: out_send(buf2); (void) sprintf(buf, "Index "); for (v = bv; v && (v != lv); v = v->v_link2) { - if (isreal(v)) + if (isreal(v)) { (void) sprintf(buf2, "%-16.15s", v->v_name); - else - { - /* The frequency vector is complex but often with imaginary part = 0, - * this prevents to print two columns. - */ - if(eq(v->v_name, "frequency")) - { - if(imagpart(v->v_compdata[0])==0.0) - { + } else { + /* The frequency vector is complex but often with imaginary part = 0, + * this prevents to print two columns. + */ + if (eq(v->v_name, "frequency")) { + if (imagpart(v->v_compdata[0]) == 0.0) (void) sprintf(buf2, "%-16.15s", v->v_name); - } else (void) sprintf(buf2, "%-32.31s", v->v_name); - } - else + } else { (void) sprintf(buf2, "%-32.31s", v->v_name); + } } - (void) strcat(buf, buf2); + (void) strcat(buf, buf2); } lineno = 3; j = 0; @@ -306,7 +299,7 @@ nextpage: for (v = bv; (v && (v != lv)); v = v->v_link2) if (v->v_length > npoints) npoints = v->v_length; -pbreak: /* New page. */ + pbreak: /* New page. */ out_send(buf); out_send("\n"); for (i = 0; i < width; i++) @@ -315,7 +308,7 @@ pbreak: /* New page. */ buf2[width+1] = '\0'; out_send(buf2); lineno += 2; -loop: + loop: while ((j < npoints) && (lineno < height)) { out_printf("%d\t", j); for (v = bv; (v && (v != lv)); v = v->v_link2) { @@ -325,23 +318,18 @@ loop: else out_send("\t\t\t\t"); } else { - if (isreal(v)) - { - printnum(numbuf, v->v_realdata[j]); + if (isreal(v)) { + printnum(numbuf, v->v_realdata[j]); out_printf("%s\t", numbuf); - } - else - { - /* In case of a single frequency and have a real part avoids print imaginary part equals 0. */ - if(eq(v->v_name, "frequency") && - imagpart(v->v_compdata[j]) == 0.0) + } else { + /* In case of a single frequency and have a real part avoids print imaginary part equals 0. */ + if (eq(v->v_name, "frequency") && + imagpart(v->v_compdata[j]) == 0.0) { - printnum(numbuf, realpart(v->v_compdata[j])); - out_printf("%s\t", numbuf); - } - else - { - printnum(numbuf, realpart(v->v_compdata[j])); + printnum(numbuf, realpart(v->v_compdata[j])); + out_printf("%s\t", numbuf); + } else { + printnum(numbuf, realpart(v->v_compdata[j])); printnum(numbuf2, imagpart(v->v_compdata[j])); out_printf("%s,\t%s\t", numbuf, numbuf2); } @@ -375,6 +363,7 @@ done: return; } + /* Write out some data. write filename expr ... Some cleverness here is * required. If the user mentions a few vectors from various plots, * probably he means for them to be written out seperate plots. In any @@ -388,7 +377,7 @@ com_write(wordlist *wl) char *file, buf[BSIZE_SP]; struct pnode *n; struct dvec *d, *vecs = NULL, *lv = NULL, *end, *vv; - static wordlist all = { "all", NULL, NULL } ; + static wordlist all = { "all", NULL, NULL }; struct pnode *names; bool ascii = AsciiRawFile; bool scalefound, appendwrite; @@ -397,14 +386,16 @@ com_write(wordlist *wl) if (wl) { file = wl->wl_word; wl = wl->wl_next; - } else + } else { file = ft_rawfile; + } + if (cp_getvar("filetype", CP_STRING, buf)) { if (eq(buf, "binary")) ascii = FALSE; else if (eq(buf, "ascii")) ascii = TRUE; - else + else fprintf(cp_err, "Warning: strange file type %s\n", buf); } appendwrite = cp_getvar("appendwrite", CP_BOOL, NULL); @@ -413,8 +404,10 @@ com_write(wordlist *wl) names = ft_getpnames(wl, TRUE); else names = ft_getpnames(&all, TRUE); + if (names == NULL) return; + for (n = names; n; n = n->pn_next) { d = ft_evaluate(n); if (!d) @@ -433,7 +426,7 @@ com_write(wordlist *wl) tpl = vecs->v_plot; tpl->pl_written = TRUE; end = NULL; - bcopy(tpl, &newplot, sizeof (struct plot)); + bcopy(tpl, &newplot, sizeof(struct plot)); scalefound = FALSE; /* Figure out how many vectors are in this plot. Also look @@ -471,15 +464,14 @@ com_write(wordlist *wl) newplot.pl_dvecs = newplot.pl_scale; } - /* Now let's go through and make sure that everything that + /* Now let's go through and make sure that everything that * has its own scale has it in the plot. */ for (;;) { scalefound = FALSE; for (d = newplot.pl_dvecs; d; d = d->v_next) { if (d->v_scale) { - for (vv = newplot.pl_dvecs; vv; vv = - vv->v_next) + for (vv = newplot.pl_dvecs; vv; vv = vv->v_next) if (vec_eq(vv, d->v_scale)) break; /* We have to grab it... */ @@ -489,6 +481,7 @@ com_write(wordlist *wl) scalefound = TRUE; } } + if (!scalefound) break; /* Otherwise loop through again... */ @@ -505,42 +498,46 @@ com_write(wordlist *wl) if (lv) { lv->v_link2 = d->v_link2; d = lv; - } else + } else { vecs = d->v_link2; - } else + } + } else { lv = d; + } /* If there are more plots we want them appended... */ appendwrite = TRUE; } return; } + /* Write scattering parameters into a file with Touchstone File Format Version 1 -with command wrs2p file . -Format info from http://www.eda.org/ibis/touchstone_ver2.0/touchstone_ver2_0.pdf -See example 13 on page 15: Two port, ASCII, real-imaginary -Check if S11, S21, S12, S22 and frequency vectors are available -Check if vector Rbase is available -Call spar_write() - */ + with command wrs2p file . + Format info from http://www.eda.org/ibis/touchstone_ver2.0/touchstone_ver2_0.pdf + See example 13 on page 15: Two port, ASCII, real-imaginary + Check if S11, S21, S12, S22 and frequency vectors are available + Check if vector Rbase is available + Call spar_write() +*/ void com_write_sparam(wordlist *wl) { char *file; - char* sbuf[6]; + char *sbuf[6]; wordlist *wl_sparam; struct pnode *n; - struct dvec *d, *vecs = NULL, *lv = NULL, *end, *vv, *Rbasevec=NULL; + struct dvec *d, *vecs = NULL, *lv = NULL, *end, *vv, *Rbasevec = NULL; struct pnode *names; - bool scalefound, appendwrite=FALSE; + bool scalefound, appendwrite = FALSE; struct plot *tpl, newplot; double Rbaseval; - if (wl) { + if (wl) file = wl->wl_word; - } else + else file = "s_param.s2p"; + /* generate wordlist with all vectors required*/ sbuf[0] = "frequency"; sbuf[1] = "S11"; @@ -553,21 +550,25 @@ com_write_sparam(wordlist *wl) names = ft_getpnames(wl_sparam, TRUE); if (names == NULL) return; + for (n = names; n; n = n->pn_next) { d = ft_evaluate(n); if (!d) return; + if (vecs) lv->v_link2 = d; else vecs = d; + for (lv = d; lv->v_link2; lv = lv->v_link2) ; } + Rbasevec = vec_get("Rbase"); - if (Rbasevec) + if (Rbasevec) { Rbaseval = Rbasevec->v_realdata[0]; - else { + } else { fprintf(stderr, "Error: No Rbase vector given\n"); return; } @@ -578,7 +579,7 @@ com_write_sparam(wordlist *wl) tpl = vecs->v_plot; tpl->pl_written = TRUE; end = NULL; - bcopy(tpl, &newplot, sizeof (struct plot)); + bcopy(tpl, &newplot, sizeof(struct plot)); scalefound = FALSE; /* Figure out how many vectors are in this plot. Also look @@ -616,15 +617,14 @@ com_write_sparam(wordlist *wl) newplot.pl_dvecs = newplot.pl_scale; } - /* Now let's go through and make sure that everything that + /* Now let's go through and make sure that everything that * has its own scale has it in the plot. */ for (;;) { scalefound = FALSE; for (d = newplot.pl_dvecs; d; d = d->v_next) { if (d->v_scale) { - for (vv = newplot.pl_dvecs; vv; vv = - vv->v_next) + for (vv = newplot.pl_dvecs; vv; vv = vv->v_next) if (vec_eq(vv, d->v_scale)) break; /* We have to grab it... */ @@ -647,10 +647,12 @@ com_write_sparam(wordlist *wl) if (lv) { lv->v_link2 = d->v_link2; d = lv; - } else + } else { vecs = d->v_link2; - } else + } + } else { lv = d; + } /* If there are more plots we want them appended... */ appendwrite = TRUE; } @@ -673,8 +675,7 @@ com_transpose(wordlist *wl) d = vec_get(s); tfree(s); /*DG: Avoid Memory Leak */ if (d == NULL) - fprintf(cp_err, "Error: no such vector as %s.\n", - wl->wl_word); + fprintf(cp_err, "Error: no such vector as %s.\n", wl->wl_word); else while (d) { vec_transpose(d); @@ -686,6 +687,7 @@ com_transpose(wordlist *wl) } } + /* Take a set of vectors and form a new vector of the nth elements of each. */ void com_cross(wordlist *wl) @@ -713,20 +715,23 @@ com_cross(wordlist *wl) while (pn) { if ((n = ft_evaluate(pn)) == NULL) return; + if (!vecs) vecs = lv = n; else lv->v_link2 = n; + for (lv = n; lv->v_link2; lv = lv->v_link2) ; pn = pn->pn_next; } + for (n = vecs, i = 0; n; n = n->v_link2) { if (iscomplex(n)) comp = TRUE; i++; } - + vec_remove(newvec); v = alloc(struct dvec); v->v_name = copy(newvec); @@ -745,18 +750,18 @@ com_cross(wordlist *wl) for (n = vecs, i = 0; n; n = n->v_link2, i++) if (n->v_length > ind) { if (comp) { - realpart(v->v_compdata[i]) = - realpart(n->v_compdata[ind]); - imagpart(v->v_compdata[i]) = - imagpart(n->v_compdata[ind]); - } else + realpart(v->v_compdata[i]) = realpart(n->v_compdata[ind]); + imagpart(v->v_compdata[i]) = imagpart(n->v_compdata[ind]); + } else { v->v_realdata[i] = n->v_realdata[ind]; + } } else { if (comp) { realpart(v->v_compdata[i]) = 0.0; imagpart(v->v_compdata[i]) = 0.0; - } else + } else { v->v_realdata[i] = 0.0; + } } vec_new(v); v->v_flags |= VF_PERMANENT; @@ -764,50 +769,46 @@ com_cross(wordlist *wl) return; } + void com_destroy(wordlist *wl) { struct plot *pl, *npl = NULL; if (!wl) { - DelPlotWindows(plot_cur); - killplot(plot_cur); - } - else if (eq(wl->wl_word, "all")) { + DelPlotWindows(plot_cur); + killplot(plot_cur); + } else if (eq(wl->wl_word, "all")) { for (pl = plot_list; pl; pl = npl) { npl = pl->pl_next; - if (!eq(pl->pl_typename, "const")) - { - DelPlotWindows(pl); + if (!eq(pl->pl_typename, "const")) { + DelPlotWindows(pl); killplot(pl); + } else { + plot_num = 1; } - else - { - plot_num=1; - } } } else { while (wl) { for (pl = plot_list; pl; pl = pl->pl_next) if (eq(pl->pl_typename, wl->wl_word)) break; - if (pl) - { + if (pl) { DelPlotWindows(pl); killplot(pl); - } - else + } else { fprintf(cp_err, "Error: no such plot %s\n", wl->wl_word); + } wl = wl->wl_next; } } return; } + static void killplot(struct plot *pl) { - struct dvec *v, *nv = NULL; struct plot *op; @@ -831,7 +832,7 @@ killplot(struct plot *pl) break; if (!op) fprintf(cp_err, - "Internal Error: kill plot -- not in list\n"); + "Internal Error: kill plot -- not in list\n"); op->pl_next = pl->pl_next; if (pl == plot_cur) plot_cur = op; @@ -842,44 +843,46 @@ killplot(struct plot *pl) wl_free(pl->pl_commands); tfree(pl->pl_date); /* va: also tfree (memory leak) */ if (pl->pl_ccom) /* va: also tfree (memory leak) */ - { throwaway((struct ccom *)pl->pl_ccom); - } - if (pl->pl_env) /* The 'environment' for this plot. */ - { - /* va: HOW to do? */ - printf("va: killplot should tfree pl->pl_env=(%p)\n", pl->pl_env); fflush(stdout); + + if (pl->pl_env) { /* The 'environment' for this plot. */ + /* va: HOW to do? */ + printf("va: killplot should tfree pl->pl_env=(%p)\n", pl->pl_env); + fflush(stdout); } tfree(pl); /* va: also tfree pl itself (memory leak) */ - + return; } -/* delete all windows with graphs dedrived from a given plot */ + +/* delete all windows with graphs dedrived from a given plot */ static void DelPlotWindows(struct plot *pl) { -/* do this only if windows or X11 is defined */ + /* do this only if windows or X11 is defined */ #if defined(HAS_WINDOWS) || !defined(X_DISPLAY_MISSING) - GRAPH *dgraph; - int n; - /* find and remove all graph structures derived from a given plot */ - for (n=1; n < 100; n++) { /* should be no more than 100 */ - dgraph = FindGraph(n); - if(dgraph) { - if (ciprefix(pl->pl_typename, dgraph->plotname)) - RemoveWindow(dgraph); - } -/* We have to run through all potential graph ids. If some numbers are - already missing, 'else break;' might miss the plotwindow to be removed. */ -/* else - break; */ - } + GRAPH *dgraph; + int n; + /* find and remove all graph structures derived from a given plot */ + for (n = 1; n < 100; n++) { /* should be no more than 100 */ + dgraph = FindGraph(n); + if (dgraph) { + if (ciprefix(pl->pl_typename, dgraph->plotname)) + RemoveWindow(dgraph); + } + /* We have to run through all potential graph ids. If some numbers are + already missing, 'else break;' might miss the plotwindow to be removed. */ + /* else + break; + */ + } #else NG_IGNORE(pl); #endif } + void com_splot(wordlist *wl) { @@ -896,7 +899,7 @@ com_splot(wordlist *wl) fprintf(cp_out, "%s%s\t%s (%s)\n", (pl == plot_cur) ? "Current " : "\t", pl->pl_typename, pl->pl_title, pl->pl_name); - + fprintf(cp_out, "? "); if (!fgets(buf, BSIZE_SP, cp_in)) { clearerr(cp_in); @@ -909,4 +912,3 @@ com_splot(wordlist *wl) plot_setcur(s); return; } - diff --git a/src/frontend/postsc.c b/src/frontend/postsc.c index b79e9707f..71d594369 100644 --- a/src/frontend/postsc.c +++ b/src/frontend/postsc.c @@ -4,7 +4,7 @@ Author: 1988 Jeffrey M. Hsu **********/ /* - Postscript driver + Postscript driver */ #include "ngspice/ngspice.h" @@ -19,9 +19,9 @@ Author: 1988 Jeffrey M. Hsu #include "variable.h" #include "plotting/graphdb.h" -#define RAD_TO_DEG (180.0 / M_PI) +#define RAD_TO_DEG (180.0 / M_PI) #define DEVDEP(g) (*((PSdevdep *) (g)->devdep)) -#define MAX_PS_LINES 1000 +#define MAX_PS_LINES 1000 #define SOLID 0 #define DOTTED 1 @@ -41,16 +41,17 @@ Author: 1988 Jeffrey M. Hsu #define FONTHEIGHT 14 /* printer default fontheight */ typedef struct { - int lastlinestyle, lastcolor; /* initial invalid value */ - int lastx, lasty, linecount; + int lastlinestyle, lastcolor; /* initial invalid value */ + int lastx, lasty, linecount; } PSdevdep; + static char *linestyle[] = { "[]", /* solid */ "[1 2]", /* dotted */ "[7 7]", /* longdashed */ "[3 3]", /* shortdashed */ - "[7 2 2 2]", /* longdotdashed */ + "[7 2 2 2]", /* longdotdashed */ "[3 2 1 2]", /* shortdotdashed */ "[8 3 2 3]", "[14 2]", @@ -66,7 +67,7 @@ static int screenflag = 0; static int colorflag = 0; static int setbgcolor = 0; static int settxcolor = -1; -static double scale; /* Used for fine tuning */ +static double scale; /* Used for fine tuning */ static int xtadj; /* text adjustment x */ static int ytadj; /* text adjustment y */ static int hcopygraphid; @@ -76,28 +77,29 @@ void PS_LinestyleColor(int linestyleid, int colorid); void PS_SelectColor(int colorid); void PS_Stroke(void); + /* Set scale, color and size of the plot */ int PS_Init(void) { char pswidth[30], psheight[30]; - + if (!cp_getvar("hcopyscale", CP_STRING, psscale)) { scale = 1.0; } else { sscanf(psscale, "%lf", &scale); if ((scale <= 0) || (scale > 10)) - scale = 1.0; + scale = 1.0; } - dispdev->numlinestyles = NUMELEMS(linestyle); - /* plot color */ + dispdev->numlinestyles = NUMELEMS(linestyle); + /* plot color */ if (!cp_getvar("hcopypscolor", CP_NUM, &setbgcolor)) { /* if not set, set plot to b&w and use line styles */ colorflag = 0; dispdev->numcolors = 2; } else { - /* get backgroung color and set plot to color */ + /* get backgroung color and set plot to color */ colorflag = 1; dispdev->numcolors = 21; /* don't know what the maximum should be */ cp_getvar("hcopypstxcolor", CP_NUM, &settxcolor); @@ -123,7 +125,7 @@ PS_Init(void) dispdev->height = 10000; } - /* The following side effects have to be considered + /* The following side effects have to be considered * when the printer is called by com_hardcopy ! * gr_init: * viewportxoff = 8 * fontwidth @@ -155,27 +157,27 @@ PS_Init(void) dispdev->minx = (int)(XOFF / scale); dispdev->miny = (int)(YOFF / scale); - return(0); - + return (0); } + /* Plot and fill bounding box */ int PS_NewViewport(GRAPH *graph) { - int x1,x2,y1,y2; + int x1, x2, y1, y2; hcopygraphid = graph->graphid; /* devdep initially contains name of output file */ if ((plotfile = fopen((char*)graph->devdep, "w")) == NULL) { perror((char*)graph->devdep); - graph->devdep = NULL; - return(1); + graph->devdep = NULL; + return (1); } if (graph->absolute.width) { - /* hardcopying from the screen */ + /* hardcopying from the screen */ - screenflag = 1; + screenflag = 1; } /* reasonable values, used in gr_ for placement */ @@ -198,23 +200,23 @@ PS_NewViewport(GRAPH *graph) /* start file off with a % */ fprintf(plotfile, "%%!PS-Adobe-3.0 EPSF-3.0\n"); fprintf(plotfile, "%%%%Creator: nutmeg\n"); - fprintf(plotfile, "%%%%BoundingBox: %d %d %d %d\n",x1,y1,x2,y2); + fprintf(plotfile, "%%%%BoundingBox: %d %d %d %d\n", x1, y1, x2, y2); fprintf(plotfile, "%g %g scale\n", 1.0 / scale, 1.0 / scale); - if (colorflag == 1){ + if (colorflag == 1) { /* set the background to color given in spinit (or 0) */ PS_SelectColor(setbgcolor); - fprintf(plotfile,"%s setrgbcolor\n",pscolor); - fprintf(plotfile,"newpath\n"); - fprintf(plotfile,"%d %d moveto %d %d lineto\n",x1,y1,x2,y1); - fprintf(plotfile,"%d %d lineto %d %d lineto\n",x2,y2,x1,y2); - fprintf(plotfile,"closepath fill\n"); + fprintf(plotfile, "%s setrgbcolor\n", pscolor); + fprintf(plotfile, "newpath\n"); + fprintf(plotfile, "%d %d moveto %d %d lineto\n", x1, y1, x2, y1); + fprintf(plotfile, "%d %d lineto %d %d lineto\n", x2, y2, x1, y2); + fprintf(plotfile, "closepath fill\n"); } /* set up a reasonable font */ fprintf(plotfile, "/%s findfont %d scalefont setfont\n\n", - psfont, (int) (fontsize * scale)); + psfont, (int) (fontsize * scale)); graph->devdep = TMALLOC(PSdevdep, 1); DEVDEP(graph).lastlinestyle = -1; @@ -228,12 +230,12 @@ PS_NewViewport(GRAPH *graph) return 0; } + int PS_Close(void) { - /* in case PS_Close is called as part of an abort, - w/o having reached PS_NewViewport */ + w/o having reached PS_NewViewport */ if (plotfile) { PS_Stroke(); fprintf(plotfile, "showpage\n%%%%EOF\n"); @@ -250,6 +252,7 @@ PS_Close(void) return 0; } + int PS_Clear(void) { @@ -257,22 +260,24 @@ PS_Clear(void) return 0; } + int PS_DrawLine(int x1, int y1, int x2, int y2) { - /* note: this is not extendible to more than one graph - => will have to give NewViewport a writeable graph XXX */ + => will have to give NewViewport a writeable graph XXX */ - if (DEVDEP(currentgraph).linecount > MAX_PS_LINES - || DEVDEP(currentgraph).linecount == 0 - || x1 != DEVDEP(currentgraph).lastx - || y1 != DEVDEP(currentgraph).lasty){ + if (DEVDEP(currentgraph).linecount > MAX_PS_LINES || + DEVDEP(currentgraph).linecount == 0 || + x1 != DEVDEP(currentgraph).lastx || + y1 != DEVDEP(currentgraph).lasty) + { PS_Stroke(); fprintf(plotfile, "newpath\n"); fprintf(plotfile, "%d %d moveto\n", x1 + xoff, y1 + yoff); DEVDEP(currentgraph).linecount += 1; } + if (x1 != x2 || y1 != y2) { fprintf(plotfile, "%d %d lineto\n", x2 + xoff, y2 + yoff); DEVDEP(currentgraph).linecount += 1; @@ -283,6 +288,7 @@ PS_DrawLine(int x1, int y1, int x2, int y2) return 0; } + int PS_Arc(int x0, int y0, int r, double theta, double delta_theta) { @@ -297,32 +303,33 @@ PS_Arc(int x0, int y0, int r, double theta, double delta_theta) fprintf(plotfile, "%f %f moveto ", x1+(double)xoff, y1+(double)yoff); fprintf(plotfile, "%d %d %d %f %f arc\n", x0+xoff, y0+yoff, r, - angle1, angle2); + angle1, angle2); fprintf(plotfile, "stroke\n"); DEVDEP(currentgraph).linecount = 0; return 0; } + int PS_Text(char *text, int x, int y) { int savedlstyle, savedcolor; /* set linestyle to solid - or may get funny color text on some plotters */ + or may get funny color text on some plotters */ savedlstyle = currentgraph->linestyle; savedcolor = currentgraph->currentcolor; PS_SetLinestyle(SOLID); /* set text color to black if background is not white */ if (setbgcolor > 0) - PS_SetColor(0); + PS_SetColor(0); else - PS_SetColor(1); + PS_SetColor(1); /* if color is given by set hcopytxpscolor=settxcolor, give it a try */ if (settxcolor >= 0) - PS_SetColor(settxcolor); + PS_SetColor(settxcolor); /* stroke the path if there's an open one */ PS_Stroke(); /* move to (x, y) */ @@ -339,15 +346,15 @@ PS_Text(char *text, int x, int y) return 0; } + /* PS_DefineColor */ /* PS_DefineLinestyle */ int PS_SetLinestyle(int linestyleid) { - /* special case - get it when PS_Text restores a -1 linestyle */ + get it when PS_Text restores a -1 linestyle */ if (linestyleid == -1) { currentgraph->linestyle = -1; return 0; @@ -361,6 +368,7 @@ PS_SetLinestyle(int linestyleid) return 0; } + int PS_SetColor(int colorid) { @@ -368,6 +376,7 @@ PS_SetColor(int colorid) return 0; } + int PS_Update(void) { @@ -375,127 +384,129 @@ PS_Update(void) return 0; } + /**************** PRIVAT FUNCTIONS OF PS FRONTEND *****************************/ void PS_SelectColor(int colorid) /* should be replaced by PS_DefineColor */ { - char colorN[30]="", colorstring[30]=""; - char rgb[30], s_red[30]="0x", s_green[30]="0x", s_blue[30]="0x"; - int red=0, green=0, blue=0, scale=1; - int i; - typedef struct { int red, green, blue;} COLOR; - /* duplicated colors from src/frontend/plotting/x11.c in rgb-style */ - const COLOR colors[]= {{ 0, 0, 0}, /*0: black */ - {255, 255, 255}, /*1: white */ - {255, 0, 0}, /*2: red */ - { 0, 0, 255}, /*3: blue */ - {255, 165, 0}, /*4: orange */ - { 0, 255, 0}, /*5: green */ - {255, 192, 203}, /*6: pink */ - {165, 42, 42}, /*7: brown */ - {240, 230, 140}, /*8: khaki */ - {221, 160, 221}, /*9: plum */ - {218, 112, 214}, /*10: orchid */ - {238, 130, 238}, /*11: violet */ - {176, 48, 96}, /*12: maroon */ - { 64, 224, 208}, /*13: turqoise */ - {160, 82, 45}, /*14: sienna */ - {255, 127, 80}, /*15: coral */ - { 0, 255, 255}, /*16: cyan */ - {255, 0, 255}, /*17: magenta */ - /*{255, 215, 0}, 18: gold */ - { 96, 96, 96}, /*18: gray for smith grid */ - /*{255, 255, 0}, 19: yello */ - {150, 150, 150}, /*19: gray for smith grid */ - {128, 128, 128}}; /*20: gray for normal grid */ + char colorN[30] = "", colorstring[30] = ""; + char rgb[30], s_red[30] = "0x", s_green[30] = "0x", s_blue[30] = "0x"; + int red = 0, green = 0, blue = 0, scale = 1; + int i; + typedef struct { int red, green, blue;} COLOR; + /* duplicated colors from src/frontend/plotting/x11.c in rgb-style */ + const COLOR colors[] = {{ 0, 0, 0}, /*0: black */ + {255, 255, 255}, /*1: white */ + {255, 0, 0}, /*2: red */ + { 0, 0, 255}, /*3: blue */ + {255, 165, 0}, /*4: orange */ + { 0, 255, 0}, /*5: green */ + {255, 192, 203}, /*6: pink */ + {165, 42, 42}, /*7: brown */ + {240, 230, 140}, /*8: khaki */ + {221, 160, 221}, /*9: plum */ + {218, 112, 214}, /*10: orchid */ + {238, 130, 238}, /*11: violet */ + {176, 48, 96}, /*12: maroon */ + { 64, 224, 208}, /*13: turqoise */ + {160, 82, 45}, /*14: sienna */ + {255, 127, 80}, /*15: coral */ + { 0, 255, 255}, /*16: cyan */ + {255, 0, 255}, /*17: magenta */ + /*{255, 215, 0}, 18: gold */ + { 96, 96, 96}, /*18: gray for smith grid */ + /*{255, 255, 0}, 19: yello */ + {150, 150, 150}, /*19: gray for smith grid */ + {128, 128, 128}}; /*20: gray for normal grid */ - /* Extract the rgbcolor, format is: "rgb://" */ - sprintf(colorN, "color%d",colorid); - if (cp_getvar(colorN, CP_STRING, colorstring)){ - for (i=0; colorstring[i]; i++) - if (colorstring[i] == '/' || colorstring[i] == ':') - colorstring[i] = ' '; + /* Extract the rgbcolor, format is: "rgb://" */ + sprintf(colorN, "color%d", colorid); + if (cp_getvar(colorN, CP_STRING, colorstring)) { + for (i = 0; colorstring[i]; i++) + if (colorstring[i] == '/' || colorstring[i] == ':') + colorstring[i] = ' '; - sscanf(colorstring,"%s %s %s %s",rgb, &(s_red[2]), &(s_green[2]), &(s_blue[2])); + sscanf(colorstring, "%s %s %s %s", rgb, &(s_red[2]), &(s_green[2]), &(s_blue[2])); - if ((strlen(s_blue) == strlen(s_red) && strlen(s_green) == strlen(s_red)) - && (strlen(s_blue) > 2) && (strlen(s_blue) < 7)){ - sscanf(s_red,"%x",&red); - sscanf(s_green,"%x",&green); - sscanf(s_blue,"%x",&blue); - scale= (1 << (strlen(s_blue) - 2) * 4) - 1; - sprintf(colorstring,"%1.3f %1.3f %1.3f", - (double) red/scale, (double) green/scale, (double) blue/scale); - strcpy(pscolor, colorstring); + if ((strlen(s_blue) == strlen(s_red) && strlen(s_green) == strlen(s_red)) + && (strlen(s_blue) > 2) && (strlen(s_blue) < 7)) { + sscanf(s_red, "%x", &red); + sscanf(s_green, "%x", &green); + sscanf(s_blue, "%x", &blue); + scale = (1 << (strlen(s_blue) - 2) * 4) - 1; + sprintf(colorstring, "%1.3f %1.3f %1.3f", + (double) red/scale, (double) green/scale, (double) blue/scale); + strcpy(pscolor, colorstring); + } + } + if (colorid < 0 || colorid > 20) { + internalerror("bad colorid inside PS_SelectColor"); + } else if (scale == 1) { /* colorN is not an rgbstring, use default color */ + sprintf(colorstring, "%1.3f %1.3f %1.3f", colors[colorid].red/255.0, + colors[colorid].green/255.0, colors[colorid].blue/255.0) ; + strcpy(pscolor, colorstring); } - } - if (colorid < 0 || colorid > 20) { - internalerror("bad colorid inside PS_SelectColor"); - } else if (scale == 1){ /* colorN is not an rgbstring, use default color */ - sprintf(colorstring,"%1.3f %1.3f %1.3f",colors[colorid].red/255.0, - colors[colorid].green/255.0, colors[colorid].blue/255.0) ; - strcpy(pscolor, colorstring); - } } + void PS_LinestyleColor(int linestyleid, int colorid) { - /* we have some different linestyles and colors: - - color and linestyle we got via function call - - color and linestyle we used last time for drawing - - generated color and linestyle we'll use for drawing this time */ - /* these are the rules: - DOTTED and colored ps -> color20 (used for grid) and SOLID - color18 or 19 and black-white -> linestyle is DOTTED */ - - int gencolor=0,genstyle=0; + /* we have some different linestyles and colors: + - color and linestyle we got via function call + - color and linestyle we used last time for drawing + - generated color and linestyle we'll use for drawing this time */ + /* these are the rules: + DOTTED and colored ps -> color20 (used for grid) and SOLID + color18 or 19 and black-white -> linestyle is DOTTED */ - if (colorflag == 1){ - genstyle = SOLID; - if (linestyleid==DOTTED) - gencolor = 20; - else - gencolor = colorid; - } else { /* colorflag == 0 -> mono*/ - if ((colorid == 18) || (colorid == 19)) - genstyle=DOTTED; - else if (linestyleid == -1) - genstyle=0; - else - genstyle=linestyleid; - } + int gencolor = 0, genstyle = 0; - /* change color if nessecary */ - if (colorflag == 1 && gencolor != DEVDEP(currentgraph).lastcolor){ - /* if background is white, set all white line colors to black */ - if ((setbgcolor == 1) && (gencolor == 1)) - PS_SelectColor(0); - else - PS_SelectColor(gencolor); - PS_Stroke(); - fprintf(plotfile,"%s setrgbcolor\n",pscolor); - DEVDEP(currentgraph).lastcolor = gencolor; - } - currentgraph->currentcolor = colorid; - - /* change linestyle if nessecary */ - if (colorflag == 0 && genstyle != DEVDEP(currentgraph).lastlinestyle){ - PS_Stroke(); - fprintf(plotfile, "%s 0 setdash\n", linestyle[genstyle]); - DEVDEP(currentgraph).lastlinestyle= genstyle; - } - currentgraph->linestyle = linestyleid; + if (colorflag == 1) { + genstyle = SOLID; + if (linestyleid == DOTTED) + gencolor = 20; + else + gencolor = colorid; + } else { /* colorflag == 0 -> mono*/ + if ((colorid == 18) || (colorid == 19)) + genstyle = DOTTED; + else if (linestyleid == -1) + genstyle = 0; + else + genstyle = linestyleid; + } + + /* change color if nessecary */ + if (colorflag == 1 && gencolor != DEVDEP(currentgraph).lastcolor) { + /* if background is white, set all white line colors to black */ + if ((setbgcolor == 1) && (gencolor == 1)) + PS_SelectColor(0); + else + PS_SelectColor(gencolor); + PS_Stroke(); + fprintf(plotfile, "%s setrgbcolor\n", pscolor); + DEVDEP(currentgraph).lastcolor = gencolor; + } + currentgraph->currentcolor = colorid; + + /* change linestyle if nessecary */ + if (colorflag == 0 && genstyle != DEVDEP(currentgraph).lastlinestyle) { + PS_Stroke(); + fprintf(plotfile, "%s 0 setdash\n", linestyle[genstyle]); + DEVDEP(currentgraph).lastlinestyle = genstyle; + } + currentgraph->linestyle = linestyleid; } + void PS_Stroke(void) { - /* strokes an open path */ - if (DEVDEP(currentgraph).linecount > 0) { - fprintf(plotfile, "stroke\n"); - DEVDEP(currentgraph).linecount = 0; - } + /* strokes an open path */ + if (DEVDEP(currentgraph).linecount > 0) { + fprintf(plotfile, "stroke\n"); + DEVDEP(currentgraph).linecount = 0; + } } - diff --git a/src/frontend/quote.c b/src/frontend/quote.c index 25433806f..dc3bf2556 100644 --- a/src/frontend/quote.c +++ b/src/frontend/quote.c @@ -23,28 +23,30 @@ cp_wstrip(char *str) char c, d; if (str) - while ((c = *str) != '\0') { /* assign and test */ - d = (char) strip(c); - if (c != d) - *str = d; - str++; - } + while ((c = *str) != '\0') { /* assign and test */ + d = (char) strip(c); + if (c != d) + *str = d; + str++; + } return; } + /* Quote all characters in a word. */ void cp_quoteword(char *str) { if (str) - while (*str) { - *str = (char) quote(*str); - str++; - } + while (*str) { + *str = (char) quote(*str); + str++; + } return; } + /* Print a word (strip the word first). */ void @@ -58,6 +60,7 @@ cp_printword(char *string, FILE *fp) return; } + /* (Destructively) strip all the words in a wlist. */ void @@ -70,6 +73,7 @@ cp_striplist(wordlist *wlist) return; } + /* Remove the "" from a string. */ char * @@ -77,17 +81,20 @@ cp_unquote(char *string) { char *s; size_t l; - if (string) { - l = strlen(string); - s = TMALLOC(char, l + 1); - - if (l>=2 && *string == '"' && string[l-1] == '"') { - strncpy(s,string+1,l-2); - s[l-2] = '\0'; - } else - strcpy(s,string); - return (s); - } else - return 0; + if (string) { + l = strlen(string); + s = TMALLOC(char, l + 1); + + if (l >= 2 && *string == '"' && string[l-1] == '"') { + strncpy(s, string+1, l-2); + s[l-2] = '\0'; + } else { + strcpy(s, string); + } + + return (s); + } else { + return 0; + } } diff --git a/src/frontend/rawfile.c b/src/frontend/rawfile.c index b199d7f13..697eff718 100644 --- a/src/frontend/rawfile.c +++ b/src/frontend/rawfile.c @@ -17,7 +17,7 @@ Author: 1986 Wayne A. Christopher, U. C. Berkeley CAD Group #include "variable.h" #include "../misc/misc_time.h" -/* static declarations */ + static void fixdims(struct dvec *v, char *s); @@ -27,7 +27,7 @@ int raw_prec = -1; /* How many sigfigs to use, default 15 (max). */ #ifdef HAS_WINDOWS #undef fscanf /* redo I/O from WINMAIN.C here -otherwise reading ASCII will not work */ + otherwise reading ASCII will not work */ #endif @@ -62,25 +62,25 @@ raw_write(char *name, struct plot *pl, bool app, bool binary) prec = DEFPREC; #if defined(__MINGW32__) || defined(_MSC_VER) + /* - Binary file binary write - hvogt 15.03.2000 ---------------------*/ if (binary) { if ((fp = fopen(name, app ? "ab" : "wb")) == NULL) { perror(name); return; } - fprintf(cp_out,"binary raw file\n"); - } else { + fprintf(cp_out, "binary raw file\n"); + } else { if ((fp = fopen(name, app ? "a" : "w")) == NULL) { perror(name); return; } - fprintf(cp_out,"ASCII raw file\n"); + fprintf(cp_out, "ASCII raw file\n"); } /* --------------------------------------------------------------------*/ #else - if (!(fp = fopen(name, app ? "a" : "w"))) { perror(name); return; @@ -115,7 +115,7 @@ raw_write(char *name, struct plot *pl, bool app, bool binary) fprintf(fp, "Date: %s\n", pl->pl_date); fprintf(fp, "Plotname: %s\n", pl->pl_name); fprintf(fp, "Flags: %s%s\n", - realflag ? "real" : "complex", raw_padding ? "" : " unpadded" ); + realflag ? "real" : "complex", raw_padding ? "" : " unpadded"); fprintf(fp, "No. Variables: %d\n", nvars); fprintf(fp, "No. Points: %d\n", length); if (numdims > 1) { @@ -154,14 +154,14 @@ raw_write(char *name, struct plot *pl, bool app, bool binary) fprintf(fp, "Variables:\n"); for (i = 0, v = pl->pl_dvecs; v; v = v->v_next) { - if ( strcmp( ft_typenames(v->v_type), "current" ) == 0 ) { + if (strcmp(ft_typenames(v->v_type), "current") == 0) { branch = NULL; - if ((branch = strstr( v->v_name, "#branch" )) != NULL) { + if ((branch = strstr(v->v_name, "#branch")) != NULL) { *branch = '\0'; } fprintf(fp, "\t%d\ti(%s)\t%s", i++, v->v_name, ft_typenames(v->v_type)); - if ( branch != NULL ) *branch = '#'; - } else if ( strcmp( ft_typenames(v->v_type), "voltage" ) == 0 ) { + if (branch != NULL) *branch = '#'; + } else if (strcmp(ft_typenames(v->v_type), "voltage") == 0) { fprintf(fp, "\t%d\t%s\t%s", i++, v->v_name, ft_typenames(v->v_type)); } else { fprintf(fp, "\t%d\t%s\t%s", i++, v->v_name, ft_typenames(v->v_type)); @@ -187,7 +187,7 @@ raw_write(char *name, struct plot *pl, bool app, bool binary) } if (writedims) { dimstring(v->v_dims, v->v_numdims, buf); - fprintf(fp, " dims=%s",buf); + fprintf(fp, " dims=%s", buf); } (void) putc('\n', fp); } @@ -201,33 +201,25 @@ raw_write(char *name, struct plot *pl, bool app, bool binary) if (realflag) { dd = (isreal(v) ? v->v_realdata[i] : realpart(v->v_compdata[i])); - (void) fwrite(&dd, sizeof - (double), 1, fp); + (void) fwrite(&dd, sizeof(double), 1, fp); } else if (isreal(v)) { dd = v->v_realdata[i]; - (void) fwrite(&dd, sizeof - (double), 1, fp); + (void) fwrite(&dd, sizeof(double), 1, fp); dd = 0.0; - (void) fwrite(&dd, sizeof - (double), 1, fp); + (void) fwrite(&dd, sizeof(double), 1, fp); } else { dd = realpart(v->v_compdata[i]); - (void) fwrite(&dd, sizeof - (double), 1, fp); + (void) fwrite(&dd, sizeof(double), 1, fp); dd = imagpart(v->v_compdata[i]); - (void) fwrite(&dd, sizeof - (double), 1, fp); + (void) fwrite(&dd, sizeof(double), 1, fp); } } else if (raw_padding) { dd = 0.0; if (realflag) { - (void) fwrite(&dd, sizeof - (double), 1, fp); + (void) fwrite(&dd, sizeof(double), 1, fp); } else { - (void) fwrite(&dd, sizeof - (double), 1, fp); - (void) fwrite(&dd, sizeof - (double), 1, fp); + (void) fwrite(&dd, sizeof(double), 1, fp); + (void) fwrite(&dd, sizeof(double), 1, fp); } } } @@ -251,12 +243,10 @@ raw_write(char *name, struct plot *pl, bool app, bool binary) prec, imagpart(v->v_compdata[i])); } else if (raw_padding) { - if (realflag) { + if (realflag) fprintf(fp, "\t%.*e\n", prec, 0.0); - } else { - fprintf(fp, "\t%.*e,%.*e\n", - prec, 0.0, prec, 0.0); - } + else + fprintf(fp, "\t%.*e,%.*e\n", prec, 0.0, prec, 0.0); } } (void) putc('\n', fp); @@ -266,6 +256,7 @@ raw_write(char *name, struct plot *pl, bool app, bool binary) return; } + /* Read a raw file. Returns a list of plot structures. This routine should be * very flexible about what it expects to see in the rawfile. Really all we * require is that there be one variables and one values section per plot @@ -306,8 +297,8 @@ raw_read(char *name) { struct plot *plots = NULL, *curpl = NULL; char buf[BSIZE_SP], buf2[BSIZE_SP], *s, *t, *r; int flags = 0, nvars = 0, npoints = 0, i, j; - int ndimpoints, numdims=0, dims[MAXDIMS]; - bool raw_padded = TRUE, is_ascii=FALSE; + int ndimpoints, numdims = 0, dims[MAXDIMS]; + bool raw_padded = TRUE, is_ascii = FALSE; double junk; struct dvec *v, *nv; struct variable *vv; @@ -332,7 +323,7 @@ raw_read(char *name) { while (fgets(buf, BSIZE_SP, fp)) { r = strchr(buf, '\n'); - if(r && r > buf && r[-1] == '\r') { + if (r && r > buf && r[-1] == '\r') { r[-1] = '\n'; r[0] = '\0'; } @@ -352,9 +343,10 @@ raw_read(char *name) { SKIP(s); NONL(s); if (curpl) { /* reverse commands list */ - for (wl=curpl->pl_commands, - curpl->pl_commands=NULL; wl && - wl->wl_next; wl=nwl) { + for (wl = curpl->pl_commands, curpl->pl_commands = NULL; + wl && wl->wl_next; + wl = nwl) + { nwl = wl->wl_next; wl->wl_next = curpl->pl_commands; curpl->pl_commands = wl; @@ -365,7 +357,7 @@ raw_read(char *name) { plots = curpl; curpl->pl_name = copy(s); if (!date) - date = copy(datestring( )); + date = copy(datestring()); curpl->pl_date = date; curpl->pl_title = copy(title); flags = VF_PERMANENT; @@ -383,9 +375,7 @@ raw_read(char *name) { else if (cieq(t, "padded")) raw_padded = TRUE; else - fprintf(cp_err, - "Warning: unknown flag %s\n", - t); + fprintf(cp_err, "Warning: unknown flag %s\n", t); } } else if (ciprefix("no. variables:", buf)) { s = buf; @@ -418,9 +408,8 @@ raw_read(char *name) { /* Let's just make sure that the no. of points * and the dimensions are consistent. */ - for (j = 0, ndimpoints = 1; j < numdims; j++) { + for (j = 0, ndimpoints = 1; j < numdims; j++) ndimpoints *= dims[j]; - } if (ndimpoints != npoints) { fprintf(cp_err, @@ -435,9 +424,9 @@ raw_read(char *name) { if (curpl) { curpl->pl_commands = wl_cons(copy(s), curpl->pl_commands); wl = curpl->pl_commands; - } else - fprintf(cp_err, - "Error: misplaced Command: line\n"); + } else { + fprintf(cp_err, "Error: misplaced Command: line\n"); + } /* Now execute the command if we can. */ (void) cp_evloop(s); } else if (ciprefix("option:", buf)) { @@ -447,15 +436,15 @@ raw_read(char *name) { if (curpl) { wl = cp_lexer(s); for (vv = curpl->pl_env; vv && vv->va_next; - vv = vv->va_next) + vv = vv->va_next) ; if (vv) vv->va_next = cp_setparse(wl); else curpl->pl_env = cp_setparse(wl); - } else - fprintf(cp_err, - "Error: misplaced Option: line\n"); + } else { + fprintf(cp_err, "Error: misplaced Option: line\n"); + } } else if (ciprefix("variables:", buf)) { /* We reverse the dvec list eventually... */ if (!curpl) { @@ -487,19 +476,17 @@ raw_read(char *name) { v->v_numdims = 0; /* Length and dims might be changed by options. */ - if (!i) + if (!i) { curpl->pl_scale = v; - else { + } else { (void) fgets(buf, BSIZE_SP, fp); s = buf; } (void) gettok(&s); /* The strchr field. */ - if ((t = gettok(&s)) != NULL) + if ((t = gettok(&s)) != NULL) { v->v_name = t; - else { - fprintf(cp_err, - "Error: bad var line %s\n", - buf); + } else { + fprintf(cp_err, "Error: bad var line %s\n", buf); /* MW. v_name must be valid in the case that no. points = 0 */ v->v_name = "no vars\n"; } @@ -507,51 +494,37 @@ raw_read(char *name) { if (t) v->v_type = ft_typnum(t); else - fprintf(cp_err, - "Error: bad var line %s\n", - buf); + fprintf(cp_err, "Error: bad var line %s\n", buf); /* Fix the name... */ - if (isdigit(*v->v_name) && (r = ft_typabbrev(v - ->v_type)) != NULL) { - (void) sprintf(buf2, "%s(%s)", r, - v->v_name); + if (isdigit(*v->v_name) && (r = ft_typabbrev(v ->v_type)) != NULL) { + (void) sprintf(buf2, "%s(%s)", r, v->v_name); v->v_name = copy(buf2); } + /* Now come the strange options... */ while ((t = gettok(&s)) != NULL) { if (ciprefix("min=", t)) { - if (sscanf(t + 4, "%lf", - &v->v_minsignal) != 1) - fprintf(cp_err, - "Error: bad arg %s\n", - t); + if (sscanf(t + 4, "%lf", &v->v_minsignal) != 1) + fprintf(cp_err, "Error: bad arg %s\n", t); v->v_flags |= VF_MINGIVEN; } else if (ciprefix("max=", t)) { - if (sscanf(t + 4, "%lf", - &v->v_maxsignal) != 1) - fprintf(cp_err, - "Error: bad arg %s\n", - t); + if (sscanf(t + 4, "%lf", &v->v_maxsignal) != 1) + fprintf(cp_err, "Error: bad arg %s\n", t); v->v_flags |= VF_MAXGIVEN; } else if (ciprefix("color=", t)) { v->v_defcolor = copy(t + 6); } else if (ciprefix("scale=", t)) { // This cast is bad, but... - v->v_scale = (struct dvec *) - copy(t + 6); + v->v_scale = (struct dvec *) copy(t + 6); } else if (ciprefix("grid=", t)) { - v->v_gridtype = (GRIDTYPE) - scannum(t + 5); + v->v_gridtype = (GRIDTYPE) scannum(t + 5); } else if (ciprefix("plot=", t)) { - v->v_plottype = (PLOTTYPE) - scannum(t + 5); + v->v_plottype = (PLOTTYPE) scannum(t + 5); } else if (ciprefix("dims=", t)) { fixdims(v, t + 5); } else { - fprintf(cp_err, - "Warning: bad var param %s\n", - t); + fprintf(cp_err, "Warning: bad var param %s\n", t); } } /* Now we default any missing dimensions. */ @@ -569,8 +542,9 @@ raw_read(char *name) { else v->v_compdata = TMALLOC(ngcomplex_t, npoints); } - } else if (ciprefix("values:", buf) || - ciprefix("binary:", buf)) { + + } else if (ciprefix("values:", buf) || ciprefix("binary:", buf)) { + if (!curpl) { fprintf(cp_err, "Error: no plot name given\n"); plots = NULL; @@ -578,8 +552,7 @@ raw_read(char *name) { } /* We'd better reverse the dvec list now... */ - for (v = curpl->pl_dvecs, curpl->pl_dvecs = NULL; v; - v = nv) { + for (v = curpl->pl_dvecs, curpl->pl_dvecs = NULL; v; v = nv) { nv = v->v_next; v->v_next = curpl->pl_dvecs; curpl->pl_dvecs = v; @@ -588,25 +561,26 @@ raw_read(char *name) { /* And fix the scale pointers. */ for (v = curpl->pl_dvecs; v; v = v->v_next) { if (v->v_scale) { - for (nv = curpl->pl_dvecs; nv; nv = - nv->v_next) - if (cieq((char *) v->v_scale, // This cast is bad, but... - nv->v_name)) { + for (nv = curpl->pl_dvecs; nv; nv = nv->v_next) + // This cast is bad, but... + if (cieq((char *) v->v_scale, nv->v_name)) { v->v_scale = nv; break; } if (!nv) { + // This cast is bad, but... fprintf(cp_err, - "Error: no such vector %s\n", - (char *) v->v_scale); // This cast is bad, but... + "Error: no such vector %s\n", (char *) v->v_scale); v->v_scale = NULL; } } } + if ((*buf == 'v') || (*buf == 'V')) - is_ascii=TRUE; + is_ascii = TRUE; else - is_ascii=FALSE; + is_ascii = FALSE; + for (i = 0; i < npoints; i++) { if (is_ascii) { /* It's an ASCII file. */ @@ -614,8 +588,7 @@ raw_read(char *name) { for (v = curpl->pl_dvecs; v; v = v->v_next) { if (i < v->v_length) { if (flags & VF_REAL) { - if (fscanf(fp, " %lf", - &v->v_realdata[i]) != 1) + if (fscanf(fp, " %lf", &v->v_realdata[i]) != 1) GETOUT(); } else { if (fscanf(fp, " %lf, %lf", @@ -625,12 +598,10 @@ raw_read(char *name) { } } else if (raw_padded) { if (flags & VF_REAL) { - if (fscanf(fp, " %lf", - &junk) != 1) + if (fscanf(fp, " %lf", &junk) != 1) GETOUT(); } else { - if (fscanf(fp, " %lf, %lf", - &junk, &junk) != 2) + if (fscanf(fp, " %lf, %lf", &junk, &junk) != 2) GETOUT(); } } @@ -641,27 +612,27 @@ raw_read(char *name) { if (i < v->v_length) { if (flags & VF_REAL) { if (fread(&v->v_realdata[i], - sizeof (double), 1, fp) != 1) + sizeof(double), 1, fp) != 1) GETOUT(); } else { if (fread(&v->v_compdata[i].cx_real, - sizeof (double), 1, fp) != 1) + sizeof(double), 1, fp) != 1) GETOUT(); if (fread(&v->v_compdata[i].cx_imag, - sizeof (double), 1, fp) != 1) + sizeof(double), 1, fp) != 1) GETOUT(); } } else if (raw_padded) { if (flags & VF_REAL) { if (fread(&junk, - sizeof (double), 1, fp) != 1) + sizeof(double), 1, fp) != 1) GETOUT(); } else { if (fread(&junk, - sizeof (double), 1, fp) != 1) + sizeof(double), 1, fp) != 1) GETOUT(); if (fread(&junk, - sizeof (double), 1, fp) != 1) + sizeof(double), 1, fp) != 1) GETOUT(); } } @@ -675,16 +646,17 @@ raw_read(char *name) { } if (*s) { fprintf(cp_err, - "Error: strange line in rawfile:\n %s\n load aborted.\n", buf); + "Error: strange line in rawfile:\n %s\n load aborted.\n", buf); return (NULL); } } } if (curpl) { /* reverse commands list */ - for (wl=curpl->pl_commands, - curpl->pl_commands=NULL; wl && - wl->wl_next; wl=nwl) { + for (wl = curpl->pl_commands, curpl->pl_commands = NULL; + wl && wl->wl_next; + wl = nwl) + { nwl = wl->wl_next; wl->wl_next = curpl->pl_commands; curpl->pl_commands = wl; @@ -700,6 +672,7 @@ raw_read(char *name) { return (plots); } + /* s is a string of the form d1,d2,d3... */ static void @@ -720,18 +693,18 @@ fixdims(struct dvec *v, char *s) * have serious problems with this vector. Try to fix * by setting to default dimensions when we return. */ - for (i = 0, ndimpoints = 1; i < v->v_numdims; i++) { + for (i = 0, ndimpoints = 1; i < v->v_numdims; i++) ndimpoints *= v->v_dims[i]; - } - if (ndimpoints > v->v_length) { + if (ndimpoints > v->v_length) v->v_numdims = 0; - } else { + else v->v_length = ndimpoints; - } + return; } + /* Write a s-param file according to format Touchstone Vers. 1. */ void @@ -757,17 +730,17 @@ spar_write(char *name, struct plot *pl, double Rbaseval) for (v = pl->pl_dvecs; v; v = v->v_next) { /* All vectors have to have same length, - only dimension 1 is allowed */ - if (length == 0) { + only dimension 1 is allowed */ + if (length == 0) length = v->v_length; - } + if (length != v->v_length) { - fprintf(stderr,"Error writing s2p: lentgth of vector %s differs from length of vector 'frequency'\n", + fprintf(stderr, "Error writing s2p: lentgth of vector %s differs from length of vector 'frequency'\n", v->v_name); return; } if (v->v_numdims != 1) { - fprintf(stderr,"Error writing s2p: Dimension of vector %s greater than 1\n",v->v_name); + fprintf(stderr, "Error writing s2p: Dimension of vector %s greater than 1\n", v->v_name); return; } @@ -776,17 +749,17 @@ spar_write(char *name, struct plot *pl, double Rbaseval) * Be paranoid and assume somewhere we may have * forgotten to set the dimensions of 1-D vectors. - if (v->v_numdims <= 1) { - v->v_numdims = 1; - v->v_dims[0] = v->v_length; - } - if (v->v_length > length) { - length = v->v_length; - numdims = v->v_numdims; - for (j = 0; j < numdims; j++) { - dims[j] = v->v_dims[j]; - } - }*/ + if (v->v_numdims <= 1) { + v->v_numdims = 1; + v->v_dims[0] = v->v_length; + } + if (v->v_length > length) { + length = v->v_length; + numdims = v->v_numdims; + for (j = 0; j < numdims; j++) { + dims[j] = v->v_dims[j]; + } + }*/ } if ((fp = fopen(name, "w")) == NULL) { @@ -799,9 +772,9 @@ spar_write(char *name, struct plot *pl, double Rbaseval) fprintf(fp, "!Generated by ngspice at %s\n", pl->pl_date); fprintf(fp, "# Hz S RI R %g\n", Rbaseval); fprintf(fp, "!%-*.5s %-*.5s %-*.5s %-*.5s %-*.5s %-*.5s %-*.5s %-*.5s %-*.5s\n", - prec+8,"freq", - prec+8,"ReS11",prec+8,"ImS11",prec+8,"ReS21",prec+8,"ImS21", - prec+8,"ReS12",prec+8,"ImS12",prec+8,"ReS22",prec+8,"ImS22"); + prec+8, "freq", + prec+8, "ReS11", prec+8, "ImS11", prec+8, "ReS21", prec+8, "ImS21", + prec+8, "ReS12", prec+8, "ImS12", prec+8, "ReS22", prec+8, "ImS22"); /* Before we write the stuff out, make sure that the scale is the first * in the list. @@ -815,7 +788,7 @@ spar_write(char *name, struct plot *pl, double Rbaseval) } /* print frequency first as real value, the real and imag part of - S11, S21, S12, S22 respectively */ + S11, S21, S12, S22 respectively */ for (i = 0; i < length; i++) { for (v = pl->pl_dvecs; v; v = v->v_next) { if (i < v->v_length) { diff --git a/src/frontend/resource.c b/src/frontend/resource.c index 4263f82d2..5b01548a7 100644 --- a/src/frontend/resource.c +++ b/src/frontend/resource.c @@ -41,7 +41,7 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group #ifdef HAVE_WIN32 #define WIN32_LEAN_AND_MEAN - + #ifdef __MINGW32__ /* access to GlobalMemoryStatusEx in winbase.h:1558 */ #define WINVER 0x0500 #endif @@ -51,11 +51,11 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group * However, BOOLEAN is not used by this file so we can work round this problem * by undefining BOOLEAN before including windows.h * SJB - April 2005 - */ + */ #undef BOOLEAN #include -/* At least Windows 2000 is needed - * Undefine _WIN32_WINNT 0x0500 if you want to compile under Windows ME +/* At least Windows 2000 is needed + * Undefine _WIN32_WINNT 0x0500 if you want to compile under Windows ME * and older (not tested under Windows ME or 98!) */ #if defined(__MINGW32__) || (_MSC_VER > 1200) /* Exclude VC++ 6.0 from using the psapi */ @@ -64,41 +64,43 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group #endif /* HAVE_WIN32 */ -/* Uncheck the following definition if you want to get the old usage information -#undef HAVE__PROC_MEMINFO +/* Uncheck the following definition if you want to get the old usage information + #undef HAVE__PROC_MEMINFO */ -/* static declarations */ -static void printres(char *name); -static void fprintmem(FILE* stream, unsigned long long memory); -#if defined(HAVE_WIN32) || defined(HAVE__PROC_MEMINFO) +static void printres(char *name); +static void fprintmem(FILE *stream, unsigned long long memory); + +#if defined(HAVE_WIN32) || defined(HAVE__PROC_MEMINFO) static int get_procm(struct proc_mem *memall); static int get_sysmem(struct sys_mem *memall); -struct sys_mem mem_t, mem_t_act; +struct sys_mem mem_t, mem_t_act; struct proc_mem mem_ng, mem_ng_act; #else static RETSIGTYPE fault(void); -static void * baseaddr(void); +static void *baseaddr(void); #endif char *startdata; char *enddata; + void init_rlimits(void) { -# if defined(HAVE_WIN32) || defined(HAVE__PROC_MEMINFO) +# if defined(HAVE_WIN32) || defined(HAVE__PROC_MEMINFO) get_procm(&mem_ng); get_sysmem(&mem_t); # else - startdata = (char *) baseaddr( ); + startdata = (char *) baseaddr(); enddata = sbrk(0); # endif } + void init_time(void) { @@ -107,7 +109,7 @@ init_time(void) # ifdef HAVE_TIMES # else # ifdef HAVE_FTIME - ftime(&timebegin); + ftime(&timebegin); # endif # endif #endif @@ -117,17 +119,17 @@ init_time(void) void com_rusage(wordlist *wl) { -char* copyword; + char *copyword; /* Fill in the SPICE accounting structure... */ if (wl && (eq(wl->wl_word, "everything") || eq(wl->wl_word, "all"))) { printres(NULL); } else if (wl) { for (; wl; wl = wl->wl_next) { - /* printres(cp_unquote(wl->wl_word)); DG: bad, memory leak*/ - copyword=cp_unquote(wl->wl_word);/*DG*/ - printres(copyword); - tfree(copyword); + /* printres(cp_unquote(wl->wl_word)); DG: bad, memory leak*/ + copyword = cp_unquote(wl->wl_word);/*DG*/ + printres(copyword); + tfree(copyword); if (wl->wl_next) (void) putc('\n', cp_out); } @@ -141,6 +143,7 @@ char* copyword; return; } + /* Find out if the user is approaching his maximum data size. If usage is withing 90% of total available then a warning message is sent to the error stream (cp_err) */ @@ -149,11 +152,11 @@ ft_ckspace(void) { unsigned long long usage, limit; -#if defined(HAVE_WIN32) || defined(HAVE__PROC_MEMINFO) +#if defined(HAVE_WIN32) || defined(HAVE__PROC_MEMINFO) get_procm(&mem_ng_act); usage = mem_ng_act.size; - limit = mem_t.free; -#else + limit = mem_t.free; +#else static size_t old_usage = 0; char *hi; @@ -167,28 +170,29 @@ ft_ckspace(void) /* SYSVRLIMIT */ limit = ulimit(3, 0L) - (enddata - startdata); #endif /* HAVE_GETRLIMIT */ - - hi=sbrk(0); + + hi = sbrk(0); usage = (size_t) (hi - enddata); if (usage <= old_usage) - return; + return; old_usage = usage; #endif /* not HAS_WINDOWS */ if ((double)usage > (double)limit * 0.9) { fprintf(cp_err, "Warning - approaching max data size: "); - fprintf(cp_err, "current size = "); - fprintmem(cp_err, usage); - fprintf(cp_err,", limit = "); - fprintmem(cp_err, limit); - fprintf(cp_err,"\n"); + fprintf(cp_err, "current size = "); + fprintmem(cp_err, usage); + fprintf(cp_err, ", limit = "); + fprintmem(cp_err, limit); + fprintf(cp_err, "\n"); } return; } + /* Print out one piece of resource usage information. */ static void @@ -196,14 +200,14 @@ printres(char *name) { #ifdef CIDER char *paramname = NULL; -#endif +#endif bool yy = FALSE; static long lastsec = 0, lastusec = 0; struct variable *v, *vfree = NULL; - char *cpu_elapsed; + char *cpu_elapsed; if (!name || eq(name, "totalcputime") || eq(name, "cputime")) { - int total, totalu; + int total, totalu; #ifdef ipsc # define NO_RUDATA @@ -214,27 +218,27 @@ printres(char *name) struct rusage ruse; memset(&ruse, 0, sizeof(ruse)); ret = getrusage(RUSAGE_SELF, &ruse); - if(ret == -1) { - perror("getrusage(): "); - } - total = ruse.ru_utime.tv_sec + ruse.ru_stime.tv_sec; - totalu = (ruse.ru_utime.tv_usec + ruse.ru_stime.tv_usec) / 1000; - cpu_elapsed = "CPU"; + if (ret == -1) + perror("getrusage(): "); + + total = ruse.ru_utime.tv_sec + ruse.ru_stime.tv_sec; + totalu = (ruse.ru_utime.tv_usec + ruse.ru_stime.tv_usec) / 1000; + cpu_elapsed = "CPU"; # else # ifdef HAVE_TIMES - struct tms ruse; - realt = times(&ruse); - total = (ruse.tms_utime + ruse.tms_stime)/ HZ; - totalu = (ruse.tms_utime + ruse.tms_utime) * 1000 / HZ; - cpu_elapsed = "CPU"; + struct tms ruse; + realt = times(&ruse); + total = (ruse.tms_utime + ruse.tms_stime)/ HZ; + totalu = (ruse.tms_utime + ruse.tms_utime) * 1000 / HZ; + cpu_elapsed = "CPU"; # else # ifdef HAVE_FTIME - struct timeb timenow; -/* int sec, msec; sjb */ - ftime(&timenow); - timediff(&timenow, &timebegin, &total, &totalu); -/* totalu /= 1000; hvogt */ - cpu_elapsed = "elapsed"; + struct timeb timenow; + /* int sec, msec; sjb */ + ftime(&timenow); + timediff(&timenow, &timebegin, &total, &totalu); + /* totalu /= 1000; hvogt */ + cpu_elapsed = "elapsed"; # else # define NO_RUDATA # endif @@ -244,47 +248,47 @@ printres(char *name) #ifndef NO_RUDATA - if (!name || eq(name, "totalcputime")) { - total += totalu / 1000; - totalu %= 1000; - fprintf(cp_out, "Total %s time: %u.%03u seconds.\n", - cpu_elapsed, total, totalu); - } + if (!name || eq(name, "totalcputime")) { + total += totalu / 1000; + totalu %= 1000; + fprintf(cp_out, "Total %s time: %u.%03u seconds.\n", + cpu_elapsed, total, totalu); + } - if (!name || eq(name, "cputime")) { - lastusec = totalu - lastusec; - lastsec = total - lastsec; - while (lastusec < 0) { - lastusec += 1000; - lastsec -= 1; - } - while (lastusec > 1000) { - lastusec -= 1000; - lastsec += 1; - } + if (!name || eq(name, "cputime")) { + lastusec = totalu - lastusec; + lastsec = total - lastsec; + while (lastusec < 0) { + lastusec += 1000; + lastsec -= 1; + } + while (lastusec > 1000) { + lastusec -= 1000; + lastsec += 1; + } #ifndef HAVE_WIN32 - fprintf(cp_out, "%s time since last call: %lu.%03lu seconds.\n", - cpu_elapsed, lastsec, lastusec); + fprintf(cp_out, "%s time since last call: %lu.%03lu seconds.\n", + cpu_elapsed, lastsec, lastusec); #endif - lastsec = total; - lastusec = totalu; - } + lastsec = total; + lastusec = totalu; + } #ifdef XSPICE - /* gtri - add - 12/12/90 - wbk - record cpu time used for ipc */ + /* gtri - add - 12/12/90 - wbk - record cpu time used for ipc */ g_ipc.cpu_time = (double) lastusec; g_ipc.cpu_time /= 1.0e6; g_ipc.cpu_time += (double) lastsec; /* gtri - end - 12/12/90 */ #endif - yy = TRUE; + yy = TRUE; #else - if (!name || eq(name, "totalcputime")) - fprintf(cp_out, "Total CPU time: ??.??? seconds.\n"); - if (!name || eq(name, "cputime")) - fprintf(cp_out, "CPU time since last call: ??.??? seconds.\n"); - yy = TRUE; + if (!name || eq(name, "totalcputime")) + fprintf(cp_out, "Total CPU time: ??.??? seconds.\n"); + if (!name || eq(name, "cputime")) + fprintf(cp_out, "CPU time since last call: ??.??? seconds.\n"); + yy = TRUE; #endif } @@ -292,84 +296,84 @@ printres(char *name) if (!name || eq(name, "space")) { #ifdef ipsc - size_t usage = 0, limit = 0; - NXINFO cur = nxinfo, start = nxinfo_snap; + size_t usage = 0, limit = 0; + NXINFO cur = nxinfo, start = nxinfo_snap; - usage = cur.dataend - cur.datastart; - limit = start.availmem; + usage = cur.dataend - cur.datastart; + limit = start.availmem; #else /* ipsc */ # ifdef HAVE_GETRLIMIT - size_t usage = 0, limit = 0; + size_t usage = 0, limit = 0; struct rlimit rld; char *hi; getrlimit(RLIMIT_DATA, &rld); - limit = rld.rlim_cur - (size_t)(enddata - startdata); + limit = rld.rlim_cur - (size_t)(enddata - startdata); hi = (char*) sbrk(0); - usage = (size_t) (hi - enddata); + usage = (size_t) (hi - enddata); # else /* HAVE_GETRLIMIT */ # ifdef HAVE_ULIMIT - size_t usage = 0, limit = 0; + size_t usage = 0, limit = 0; char *hi; - limit = ulimit(3, 0L) - (size_t)(enddata - startdata); + limit = ulimit(3, 0L) - (size_t)(enddata - startdata); hi = sbrk(0); - usage = (size_t) (hi - enddata); + usage = (size_t) (hi - enddata); # endif /* HAVE_ULIMIT */ # endif /* HAVE_GETRLIMIT */ #endif /* ipsc */ -#if defined(HAVE_WIN32) || defined(HAVE__PROC_MEMINFO) - - get_procm(&mem_ng_act); - get_sysmem(&mem_t_act); - +#if defined(HAVE_WIN32) || defined(HAVE__PROC_MEMINFO) + + get_procm(&mem_ng_act); + get_sysmem(&mem_t_act); + /* get_sysmem returns bytes */ - fprintf(cp_out, "Total DRAM available = "); - fprintmem(cp_out, mem_t_act.size); - fprintf(cp_out, ".\n"); - - fprintf(cp_out, "DRAM currently available = "); - fprintmem(cp_out, mem_t_act.free); - fprintf(cp_out, ".\n"); - + fprintf(cp_out, "Total DRAM available = "); + fprintmem(cp_out, mem_t_act.size); + fprintf(cp_out, ".\n"); + + fprintf(cp_out, "DRAM currently available = "); + fprintmem(cp_out, mem_t_act.free); + fprintf(cp_out, ".\n"); + /* get_procm returns Kilobytes */ - fprintf(cp_out, "Total ngspice program size = "); - fprintmem(cp_out, mem_ng_act.size*1024); - fprintf(cp_out, ".\n"); -#if defined(HAVE__PROC_MEMINFO) - fprintf(cp_out, "Resident set size = "); - fprintmem(cp_out, mem_ng_act.resident*1024); - fprintf(cp_out, ".\n"); - - fprintf(cp_out, "Shared ngspice pages = "); - fprintmem(cp_out, mem_ng_act.shared*1024); - fprintf(cp_out, ".\n"); - - fprintf(cp_out, "Text (code) pages = "); - fprintmem(cp_out, mem_ng_act.trs*1024); - fprintf(cp_out, ".\n"); - - fprintf(cp_out, "Stack = "); - fprintmem(cp_out, mem_ng_act.drs*1024); - fprintf(cp_out, ".\n"); - - fprintf(cp_out, "Library pages = "); - fprintmem(cp_out, mem_ng_act.lrs*1024); - fprintf(cp_out, ".\n"); -/* not used - fprintf(cp_out, "Dirty pages = "); - fprintmem(cp_out, all_memory.dt * 1024); - fprintf(cp_out, ".\n"); */ -#endif /* HAVE__PROC_MEMINFO */ + fprintf(cp_out, "Total ngspice program size = "); + fprintmem(cp_out, mem_ng_act.size*1024); + fprintf(cp_out, ".\n"); +#if defined(HAVE__PROC_MEMINFO) + fprintf(cp_out, "Resident set size = "); + fprintmem(cp_out, mem_ng_act.resident*1024); + fprintf(cp_out, ".\n"); + + fprintf(cp_out, "Shared ngspice pages = "); + fprintmem(cp_out, mem_ng_act.shared*1024); + fprintf(cp_out, ".\n"); + + fprintf(cp_out, "Text (code) pages = "); + fprintmem(cp_out, mem_ng_act.trs*1024); + fprintf(cp_out, ".\n"); + + fprintf(cp_out, "Stack = "); + fprintmem(cp_out, mem_ng_act.drs*1024); + fprintf(cp_out, ".\n"); + + fprintf(cp_out, "Library pages = "); + fprintmem(cp_out, mem_ng_act.lrs*1024); + fprintf(cp_out, ".\n"); + /* not used + fprintf(cp_out, "Dirty pages = "); + fprintmem(cp_out, all_memory.dt * 1024); + fprintf(cp_out, ".\n"); */ +#endif /* HAVE__PROC_MEMINFO */ #else /* HAS_WINDOWS or HAVE__PROC_MEMINFO */ - fprintf(cp_out, "Current dynamic memory usage = "); - fprintmem(cp_out, usage); - fprintf(cp_out, ",\n"); - - fprintf(cp_out, "Dynamic memory limit = "); - fprintmem(cp_out, limit); - fprintf(cp_out, ".\n"); + fprintf(cp_out, "Current dynamic memory usage = "); + fprintmem(cp_out, usage); + fprintf(cp_out, ",\n"); + + fprintf(cp_out, "Dynamic memory limit = "); + fprintmem(cp_out, limit); + fprintf(cp_out, ".\n"); #endif yy = TRUE; } @@ -380,24 +384,22 @@ printres(char *name) struct rusage ruse; memset(&ruse, 0, sizeof(ruse)); ret = getrusage(RUSAGE_SELF, &ruse); - if(ret == -1) { - perror("getrusage(): "); - } - fprintf(cp_out, - "%lu page faults, %lu vol + %lu invol = %lu context switches.\n", - ruse.ru_majflt, ruse.ru_nvcsw, ruse.ru_nivcsw, + if (ret == -1) + perror("getrusage(): "); + fprintf(cp_out, + "%lu page faults, %lu vol + %lu invol = %lu context switches.\n", + ruse.ru_majflt, ruse.ru_nvcsw, ruse.ru_nivcsw, ruse.ru_nvcsw + ruse.ru_nivcsw); yy = TRUE; #endif - } + } /* PN Now get all the frontend resource stuff */ if (ft_curckt) { - if (name && eq(name, "task")) { + if (name && eq(name, "task")) vfree = v = ft_getstat(ft_curckt, NULL); - } else { + else vfree = v = ft_getstat(ft_curckt, name); - } if (name && v) { fprintf(cp_out, "%s= ", v->va_name); @@ -418,29 +420,30 @@ printres(char *name) } } - if(vfree) + if (vfree) free_struct_variable(vfree); /* Now get all the spice resource stuff. */ if (ft_curckt && ft_curckt->ci_ckt) { #ifdef CIDER -/* begin cider integration */ - if (!name || eq(name, "circuit") || eq(name, "task")) { - paramname = NULL; - } else { - paramname = name; - } - vfree = v = if_getstat(ft_curckt->ci_ckt, paramname); - if (paramname && v) { +/* begin cider integration */ + if (!name || eq(name, "circuit") || eq(name, "task")) + paramname = NULL; + else + paramname = name; + + vfree = v = if_getstat(ft_curckt->ci_ckt, paramname); + if (paramname && v) { /* end cider integration */ -#else /* ~CIDER */ - if (name && eq(name, "task")) - vfree = v = if_getstat(ft_curckt->ci_ckt, NULL); - else - vfree = v = if_getstat(ft_curckt->ci_ckt, name); - if (name && v) { -#endif +#else /* ~CIDER */ + if (name && eq(name, "task")) + vfree = v = if_getstat(ft_curckt->ci_ckt, NULL); + else + vfree = v = if_getstat(ft_curckt->ci_ckt, name); + + if (name && v) { +#endif fprintf(cp_out, "%s = ", v->va_name); wl_print(cp_varwl(v), cp_out); (void) putc('\n', cp_out); @@ -461,69 +464,70 @@ printres(char *name) #ifdef CIDER /* begin cider integration */ /* Now print out interesting stuff about numerical devices. */ - if (!name || eq(name, "devices")) { - (void) NDEVacct(ft_curckt->ci_ckt, cp_out); - yy = TRUE; - } - /* end cider integration */ + if (!name || eq(name, "devices")) { + (void) NDEVacct(ft_curckt->ci_ckt, cp_out); + yy = TRUE; + } + /* end cider integration */ #endif - } if (!yy) { - fprintf(cp_err, "Note: no resource usage information for '%s',\n", - name); + fprintf(cp_err, "Note: no resource usage information for '%s',\n", name); fprintf(cp_err, "\tor no active circuit available\n"); } - if(vfree) free_struct_variable(vfree); + + if (vfree) + free_struct_variable(vfree); return; } + /* Print to stream the given memory size in a human friendly format */ static void -fprintmem(FILE* stream, unsigned long long memory) { +fprintmem(FILE *stream, unsigned long long memory) { if (memory > 1048576) - fprintf(stream, "%8.6f MB", (double)memory / 1048576.); - else if (memory > 1024) - fprintf(stream, "%5.3f kB", (double)memory / 1024.); + fprintf(stream, "%8.6f MB", (double)memory / 1048576.); + else if (memory > 1024) + fprintf(stream, "%5.3f kB", (double)memory / 1024.); else - fprintf(stream, "%llu bytes", memory); + fprintf(stream, "%llu bytes", memory); } -#if defined(HAVE_WIN32) || defined(HAVE__PROC_MEMINFO) + +#if defined(HAVE_WIN32) || defined(HAVE__PROC_MEMINFO) static int get_procm(struct proc_mem *memall) { -#if defined (_MSC_VER) || defined(__MINGW32__) + +#if defined(_MSC_VER) || defined(__MINGW32__) #if (_WIN32_WINNT >= 0x0500) && defined(HAS_WINDOWS) /* Use Windows API function to obtain size of memory - more accurate */ HANDLE hProcess; PROCESS_MEMORY_COUNTERS pmc; DWORD procid = GetCurrentProcessId(); - hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | - PROCESS_VM_READ, - FALSE, procid ); + hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, + FALSE, procid); if (NULL == hProcess) return 0; /* psapi library required */ - if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ) { + if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc))) { memall->size = pmc.WorkingSetSize/1024; memall->resident = pmc.QuotaNonPagedPoolUsage/1024; memall->trs = pmc.QuotaPagedPoolUsage/1024; - } - else { - CloseHandle( hProcess ); + } else { + CloseHandle(hProcess); return 0; } - CloseHandle( hProcess ); -#else + CloseHandle(hProcess); +#else /* Use Windows GlobalMemoryStatus or /proc/memory to obtain size of memory - not accurate */ get_sysmem(&mem_t_act); /* size is the difference between free memory at start time and now */ - if (mem_t.free > mem_t_act.free) /* it can happen that that ngspice is */ - memall->size = (mem_t.free - mem_t_act.free)/1024; /* to small compared to os memory usage */ + if (mem_t.free > mem_t_act.free) /* it can happen that that ngspice is */ + memall->size = (mem_t.free - mem_t_act.free)/1024; /* to small compared to os memory usage */ else - memall->size = 0; /* sure, it is more */ + memall->size = 0; /* sure, it is more */ memall->resident = 0; memall->trs = 0; #endif /* _WIN32_WINNT 0x0500 && HAS_WINDOWS */ @@ -532,97 +536,101 @@ static int get_procm(struct proc_mem *memall) { FILE *fp; char buffer[1024], fibuf[100]; size_t bytes_read; - - (void) sprintf(fibuf, "/proc/%d/statm", getpid()); - - if((fp = fopen(fibuf, "r")) == NULL) { - perror("fopen(\"/proc/%d/statm\")"); - return 0; + + (void) sprintf(fibuf, "/proc/%d/statm", getpid()); + + if ((fp = fopen(fibuf, "r")) == NULL) { + perror("fopen(\"/proc/%d/statm\")"); + return 0; } - bytes_read = fread (buffer, 1, sizeof (buffer), fp); - fclose (fp); - if (bytes_read == 0 || bytes_read == sizeof (buffer)) - return 0; + bytes_read = fread(buffer, 1, sizeof(buffer), fp); + fclose(fp); + if (bytes_read == 0 || bytes_read == sizeof(buffer)) + return 0; buffer[bytes_read] = '\0'; - - sscanf (buffer, "%llu %llu %llu %llu %llu %llu %llu", &memall->size, &memall->resident, &memall->shared, &memall->trs, &memall->drs, &memall->lrs, &memall->dt); + + sscanf(buffer, "%llu %llu %llu %llu %llu %llu %llu", &memall->size, &memall->resident, &memall->shared, &memall->trs, &memall->drs, &memall->lrs, &memall->dt); #endif - return 1; + return 1; } -static int get_sysmem(struct sys_mem *memall) { + +static int +get_sysmem(struct sys_mem *memall) +{ #ifdef HAVE_WIN32 -#if ( _WIN32_WINNT >= 0x0500) - MEMORYSTATUSEX ms; - ms.dwLength = sizeof(MEMORYSTATUSEX); - GlobalMemoryStatusEx( &ms); - memall->size = ms.ullTotalPhys; - memall->free = ms.ullAvailPhys; - memall->swap_t = ms.ullTotalPageFile; - memall->swap_f = ms.ullAvailPageFile; +#if (_WIN32_WINNT >= 0x0500) + MEMORYSTATUSEX ms; + ms.dwLength = sizeof(MEMORYSTATUSEX); + GlobalMemoryStatusEx(&ms); + memall->size = ms.ullTotalPhys; + memall->free = ms.ullAvailPhys; + memall->swap_t = ms.ullTotalPageFile; + memall->swap_f = ms.ullAvailPageFile; #else - MEMORYSTATUS ms; - ms.dwLength = sizeof(MEMORYSTATUS); - GlobalMemoryStatus( &ms); - memall->size = ms.dwTotalPhys; - memall->free = ms.dwAvailPhys; - memall->swap_t = ms.dwTotalPageFile; - memall->swap_f = ms.dwAvailPageFile; + MEMORYSTATUS ms; + ms.dwLength = sizeof(MEMORYSTATUS); + GlobalMemoryStatus(&ms); + memall->size = ms.dwTotalPhys; + memall->free = ms.dwAvailPhys; + memall->swap_t = ms.dwTotalPageFile; + memall->swap_f = ms.dwAvailPageFile; #endif /*_WIN32_WINNT 0x0500*/ #else - FILE *fp; - char buffer[2048]; - size_t bytes_read; - char *match; - unsigned long long mem_got; + FILE *fp; + char buffer[2048]; + size_t bytes_read; + char *match; + unsigned long long mem_got; - if((fp = fopen("/proc/meminfo", "r")) == NULL) { - perror("fopen(\"/proc/meminfo\")"); - return 0; - } - - bytes_read = fread (buffer, 1, sizeof (buffer), fp); - fclose (fp); - if (bytes_read == 0 || bytes_read == sizeof (buffer)) - return 0; - buffer[bytes_read] = '\0'; + if ((fp = fopen("/proc/meminfo", "r")) == NULL) { + perror("fopen(\"/proc/meminfo\")"); + return 0; + } - /* Search for string "MemTotal" */ - match = strstr (buffer, "MemTotal"); - if (match == NULL) /* not found */ - return 0; - sscanf (match, "MemTotal: %llu", &mem_got); - memall->size = mem_got*1024; /* 1MB = 1024KB */ - /* Search for string "MemFree" */ - match = strstr (buffer, "MemFree"); - if (match == NULL) /* not found */ - return 0; - sscanf (match, "MemFree: %llu", &mem_got); - memall->free = mem_got*1024; /* 1MB = 1024KB */ - /* Search for string "SwapTotal" */ - match = strstr (buffer, "SwapTotal"); - if (match == NULL) /* not found */ - return 0; - sscanf (match, "SwapTotal: %llu", &mem_got); - memall->swap_t = mem_got*1024; /* 1MB = 1024KB */ - /* Search for string "SwapFree" */ - match = strstr (buffer, "SwapFree"); - if (match == NULL) /* not found */ - return 0; - sscanf (match, "SwapFree: %llu", &mem_got); - memall->swap_f = mem_got*1024; /* 1MB = 1024KB */ -#endif - return 1; + bytes_read = fread(buffer, 1, sizeof(buffer), fp); + fclose(fp); + if (bytes_read == 0 || bytes_read == sizeof(buffer)) + return 0; + buffer[bytes_read] = '\0'; + + /* Search for string "MemTotal" */ + match = strstr(buffer, "MemTotal"); + if (match == NULL) /* not found */ + return 0; + sscanf(match, "MemTotal: %llu", &mem_got); + memall->size = mem_got*1024; /* 1MB = 1024KB */ + /* Search for string "MemFree" */ + match = strstr(buffer, "MemFree"); + if (match == NULL) /* not found */ + return 0; + sscanf(match, "MemFree: %llu", &mem_got); + memall->free = mem_got*1024; /* 1MB = 1024KB */ + /* Search for string "SwapTotal" */ + match = strstr(buffer, "SwapTotal"); + if (match == NULL) /* not found */ + return 0; + sscanf(match, "SwapTotal: %llu", &mem_got); + memall->swap_t = mem_got*1024; /* 1MB = 1024KB */ + /* Search for string "SwapFree" */ + match = strstr(buffer, "SwapFree"); + if (match == NULL) /* not found */ + return 0; + sscanf(match, "SwapFree: %llu", &mem_got); + memall->swap_f = mem_got*1024; /* 1MB = 1024KB */ +#endif + return 1; } #else + #include #include /* - * baseaddr( ) returns the base address of the data segment on most Unix + * baseaddr() returns the base address of the data segment on most Unix * systems. It's an ugly hack for info that should be provided by the OS. */ @@ -630,17 +638,19 @@ static int get_sysmem(struct sys_mem *memall) { * too small doesn't hurt */ -#define LOG2_PAGESIZE 8 +#define LOG2_PAGESIZE 8 + +static JMP_BUF env; -static JMP_BUF env; static RETSIGTYPE fault(void) { - signal(SIGSEGV, (SIGNAL_FUNCTION) fault); /* SysV style */ + signal(SIGSEGV, (SIGNAL_FUNCTION) fault); /* SysV style */ LONGJMP(env, 1); } + static void * baseaddr(void) { @@ -649,10 +659,10 @@ baseaddr(void) #else char *low, *high, *at; long x; - RETSIGTYPE (*orig_signal)( ); + RETSIGTYPE (*orig_signal)(); if (getenv("SPICE_NO_DATASEG_CHECK")) - return 0; + return 0; low = 0; high = (char *) ((unsigned long) sbrk(0) & ~((1 << LOG2_PAGESIZE) - 1)); @@ -661,27 +671,28 @@ baseaddr(void) for (;;) { - at = (char *) ((((long)low >> LOG2_PAGESIZE) - + ((long)high >> LOG2_PAGESIZE)) - << (LOG2_PAGESIZE - 1)); + at = (char *) ((((long)low >> LOG2_PAGESIZE) + + ((long)high >> LOG2_PAGESIZE)) + << (LOG2_PAGESIZE - 1)); - if (at == low || at == high) { - break; - } + if (at == low || at == high) + break; - if (SETJMP(env, 1)) { - low = at; - continue; - } else - x = *at; + if (SETJMP(env, 1)) { + low = at; + continue; + } else { + x = *at; + } - if (SETJMP(env, 1)) { - low = at; - continue; - } else - *at = x; + if (SETJMP(env, 1)) { + low = at; + continue; + } else { + *at = x; + } - high = at; + high = at; } @@ -695,12 +706,10 @@ baseaddr(void) #endif - # ifdef notdef -main( ) +main() { printf("testing\n"); - printf("baseaddr: %#8x topaddr: %#8x\n", baseaddr( ), sbrk(0)); + printf("baseaddr: %#8x topaddr: %#8x\n", baseaddr(), sbrk(0)); } # endif - diff --git a/src/frontend/runcoms.c b/src/frontend/runcoms.c index a4041ac30..a9f95ab13 100644 --- a/src/frontend/runcoms.c +++ b/src/frontend/runcoms.c @@ -28,7 +28,7 @@ Modified: 2000 AlansFixes /* gtri - end - 12/12/90 */ #endif -/* static declarations */ + static int dosim(char *what, wordlist *wl); /* Routines for the commands op, tran, ac, dc, listing, device, state, @@ -59,9 +59,10 @@ com_scirc(wordlist *wl) fprintf(cp_err, "Error: there aren't any circuits loaded.\n"); return; } + if (wl == NULL) { - fprintf(cp_out, - "\tType the number of the desired circuit:\n\n"); + fprintf(cp_out, + "\tType the number of the desired circuit:\n\n"); for (p = ft_circuits; p; p = p->ci_next) { if (ft_curckt == p) fprintf(cp_out, "Current"); @@ -76,35 +77,36 @@ com_scirc(wordlist *wl) for (p = ft_circuits; --i > 0; p = p->ci_next) ; } else { - for (p = ft_circuits; p; p = p->ci_next) - j++; + for (p = ft_circuits; p; p = p->ci_next) + j++; - p=NULL; - if ((sscanf(wl->wl_word, " %d ", &i) != 1) || (i < 0) || (i > j)); - else - for (p = ft_circuits; --i > 0; p = p->ci_next) - ; + p = NULL; + if ((sscanf(wl->wl_word, " %d ", &i) != 1) || (i < 0) || (i > j)) + ; + else + for (p = ft_circuits; --i > 0; p = p->ci_next) + ; /* for (p = ft_circuits; p; p = p->ci_next) * if (ciprefix(wl->wl_word, p->ci_name)) - * break; - */ - if (p == NULL) - { - fprintf(cp_err, "Warning: no such circuit \"%s\"\n",wl->wl_word); + * break; + */ + if (p == NULL) { + fprintf(cp_err, "Warning: no such circuit \"%s\"\n", wl->wl_word); return; } fprintf(cp_out, "\t%s\n", p->ci_name); } if (ft_curckt) { /* Actually this can't be FALSE */ - ft_curckt->ci_devices = - cp_kwswitch(CT_DEVNAMES, p->ci_devices); + ft_curckt->ci_devices = + cp_kwswitch(CT_DEVNAMES, p->ci_devices); ft_curckt->ci_nodes = cp_kwswitch(CT_NODENAMES, p->ci_nodes); } ft_curckt = p; return; } + void com_pz(wordlist *wl) { @@ -112,6 +114,7 @@ com_pz(wordlist *wl) return; } + void com_op(wordlist *wl) { @@ -119,6 +122,7 @@ com_op(wordlist *wl) return; } + void com_dc(wordlist *wl) { @@ -126,6 +130,7 @@ com_dc(wordlist *wl) return; } + void com_ac(wordlist *wl) { @@ -133,6 +138,7 @@ com_ac(wordlist *wl) return; } + void com_tf(wordlist *wl) { @@ -140,6 +146,7 @@ com_tf(wordlist *wl) return; } + void com_tran(wordlist *wl) { @@ -147,6 +154,7 @@ com_tran(wordlist *wl) return; } + void com_sens(wordlist *wl) { @@ -154,6 +162,7 @@ com_sens(wordlist *wl) return; } + void com_disto(wordlist *wl) { @@ -161,6 +170,7 @@ com_disto(wordlist *wl) return; } + void com_noise(wordlist *wl) { @@ -168,9 +178,10 @@ com_noise(wordlist *wl) return; } + #ifdef WITH_PSS /* SP: Steady State Analysis */ -void +void com_pss(wordlist *wl) { dosim("pss", wl); @@ -179,227 +190,230 @@ com_pss(wordlist *wl) /* SP */ #endif + static int dosim( - char *what, /* in: command (pz,op,dc,ac,tf,tran,sens,disto,noise,run) */ - wordlist *wl /* in: command option */ - /* global variables in: ft_curckt, ft_circuits, - out: ft_setflag, ft_intrpt, rawfileFp, rawfileBinary, - last_used_rawfile + char *what, /* in: command (pz,op,dc,ac,tf,tran,sens,disto,noise,run) */ + wordlist *wl /* in: command option */ + /* global variables in: ft_curckt, ft_circuits, + out: ft_setflag, ft_intrpt, rawfileFp, rawfileBinary, + last_used_rawfile */ - ) + ) { - wordlist *ww = NULL; - bool dofile = FALSE; - char buf[BSIZE_SP]; - struct circ *ct; - int err = 0; - /* set file type to binary or to what is given by environmental - variable SPICE_ASCIIRAWFILE in ivars.c */ - bool ascii = AsciiRawFile; - if (eq(what, "run") && wl) - dofile = TRUE; - /* add "what" to beginning of wordlist wl, except "what" equals "run" - and a rawfile name is given (in wl) */ - if (!dofile) { - ww = wl_cons(copy(what), wl); - } - /* reset output file type according to variable given in spinit */ - if (cp_getvar("filetype", CP_STRING, buf)) { - if (eq(buf, "binary")) - ascii = FALSE; - else if (eq(buf, "ascii")) - ascii = TRUE; - else { - fprintf(cp_err, - "Warning: strange file type \"%s\" (using \"ascii\")\n", buf); - ascii = TRUE; - } - } + wordlist *ww = NULL; + bool dofile = FALSE; + char buf[BSIZE_SP]; + struct circ *ct; + int err = 0; + /* set file type to binary or to what is given by environmental + variable SPICE_ASCIIRAWFILE in ivars.c */ + bool ascii = AsciiRawFile; + if (eq(what, "run") && wl) + dofile = TRUE; + /* add "what" to beginning of wordlist wl, except "what" equals "run" + and a rawfile name is given (in wl) */ + if (!dofile) { + ww = wl_cons(copy(what), wl); + } + /* reset output file type according to variable given in spinit */ + if (cp_getvar("filetype", CP_STRING, buf)) { + if (eq(buf, "binary")) + ascii = FALSE; + else if (eq(buf, "ascii")) + ascii = TRUE; + else { + fprintf(cp_err, + "Warning: strange file type \"%s\" (using \"ascii\")\n", buf); + ascii = TRUE; + } + } - if (!ft_curckt) { - fprintf(cp_err, "Error: there aren't any circuits loaded.\n"); - return 1; - } else if (ft_curckt->ci_ckt == NULL) { /* Set noparse? */ - fprintf(cp_err, "Error: circuit not parsed.\n"); - return 1; - } - for (ct = ft_circuits; ct; ct = ct->ci_next) - if (ct->ci_inprogress && (ct != ft_curckt)) { - fprintf(cp_err, - "Warning: losing old state for circuit '%s'\n", - ct->ci_name); - ct->ci_inprogress = FALSE; - } - /* "resume" will never occur in ngspice */ - if (ft_curckt->ci_inprogress && eq(what, "resume")) { - ft_setflag = TRUE; /* don't allow abort upon interrupt during run */ - ft_intrpt = FALSE; - fprintf(cp_err, "Warning: resuming run in progress.\n"); - com_resume(NULL); - ft_setflag = FALSE; /* Now allow aborts again */ - return 0; - } + if (!ft_curckt) { + fprintf(cp_err, "Error: there aren't any circuits loaded.\n"); + return 1; + } else if (ft_curckt->ci_ckt == NULL) { /* Set noparse? */ + fprintf(cp_err, "Error: circuit not parsed.\n"); + return 1; + } + for (ct = ft_circuits; ct; ct = ct->ci_next) + if (ct->ci_inprogress && (ct != ft_curckt)) { + fprintf(cp_err, + "Warning: losing old state for circuit '%s'\n", + ct->ci_name); + ct->ci_inprogress = FALSE; + } + /* "resume" will never occur in ngspice */ + if (ft_curckt->ci_inprogress && eq(what, "resume")) { + ft_setflag = TRUE; /* don't allow abort upon interrupt during run */ + ft_intrpt = FALSE; + fprintf(cp_err, "Warning: resuming run in progress.\n"); + com_resume(NULL); + ft_setflag = FALSE; /* Now allow aborts again */ + return 0; + } - /* From now on until the next prompt, an interrupt will just - * set a flag and let spice finish up, then control will be - * passed back to the user. - */ - ft_setflag = TRUE; /* Don't allow abort upon interrupt during run. */ - ft_intrpt = FALSE; - /* command "run" is given with rawfile name in wl */ - if (dofile) { + /* From now on until the next prompt, an interrupt will just + * set a flag and let spice finish up, then control will be + * passed back to the user. + */ + ft_setflag = TRUE; /* Don't allow abort upon interrupt during run. */ + ft_intrpt = FALSE; + /* command "run" is given with rawfile name in wl */ + if (dofile) { #ifdef PARALLEL_ARCH - if (ARCHme == 0) { + if (ARCHme == 0) { #endif /* PARALLEL_ARCH */ - if (!*wl->wl_word) - rawfileFp = stdout; + if (!*wl->wl_word) + rawfileFp = stdout; #if defined(__MINGW32__) || defined(_MSC_VER) -/* ask if binary or ASCII, open file with wb or w */ - else if (ascii) { - if((rawfileFp = fopen(wl->wl_word, "w")) == NULL) { - perror(wl->wl_word); - ft_setflag = FALSE; - return 1; - } - fprintf(cp_out,"ASCII raw file\n"); - } - else if (!ascii) { - if((rawfileFp = fopen(wl->wl_word, "wb")) == NULL) { - perror(wl->wl_word); - ft_setflag = FALSE; - return 1; - } - fprintf(cp_out,"binary raw file\n"); - } + /* ask if binary or ASCII, open file with wb or w */ + else if (ascii) { + if ((rawfileFp = fopen(wl->wl_word, "w")) == NULL) { + perror(wl->wl_word); + ft_setflag = FALSE; + return 1; + } + fprintf(cp_out, "ASCII raw file\n"); + } + else if (!ascii) { + if ((rawfileFp = fopen(wl->wl_word, "wb")) == NULL) { + perror(wl->wl_word); + ft_setflag = FALSE; + return 1; + } + fprintf(cp_out, "binary raw file\n"); + } /*---------------------------------------------------------------------------*/ -#else - else if (!(rawfileFp = fopen(wl->wl_word, "w"))) { - setvbuf(rawfileFp, rawfileBuf, _IOFBF, RAWBUF_SIZE); - perror(wl->wl_word); - ft_setflag = FALSE; - return 1; - } +#else + else if (!(rawfileFp = fopen(wl->wl_word, "w"))) { + setvbuf(rawfileFp, rawfileBuf, _IOFBF, RAWBUF_SIZE); + perror(wl->wl_word); + ft_setflag = FALSE; + return 1; + } #endif /* __MINGW32__ */ - rawfileBinary = !ascii; + rawfileBinary = !ascii; #ifdef PARALLEL_ARCH - } else { - rawfileFp = NULL; - } + } else { + rawfileFp = NULL; + } #endif /* PARALLEL_ARCH */ - } else { - rawfileFp = NULL; - } + } else { + rawfileFp = NULL; + } - /*save rawfile name */ - if(last_used_rawfile) - tfree(last_used_rawfile); - if(rawfileFp){ - last_used_rawfile = copy(wl->wl_word); - } else { - last_used_rawfile = NULL; - } + /*save rawfile name */ + if (last_used_rawfile) + tfree(last_used_rawfile); + if (rawfileFp) + last_used_rawfile = copy(wl->wl_word); + else + last_used_rawfile = NULL; - ft_curckt->ci_inprogress = TRUE; - /* "sens2" not used in ngspice */ - if (eq(what,"sens2")) { - if (if_sens_run(ft_curckt->ci_ckt, ww, ft_curckt->ci_symtab) == 1) { - /* The circuit was interrupted somewhere. */ - fprintf(cp_err, "%s simulation interrupted\n", what); + ft_curckt->ci_inprogress = TRUE; + /* "sens2" not used in ngspice */ + if (eq(what, "sens2")) { + if (if_sens_run(ft_curckt->ci_ckt, ww, ft_curckt->ci_symtab) == 1) { + /* The circuit was interrupted somewhere. */ + fprintf(cp_err, "%s simulation interrupted\n", what); #ifdef XSPICE - /* gtri - add - 12/12/90 - wbk - record error and return errchk */ - g_ipc.run_error = IPC_TRUE; - if(g_ipc.enabled) - ipc_send_errchk(); - /* gtri - end - 12/12/90 */ + /* gtri - add - 12/12/90 - wbk - record error and return errchk */ + g_ipc.run_error = IPC_TRUE; + if (g_ipc.enabled) + ipc_send_errchk(); + /* gtri - end - 12/12/90 */ #endif - } else - ft_curckt->ci_inprogress = FALSE; - /* Do a run of the circuit */ - } else { - err = if_run(ft_curckt->ci_ckt, what, ww, ft_curckt->ci_symtab); - if (err == 1) { - /* The circuit was interrupted somewhere. */ - fprintf(cp_err, "%s simulation interrupted\n", what); + } else { + ft_curckt->ci_inprogress = FALSE; + } + /* Do a run of the circuit */ + } else { + err = if_run(ft_curckt->ci_ckt, what, ww, ft_curckt->ci_symtab); + if (err == 1) { + /* The circuit was interrupted somewhere. */ + fprintf(cp_err, "%s simulation interrupted\n", what); #ifdef XSPICE - /* record error and return errchk */ - g_ipc.run_error = IPC_TRUE; - if(g_ipc.enabled) - ipc_send_errchk(); - /* gtri - end - 12/12/90 */ + /* record error and return errchk */ + g_ipc.run_error = IPC_TRUE; + if (g_ipc.enabled) + ipc_send_errchk(); + /* gtri - end - 12/12/90 */ #endif - err = 0; - } else if (err == 2) { - fprintf(cp_err, "%s simulation(s) aborted\n", what); - ft_curckt->ci_inprogress = FALSE; - err = 1; - } else - ft_curckt->ci_inprogress = FALSE; - } - /* close the rawfile */ - if (rawfileFp){ - if (ftell(rawfileFp)==0) { - (void) fclose(rawfileFp); - (void) unlink(wl->wl_word); - } else { - (void) fclose(rawfileFp); - } - } - ft_curckt->ci_runonce = TRUE; - ft_setflag = FALSE; + err = 0; + } else if (err == 2) { + fprintf(cp_err, "%s simulation(s) aborted\n", what); + ft_curckt->ci_inprogress = FALSE; + err = 1; + } else { + ft_curckt->ci_inprogress = FALSE; + } + } + /* close the rawfile */ + if (rawfileFp) { + if (ftell(rawfileFp) == 0) { + (void) fclose(rawfileFp); + (void) unlink(wl->wl_word); + } else { + (void) fclose(rawfileFp); + } + } + ft_curckt->ci_runonce = TRUE; + ft_setflag = FALSE; - /* va: garbage collection: unlink first word (inserted here) and tfree it */ - if (!dofile) { - tfree(ww->wl_word); - if (wl) - wl->wl_prev = NULL; - tfree(ww); - } + /* va: garbage collection: unlink first word (inserted here) and tfree it */ + if (!dofile) { + tfree(ww->wl_word); + if (wl) + wl->wl_prev = NULL; + tfree(ww); + } - /* execute the .measure statements */ - if ( !err && ft_curckt->ci_last_an && ft_curckt->ci_meas) - do_measure( ft_curckt->ci_last_an, FALSE ); + /* execute the .measure statements */ + if (!err && ft_curckt->ci_last_an && ft_curckt->ci_meas) + do_measure(ft_curckt->ci_last_an, FALSE); - return err; + return err; } + /* Usage is run [filename] */ void com_run(wordlist *wl) { -/* ft_getsaves(); */ + /* ft_getsaves(); */ dosim("run", wl); return; } + int ft_dorun(char *file) { - static wordlist wl = { NULL, NULL, NULL } ; + static wordlist wl = { NULL, NULL, NULL }; wl.wl_word = file; if (file) return dosim("run", &wl); - else { + else return dosim("run", NULL); - } } + /* ARGSUSED */ /* until the else clause gets put back */ bool ft_getOutReq(FILE **fpp, struct plot **plotp, bool *binp, char *name, char *title) { - NG_IGNORE(title); - NG_IGNORE(name); - NG_IGNORE(plotp); + NG_IGNORE(title); + NG_IGNORE(name); + NG_IGNORE(plotp); - if (rawfileFp) { - *fpp = rawfileFp; - *binp = rawfileBinary; - return (TRUE); - } else { - return (FALSE); - } + if (rawfileFp) { + *fpp = rawfileFp; + *binp = rawfileBinary; + return (TRUE); + } else { + return (FALSE); + } } - diff --git a/src/frontend/runcoms2.c b/src/frontend/runcoms2.c index 4f9d273ab..65650aabd 100644 --- a/src/frontend/runcoms2.c +++ b/src/frontend/runcoms2.c @@ -40,11 +40,12 @@ extern void line_free_x(struct line * deck, bool recurse); */ /* This is a hack to tell iplot routine to redraw the grid and initialize - the display device - */ + the display device +*/ bool resumption = FALSE; + void com_resume(wordlist *wl) { @@ -77,11 +78,10 @@ com_resume(wordlist *wl) ft_curckt->ci_inprogress = TRUE; ft_setflag = TRUE; - reset_trace( ); - for ( db = dbs, resumption = FALSE; db; db = db->db_next ) - if( db->db_type == DB_IPLOT || db->db_type == DB_IPLOTALL ) { + reset_trace(); + for (db = dbs, resumption = FALSE; db; db = db->db_next) + if (db->db_type == DB_IPLOT || db->db_type == DB_IPLOTALL) resumption = TRUE; - } /*rawfile output saj*/ if (last_used_rawfile) @@ -94,8 +94,7 @@ com_resume(wordlist *wl) ascii = TRUE; else fprintf(cp_err, - "Warning: strange file type \"%s\" (using \"ascii\")\n", - buf); + "Warning: strange file type \"%s\" (using \"ascii\")\n", buf); } if (dofile) { @@ -107,14 +106,14 @@ com_resume(wordlist *wl) #if defined(__MINGW32__) || defined(_MSC_VER) /* ask if binary or ASCII, open file with w or wb hvogt 15.3.2000 */ else if (ascii) { - if((rawfileFp = fopen(last_used_rawfile, "a")) == NULL) { + if ((rawfileFp = fopen(last_used_rawfile, "a")) == NULL) { setvbuf(rawfileFp, rawfileBuf, _IOFBF, RAWBUF_SIZE); perror(last_used_rawfile); ft_setflag = FALSE; return; } } else if (!ascii) { - if((rawfileFp = fopen(last_used_rawfile, "ab")) == NULL) { + if ((rawfileFp = fopen(last_used_rawfile, "ab")) == NULL) { setvbuf(rawfileFp, rawfileBuf, _IOFBF, RAWBUF_SIZE); perror(last_used_rawfile); ft_setflag = FALSE; @@ -147,7 +146,7 @@ com_resume(wordlist *wl) /*close rawfile saj*/ if (rawfileFp) { - if (ftell(rawfileFp)==0) { + if (ftell(rawfileFp) == 0) { (void) fclose(rawfileFp); (void) unlink(last_used_rawfile); } else { @@ -163,11 +162,14 @@ com_resume(wordlist *wl) } else if (err == 2) { fprintf(cp_err, "simulation aborted\n"); ft_curckt->ci_inprogress = FALSE; - } else + } else { ft_curckt->ci_inprogress = FALSE; + } + return; } + /* Throw out the circuit struct and recreate it from the deck. This command * should be obsolete. */ @@ -223,9 +225,9 @@ com_remcirc(wordlist *wl) ft_curckt->ci_vars = NULL; /* delete the deck and parameter list in ft_curckt */ dd = ft_curckt->ci_deck; - line_free(dd,TRUE); + line_free(dd, TRUE); dd = ft_curckt->ci_param; - line_free(dd,TRUE); + line_free(dd, TRUE); tfree(ft_curckt->FTEstats); tfree(ft_curckt->ci_defTask); @@ -257,4 +259,3 @@ com_remcirc(wordlist *wl) return; } - diff --git a/src/frontend/shyu.c b/src/frontend/shyu.c index fee14341a..967798190 100644 --- a/src/frontend/shyu.c +++ b/src/frontend/shyu.c @@ -42,7 +42,7 @@ if_sens_run(CKTcircuit *ckt, wordlist *args, INPtables *tab) int i; int j; int error; - int save ; + int save; int flag = 0; int which = -1; @@ -63,14 +63,14 @@ if_sens_run(CKTcircuit *ckt, wordlist *args, INPtables *tab) err = ft_sim->deleteTask (ft_curckt->ci_ckt, ft_curckt->ci_specTask); if (err) { ft_sperror(err, "deleteTask"); - return(0); /* temporary */ + return (0); /* temporary */ } } err = ft_sim->newTask (ft_curckt->ci_ckt, &(ft_curckt->ci_specTask), "special", & (ft_curckt->ci_defTask)); if (err) { ft_sperror(err, "newTask"); - return(0); /* temporary */ + return (0); /* temporary */ } for (j = 0; j < ft_sim->numAnalyses; j++) @@ -82,14 +82,14 @@ if_sens_run(CKTcircuit *ckt, wordlist *args, INPtables *tab) if (which == -1) { /* in DEEP trouble */ ft_sperror(err, "in DEEP trouble"); - return(0); /* temporary */ + return (0); /* temporary */ } err = ft_sim->newAnalysis (ft_curckt->ci_ckt, which, "options", & (ft_curckt->ci_specOpt), ft_curckt->ci_specTask); if (err) { ft_sperror(err, "createOptions"); - return(0); /* temporary */ + return (0); /* temporary */ } ft_curckt->ci_curOpt = ft_curckt->ci_specOpt; @@ -106,14 +106,14 @@ if_sens_run(CKTcircuit *ckt, wordlist *args, INPtables *tab) current->error = INPerrCat( current->error, INPmkTemp("sensetivity analysis unsupported\n")); - return(0); + return (0); } err = ft_sim->newAnalysis (ft_curckt->ci_ckt, which, "sense", & senseJob, ft_curckt->ci_specTask); if (err) { ft_sperror(err, "createSense"); - return(0); /* temporary */ + return (0); /* temporary */ } save = which; @@ -132,13 +132,13 @@ if_sens_run(CKTcircuit *ckt, wordlist *args, INPtables *tab) current->error = INPerrCat (current->error, INPmkTemp("ac analysis unsupported\n")); - return(0); /* temporary */ + return (0); /* temporary */ } err = ft_sim->newAnalysis (ft_curckt->ci_ckt, which, "acan", & acJob, ft_curckt->ci_specTask); if (err) { ft_sperror(err, "createAC"); /* or similar error message */ - return(0); /* temporary */ + return (0); /* temporary */ } INPgetTok(&line, &steptype, 1); /* get DEC, OCT, or LIN */ @@ -172,13 +172,13 @@ if_sens_run(CKTcircuit *ckt, wordlist *args, INPtables *tab) current->error = INPerrCat (current->error, INPmkTemp("DC operating point analysis unsupported\n")); - return(0); /* temporary */ + return (0); /* temporary */ } err = ft_sim->newAnalysis (ft_curckt->ci_ckt, which, "dcop", & opJob, ft_curckt->ci_specTask); if (err) { ft_sperror(err, "createOP"); /* or similar error message */ - return(0); + return (0); } } @@ -196,13 +196,13 @@ if_sens_run(CKTcircuit *ckt, wordlist *args, INPtables *tab) current->error = INPerrCat (current->error, INPmkTemp("DC transfer curve analysis unsupported\n")); - return(0); /* temporary */ + return (0); /* temporary */ } err = ft_sim->newAnalysis (ft_curckt->ci_ckt, which, "DCtransfer", & dcJob, ft_curckt->ci_specTask); if (err) { ft_sperror(err, "createOP"); /* or similar error message */ - return(0); + return (0); } INPgetTok(&line, &name, 1); INPinsert(&name, tab); @@ -258,13 +258,13 @@ if_sens_run(CKTcircuit *ckt, wordlist *args, INPtables *tab) current->error = INPerrCat (current->error, INPmkTemp("transient analysis unsupported\n")); - return(0); /* temporary */ + return (0); /* temporary */ } err = ft_sim->newAnalysis (ft_curckt->ci_ckt, which, "tranan", & tranJob, ft_curckt->ci_specTask); if (err) { ft_sperror(err, "createTRAN"); - return(0); + return (0); } parm = INPgetValue(ckt, &line, IF_REAL, tab); /* Tstep */ @@ -319,13 +319,13 @@ if_sens_run(CKTcircuit *ckt, wordlist *args, INPtables *tab) current->error = INPerrCat (current->error, INPmkTemp("periodic steady state analysis unsupported\n")); - return(0); /* temporary */ + return (0); /* temporary */ } err = ft_sim->newAnalysis (ft_curckt->ci_ckt, which, "pssan", & pssJob, ft_curckt->ci_specTask); if (err) { ft_sperror(err, "createPSS"); - return(0); + return (0); } parm = INPgetValue(ckt, &line, IF_REAL, tab); /* Guessed Frequency */ @@ -392,11 +392,10 @@ next: } } - if ((err = ft_sim->doAnalyses (ckt, 1, ft_curckt->ci_curTask)) != OK) { ft_sperror(err, "doAnalyses"); - return(0); /* temporary */ + return (0); /* temporary */ } - return(0); + return (0); } diff --git a/src/frontend/signal_handler.c b/src/frontend/signal_handler.c index 8a21fe85b..234843b2b 100644 --- a/src/frontend/signal_handler.c +++ b/src/frontend/signal_handler.c @@ -46,17 +46,17 @@ JMP_BUF jbuf; RETSIGTYPE ft_sigintr(void) { - /* fprintf (cp_err, "Received interrupt. Handling it . . . . .\n"); */ + /* fprintf(cp_err, "Received interrupt. Handling it . . . . .\n"); */ - /* Reinstall ft_signintr as the signal handler. */ - (void) signal( SIGINT, (SIGNAL_FUNCTION) ft_sigintr ); + /* Reinstall ft_signintr as the signal handler. */ + (void) signal(SIGINT, (SIGNAL_FUNCTION) ft_sigintr); gr_clean(); /* Clean up plot window */ - if (ft_intrpt) /* check to see if we're being interrupted repeatedly */ - fprintf(cp_err, "\nInterrupted again (ouch)\n"); - else { - fprintf(cp_err, "\nInterrupted once . . .\n"); + if (ft_intrpt) { /* check to see if we're being interrupted repeatedly */ + fprintf(cp_err, "\nInterrupted again (ouch)\n"); + } else { + fprintf(cp_err, "\nInterrupted once . . .\n"); ft_intrpt = TRUE; } @@ -64,23 +64,22 @@ ft_sigintr(void) return; /* just return without aborting simulation if ft_setflag = TRUE */ } - /* sjb - what to do for editline??? - The following are not supported in editline */ -#if defined(HAVE_GNUREADLINE) - /* Clean up readline after catching signals */ - /* One or all of these might be superfluous */ - (void) rl_free_line_state(); - (void) rl_cleanup_after_signal(); - (void) rl_reset_after_signal(); + /* sjb - what to do for editline??? + The following are not supported in editline */ +#if defined(HAVE_GNUREADLINE) + /* Clean up readline after catching signals */ + /* One or all of these might be superfluous */ + (void) rl_free_line_state(); + (void) rl_cleanup_after_signal(); + (void) rl_reset_after_signal(); #endif /* defined(HAVE_GNUREADLINE) || defined(HAVE_BSDEDITLINE) */ /* To restore screen after an interrupt to a plot for instance */ cp_interactive = TRUE; - cp_resetcontrol(); + cp_resetcontrol(); /* here we jump to the start of command processing in main() after resetting everything. */ LONGJMP(jbuf, 1); - } @@ -92,13 +91,14 @@ sigfloat(int sig, int code) gr_clean(); fperror("Error", code); rewind(cp_out); - (void) signal( SIGFPE, (SIGNAL_FUNCTION) sigfloat ); + (void) signal(SIGFPE, (SIGNAL_FUNCTION) sigfloat); LONGJMP(jbuf, 1); } + /* This should give a new prompt if cshpar is waiting for input. */ -# ifdef SIGTSTP +#ifdef SIGTSTP RETSIGTYPE sigstop(void) @@ -110,6 +110,7 @@ sigstop(void) return; } + RETSIGTYPE sigcont(void) { @@ -118,7 +119,9 @@ sigcont(void) LONGJMP(jbuf, 1); } -# endif + +#endif + /* Special (void) signal handlers. */ @@ -129,6 +132,7 @@ sigill(void) fatal(); } + RETSIGTYPE sigbus(void) { @@ -136,22 +140,21 @@ sigbus(void) fatal(); } + RETSIGTYPE sigsegv(void) { fprintf(cp_err, "\ninternal error -- segmentation violation\n"); #ifdef HAS_WINDOWS winmessage("Fatal error in NGSPICE"); -#endif +#endif fatal(); } + RETSIGTYPE sig_sys(void) { - fprintf(cp_err, - "\ninternal error -- bad argument to system call\n"); + fprintf(cp_err, "\ninternal error -- bad argument to system call\n"); fatal(); } - - diff --git a/src/frontend/spec.c b/src/frontend/spec.c index 25217521a..d9f6ef8fa 100644 --- a/src/frontend/spec.c +++ b/src/frontend/spec.c @@ -18,6 +18,7 @@ Author: 1994 Anthony E. Parker, Department of Electronics, Macquarie Uni. #include "ngspice/missing_math.h" #include "../misc/misc_time.h" + void com_spec(wordlist *wl) { @@ -35,11 +36,13 @@ com_spec(wordlist *wl) fprintf(cp_err, "Error: no vectors loaded.\n"); return; } - if (!isreal(plot_cur->pl_scale) || + + if (!isreal(plot_cur->pl_scale) || ((plot_cur->pl_scale)->v_type != SV_TIME)) { fprintf(cp_err, "Error: spec needs real time scale\n"); return; } + s = wl->wl_word; tlen = (plot_cur->pl_scale)->v_length; if ((freq = ft_numparse(&s, FALSE)) == NULL || (*freq < 0.0)) { @@ -47,6 +50,7 @@ com_spec(wordlist *wl) return; } startf = *freq; + wl = wl->wl_next; s = wl->wl_word; if ((freq = ft_numparse(&s, FALSE)) == NULL || (*freq <= startf)) { @@ -54,6 +58,7 @@ com_spec(wordlist *wl) return; } stopf = *freq; + wl = wl->wl_next; s = wl->wl_word; if ((freq = ft_numparse(&s, FALSE)) == NULL || !(*freq <= (stopf-startf))) { @@ -61,101 +66,106 @@ com_spec(wordlist *wl) return; } stepf = *freq; + wl = wl->wl_next; time = (plot_cur->pl_scale)->v_realdata; span = time[tlen-1] - time[0]; if (stopf > 0.5*tlen/span) { fprintf(cp_err, - "Error: nyquist limit exceeded, try stop freq less than %e Hz\n", - tlen/2/span); + "Error: nyquist limit exceeded, try stop freq less than %e Hz\n", + tlen/2/span); return; } span = ((int)(span*stepf*1.000000000001))/stepf; if (span > 0) { startf = (int)(startf/stepf*1.000000000001) * stepf; fpts = (int)((stopf - startf)/stepf + 1.); - if (stopf > startf + (fpts-1)*stepf) fpts++; + if (stopf > startf + (fpts-1)*stepf) + fpts++; } else { - fprintf(cp_err,"Error: time span limits step freq to %1.1e Hz\n", - 1/(time[tlen-1] - time[0])); + fprintf(cp_err, "Error: time span limits step freq to %1.1e Hz\n", + 1/(time[tlen-1] - time[0])); return; } win = TMALLOC(double, tlen); { - char window[BSIZE_SP]; - double maxt = time[tlen-1]; - if (!cp_getvar("specwindow", CP_STRING, window)) - strcpy(window,"hanning"); - if (eq(window, "none")) - for(i=0; i span) { - win[i] = 0; - } else { + char window[BSIZE_SP]; + double maxt = time[tlen-1]; + if (!cp_getvar("specwindow", CP_STRING, window)) + strcpy(window, "hanning"); + if (eq(window, "none")) + for (i = 0; i < tlen; i++) win[i] = 1; - } - } - else if (eq(window, "hanning") || eq(window, "cosine")) - for(i=0; i span) { - win[i] = 0; - } else { - win[i] = 1 - cos(2*M_PI*(time[i]-maxt)/span); - } - } - else if (eq(window, "hamming")) - for(i=0; i span) { - win[i] = 0; - } else { - win[i] = 1 - 0.92/1.08*cos(2*M_PI*(time[i]-maxt)/span); - } - } - else if (eq(window, "triangle") || eq(window, "bartlet")) - for(i=0; i span) { - win[i] = 0; - } else { - win[i] = 2 - fabs(2+4*(time[i]-maxt)/span); - } - } - else if (eq(window, "blackman")) { - int order; - if (!cp_getvar("specwindoworder", CP_NUM, &order)) order = 2; - if (order < 2) order = 2; /* only order 2 supported here */ - for(i=0; i span) { - win[i] = 0; - } else { - win[i] = 1; - win[i] -= 0.50/0.42*cos(2*M_PI*(time[i]-maxt)/span); - win[i] += 0.08/0.42*cos(4*M_PI*(time[i]-maxt)/span); - } - } - } else if (eq(window, "gaussian")) { - int order; - double scale; - if (!cp_getvar("specwindoworder", CP_NUM, &order)) order = 2; - if (order < 2) order = 2; - scale = pow(2*M_PI/order,0.5)*(0.5-erfc(pow(order,0.5))); - for(i=0; i span) { - win[i] = 0; - } else { - win[i] = exp(-0.5*order*(1-2*(maxt-time[i])/span) - *(1-2*(maxt-time[i])/span))/scale; - } - } - } else { - fprintf(cp_err, "Warning: unknown window type %s\n", window); - tfree(win); - return; - } + else if (eq(window, "rectangular")) + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) { + win[i] = 0; + } else { + win[i] = 1; + } + } + else if (eq(window, "hanning") || eq(window, "cosine")) + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) { + win[i] = 0; + } else { + win[i] = 1 - cos(2*M_PI*(time[i]-maxt)/span); + } + } + else if (eq(window, "hamming")) + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) { + win[i] = 0; + } else { + win[i] = 1 - 0.92/1.08*cos(2*M_PI*(time[i]-maxt)/span); + } + } + else if (eq(window, "triangle") || eq(window, "bartlet")) + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) { + win[i] = 0; + } else { + win[i] = 2 - fabs(2+4*(time[i]-maxt)/span); + } + } + else if (eq(window, "blackman")) { + int order; + if (!cp_getvar("specwindoworder", CP_NUM, &order)) + order = 2; + if (order < 2) /* only order 2 supported here */ + order = 2; + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) { + win[i] = 0; + } else { + win[i] = 1; + win[i] -= 0.50/0.42*cos(2*M_PI*(time[i]-maxt)/span); + win[i] += 0.08/0.42*cos(4*M_PI*(time[i]-maxt)/span); + } + } + } else if (eq(window, "gaussian")) { + int order; + double scale; + if (!cp_getvar("specwindoworder", CP_NUM, &order)) + order = 2; + if (order < 2) + order = 2; + scale = pow(2*M_PI/order, 0.5)*(0.5-erfc(pow(order, 0.5))); + for (i = 0; i < tlen; i++) { + if (maxt-time[i] > span) { + win[i] = 0; + } else { + win[i] = exp(-0.5*order*(1-2*(maxt-time[i])/span) + *(1-2*(maxt-time[i])/span))/scale; + } + } + } else { + fprintf(cp_err, "Warning: unknown window type %s\n", window); + tfree(win); + return; + } } - + names = ft_getpnames(wl, TRUE); first_name = names; vlist = NULL; @@ -171,7 +181,7 @@ com_spec(wordlist *wl) continue; } if (!isreal(vec)) { - fprintf(cp_err, "Error: %s isn't real!\n", + fprintf(cp_err, "Error: %s isn't real!\n", vec->v_name); vec = vec->v_link2; continue; @@ -180,10 +190,10 @@ com_spec(wordlist *wl) vec = vec->v_link2; continue; } - if (!vlist) - vlist = vec; - else - lv->v_link2 = vec; + if (!vlist) + vlist = vec; + else + lv->v_link2 = vec; lv = vec; vec = vec->v_link2; ngood++; @@ -191,16 +201,16 @@ com_spec(wordlist *wl) } free_pnode_o(first_name); /* h_vogt 081206 */ if (!ngood) { - tfree(win); - return; + tfree(win); + return; } - + plot_cur = plot_alloc("spectrum"); plot_cur->pl_next = plot_list; plot_list = plot_cur; plot_cur->pl_title = copy((plot_cur->pl_next)->pl_title); plot_cur->pl_name = copy("Spectrum"); - plot_cur->pl_date = copy(datestring( )); + plot_cur->pl_date = copy(datestring()); freq = TMALLOC(double, fpts); f = alloc(struct dvec); @@ -214,62 +224,64 @@ com_spec(wordlist *wl) tdvec = TMALLOC(double *, ngood); fdvec = TMALLOC(ngcomplex_t *, ngood); - for (i = 0, vec = vlist; iv_realdata; - fdvec[i] = TMALLOC(ngcomplex_t, fpts); - f = alloc(struct dvec); - ZERO(f, struct dvec); - f->v_name = vec_basename(vec); - f->v_type = vec->v_type; - f->v_flags = (VF_COMPLEX | VF_PERMANENT); - f->v_length = fpts; - f->v_compdata = fdvec[i]; - vec_new(f); - vec = vec->v_link2; + for (i = 0, vec = vlist; i < ngood; i++) { + tdvec[i] = vec->v_realdata; + fdvec[i] = TMALLOC(ngcomplex_t, fpts); + f = alloc(struct dvec); + ZERO(f, struct dvec); + f->v_name = vec_basename(vec); + f->v_type = vec->v_type; + f->v_flags = (VF_COMPLEX | VF_PERMANENT); + f->v_length = fpts; + f->v_compdata = fdvec[i]; + vec_new(f); + vec = vec->v_link2; } dc = TMALLOC(double, ngood); - for (i = 0; inewCircuit (&ckt); if (err != OK) { ft_sperror(err, "CKTinit"); - return(NULL); + return (NULL); } /*CDHW Create a task DDD with a new UID. ci_defTask will point to it CDHW*/ @@ -115,7 +114,7 @@ if_inpdeck(struct line *deck, INPtables **tab) err = IFnewUid(ckt, &taskUid, NULL, "default", UID_TASK, NULL); if (err) { ft_sperror(err, "newUid"); - return(NULL); + return (NULL); } #if (0) @@ -125,23 +124,22 @@ if_inpdeck(struct line *deck, INPtables **tab) #endif if (err) { ft_sperror(err, "newTask"); - return(NULL); + return (NULL); } /*CDHW which options available for this simulator? CDHW*/ - for (j = 0; j < ft_sim->numAnalyses; j++) { + for (j = 0; j < ft_sim->numAnalyses; j++) if (strcmp(ft_sim->analyses[j]->name, "options") == 0) { which = j; break; } - } if (which != -1) { err = IFnewUid(ckt, &optUid, NULL, "options", UID_ANALYSIS, NULL); if (err) { ft_sperror(err, "newUid"); - return(NULL); + return (NULL); } err = ft_sim->newAnalysis (ft_curckt->ci_ckt, which, optUid, @@ -152,7 +150,7 @@ if_inpdeck(struct line *deck, INPtables **tab) if (err) { ft_sperror(err, "createOptions"); - return(NULL); + return (NULL); } ft_curckt->ci_curOpt = ft_curckt->ci_defOpt; @@ -181,12 +179,12 @@ if_inpdeck(struct line *deck, INPtables **tab) err = EVTinit(ckt); if (err) { ft_sperror(err, "EVTinit"); - return(NULL); + return (NULL); } /* gtri - end - wbk - 6/6/91 - Finish initialization of event driven structures */ #endif - return(ckt); + return (ckt); } @@ -210,16 +208,16 @@ if_run(CKTcircuit *ckt, char *what, wordlist *args, INPtables *tab) /* First parse the line... */ /*CDHW Look for an interactive task CDHW*/ - if (eq(what, "tran") - || eq(what, "ac") - || eq(what, "dc") - || eq(what, "op") - || eq(what, "pz") - || eq(what, "disto") - || eq(what, "adjsen") - || eq(what, "sens") - || eq(what, "tf") - || eq(what, "noise") + if (eq(what, "tran") || + eq(what, "ac") || + eq(what, "dc") || + eq(what, "op") || + eq(what, "pz") || + eq(what, "disto") || + eq(what, "adjsen") || + eq(what, "sens") || + eq(what, "tf") || + eq(what, "noise") #ifdef WITH_PSS /* SP: Steady State Analysis */ || eq(what, "pss") @@ -244,7 +242,7 @@ if_run(CKTcircuit *ckt, char *what, wordlist *args, INPtables *tab) err = ft_sim->deleteTask (ft_curckt->ci_ckt, ft_curckt->ci_specTask); if (err) { ft_sperror(err, "deleteTask"); - return(2); + return (2); } ft_curckt->ci_specTask = NULL; @@ -257,7 +255,7 @@ if_run(CKTcircuit *ckt, char *what, wordlist *args, INPtables *tab) UID_TASK, NULL); if (err) { ft_sperror(err, "newUid"); - return(2); + return (2); } #if (0) err = ft_sim->newTask (ft_curckt->ci_ckt, @@ -270,7 +268,7 @@ if_run(CKTcircuit *ckt, char *what, wordlist *args, INPtables *tab) #endif if (err) { ft_sperror(err, "newTask"); - return(2); + return (2); } /*CDHW which options available for this simulator? CDHW*/ @@ -286,7 +284,7 @@ if_run(CKTcircuit *ckt, char *what, wordlist *args, INPtables *tab) UID_ANALYSIS, NULL); if (err) { ft_sperror(err, "newUid"); - return(2); + return (2); } err = ft_sim->newAnalysis (ft_curckt->ci_ckt, which, optUid, @@ -297,7 +295,7 @@ if_run(CKTcircuit *ckt, char *what, wordlist *args, INPtables *tab) if (err) { ft_sperror(err, "createOptions"); - return(2); + return (2); } ft_curckt->ci_curOpt = ft_curckt->ci_specOpt; @@ -331,23 +329,23 @@ if_run(CKTcircuit *ckt, char *what, wordlist *args, INPtables *tab) /* -- Find out what we are supposed to do. */ - if ( (eq(what, "tran")) - ||(eq(what, "ac")) - ||(eq(what, "dc")) - ||(eq(what, "op")) - ||(eq(what, "pz")) - ||(eq(what, "disto")) - ||(eq(what, "noise")) - ||(eq(what, "adjsen")) - ||(eq(what, "sens")) - ||(eq(what, "tf")) + if ((eq(what, "tran")) || + (eq(what, "ac")) || + (eq(what, "dc")) || + (eq(what, "op")) || + (eq(what, "pz")) || + (eq(what, "disto")) || + (eq(what, "noise")) || + (eq(what, "adjsen")) || + (eq(what, "sens")) || + (eq(what, "tf")) || #ifdef WITH_PSS - /* SP: Steady State Analysis */ - ||(eq(what, "pss")) - /* SP */ + /* SP: Steady State Analysis */ + (eq(what, "pss")) || + /* SP */ #endif - ||(eq(what, "run")) ) { - + (eq(what, "run"))) + { /*CDHW Run the analysis pointed to by ci_curTask CDHW*/ ft_curckt->ci_curOpt = ft_curckt->ci_defOpt; @@ -355,27 +353,28 @@ if_run(CKTcircuit *ckt, char *what, wordlist *args, INPtables *tab) ft_sperror(err, "doAnalyses"); /* wrd_end(); */ if (err == E_PAUSE) - return(1); + return (1); else - return(2); + return (2); } } else if (eq(what, "resume")) { if ((err = ft_sim->doAnalyses (ckt, 0, ft_curckt->ci_curTask)) != OK) { ft_sperror(err, "doAnalyses"); /* wrd_end(); */ if (err == E_PAUSE) - return(1); + return (1); else - return(2); + return (2); } } else { fprintf(cp_err, "if_run: Internal Error: bad run type %s\n", what); - return(2); + return (2); } - return(0); + return (0); } + /* Set an option in the circuit. Arguments are option name, type, and * value (the last a char *), suitable for casting to whatever needed... */ @@ -396,6 +395,7 @@ static char *obsolete[] = { NULL }; + int if_option(CKTcircuit *ckt, char *name, enum cp_types type, void *value) { @@ -449,14 +449,12 @@ if_option(CKTcircuit *ckt, char *name, enum cp_types type, void *value) /* See if this is unsupported or obsolete. */ for (vv = unsupported; *vv; vv++) if (eq(name, *vv)) { - fprintf(cp_err, - "Warning: option %s is currently unsupported.\n", name); + fprintf(cp_err, "Warning: option %s is currently unsupported.\n", name); return 1; } for (vv = obsolete; *vv; vv++) if (eq(name, *vv)) { - fprintf(cp_err, - "Warning: option %s is obsolete.\n", name); + fprintf(cp_err, "Warning: option %s is obsolete.\n", name); return 1; } return 0; @@ -544,7 +542,7 @@ badtype: break; } fprintf(cp_err, ", type expected was "); - switch(ft_sim->analyses[which]->analysisParms[i].dataType & IF_VARTYPES) { + switch (ft_sim->analyses[which]->analysisParms[i].dataType & IF_VARTYPES) { case IF_REAL: fputs("real.\n", cp_err); break; @@ -561,6 +559,7 @@ badtype: fputs("something strange.\n", cp_err); break; } + if (type == CP_BOOL) fputs("\t(Note that you must use an = to separate option name and value.)\n", cp_err); @@ -576,6 +575,7 @@ if_dump(CKTcircuit *ckt, FILE *file) fprintf(file, "diagnostic output dump unavailable."); } + void if_cktfree(CKTcircuit *ckt, INPtables *tab) { @@ -583,17 +583,18 @@ if_cktfree(CKTcircuit *ckt, INPtables *tab) INPtabEnd(tab); } -/* Return a string describing an error code. */ +/* Return a string describing an error code. */ /* BLOW THIS AWAY.... */ char * if_errstring(int code) { - return(INPerror(code)); + return (INPerror(code)); } + /* Get pointers to a device, its model, and its type number given the name. If * there is no such device, try to find a model with that name * device_or_model says if we are referencing a device or a model. @@ -617,7 +618,7 @@ finddev_special( err = ft_sim->findInstance (ckt, &type, devptr, name, NULL, NULL); if (err == OK) { *device_or_model = 0; - return(type); + return (type); } type = -1; @@ -626,20 +627,22 @@ finddev_special( err = ft_sim->findModel (ckt, &type, modptr, name); if (err == OK) { *device_or_model = 1; - return(type); + return (type); } *modptr = NULL; *device_or_model = 2; - return(-1); + return (-1); } + /* Get a parameter value from the circuit. If name is left unspecified, * we want a circuit parameter. Now works both for devices and models. * A.Roldan (espice) */ struct variable * -spif_getparam_special(CKTcircuit *ckt, char **name, char *param, int ind, int do_model) { +spif_getparam_special(CKTcircuit *ckt, char **name, char *param, int ind, int do_model) +{ struct variable *vv = NULL, *tv; IFvalue *pv; IFparm *opt; @@ -657,7 +660,7 @@ spif_getparam_special(CKTcircuit *ckt, char **name, char *param, int ind, int do typecode = finddev_special(ckt, *name, &dev, &mod, &modelo_dispositivo); if (typecode == -1) { fprintf(cp_err, "Error: no such device or model name %s\n", *name); - return(NULL); + return (NULL); } device = ft_sim->devices[typecode]; if (!modelo_dispositivo) { @@ -683,11 +686,13 @@ spif_getparam_special(CKTcircuit *ckt, char **name, char *param, int ind, int do if (vv) tv->va_next = vv; vv = tv; - } else - fprintf(cp_err, "Internal Error: no parameter '%s' on device '%s'\n", + } else { + fprintf(cp_err, + "Internal Error: no parameter '%s' on device '%s'\n", device->instanceParms[i].keyword, device->name); + } } - return(vv); + return (vv); } else { /* Is it a model or a device ? */ /* It is a model */ for (i = 0; i < *(device->numModelParms); i++) { @@ -702,8 +707,8 @@ spif_getparam_special(CKTcircuit *ckt, char **name, char *param, int ind, int do * IF_STRING, N-channel or P-channel MOS") would not be printed. */ - /* if (!(opt->dataType & IF_ASK ) || (opt->dataType & IF_UNINTERESTING ) || (opt->dataType & IF_STRING)) continue; */ - if (!(opt->dataType & IF_ASK ) || (opt->dataType & IF_UNINTERESTING )) + /* if (!(opt->dataType & IF_ASK) || (opt->dataType & IF_UNINTERESTING) || (opt->dataType & IF_STRING)) continue; */ + if (!(opt->dataType & IF_ASK) || (opt->dataType & IF_UNINTERESTING )) continue; pv = doask(ckt, typecode, dev, mod, opt, ind); if (pv) { @@ -730,41 +735,44 @@ spif_getparam_special(CKTcircuit *ckt, char **name, char *param, int ind, int do if (vv) tv->va_next = vv; vv = tv; - } else - fprintf(cp_err, "Internal Error: no parameter '%s' on device '%s'\n", device->modelParms[i].keyword, device->name); + } else { + fprintf(cp_err, + "Internal Error: no parameter '%s' on device '%s'\n", + device->modelParms[i].keyword, device->name); + } } - return(vv); + return (vv); } } else if (param) { INPretrieve(name, ft_curckt->ci_symtab); typecode = finddev_special(ckt, *name, &dev, &mod, &modelo_dispositivo); if (typecode == -1) { fprintf(cp_err, "Error: no such device or model name %s\n", *name); - return(NULL); + return (NULL); } device = ft_sim->devices[typecode]; opt = parmlookup(device, &dev, param, modelo_dispositivo, 0); if (!opt) { fprintf(cp_err, "Error: no such parameter %s.\n", param); - return(NULL); + return (NULL); } pv = doask(ckt, typecode, dev, mod, opt, ind); if (pv) vv = parmtovar(pv, opt); - return(vv); - } else - return(if_getstat(ckt, *name)); + return (vv); + } else { + return (if_getstat(ckt, *name)); + } } - - /* Get a parameter value from the circuit. If name is left unspecified, * we want a circuit parameter. */ struct variable * -spif_getparam(CKTcircuit *ckt, char **name, char *param, int ind, int do_model) { +spif_getparam(CKTcircuit *ckt, char **name, char *param, int ind, int do_model) +{ struct variable *vv = NULL, *tv; IFvalue *pv; IFparm *opt; @@ -785,7 +793,7 @@ spif_getparam(CKTcircuit *ckt, char **name, char *param, int ind, int do_model) fprintf(cp_err, "Error: no such device or model name %s\n", *name); - return(NULL); + return (NULL); } device = ft_sim->devices[typecode]; for (i = 0; i < *(device->numInstanceParms); i++) { @@ -800,37 +808,36 @@ spif_getparam(CKTcircuit *ckt, char **name, char *param, int ind, int do_model) if (vv) tv->va_next = vv; vv = tv; - } else + } else { fprintf(cp_err, "Internal Error: no parameter '%s' on device '%s'\n", device->instanceParms[i].keyword, device->name); + } } - return(vv); + return (vv); } else if (param) { /* MW. */ INPretrieve(name, ft_curckt->ci_symtab); typecode = finddev(ckt, *name, &dev, &mod); if (typecode == -1) { - fprintf(cp_err, - "Error: no such device or model name %s\n", - *name); - return(NULL); + fprintf(cp_err, "Error: no such device or model name %s\n", *name); + return (NULL); } device = ft_sim->devices[typecode]; opt = parmlookup(device, &dev, param, do_model, 0); if (!opt) { - fprintf(cp_err, "Error: no such parameter %s.\n", - param); - return(NULL); + fprintf(cp_err, "Error: no such parameter %s.\n", param); + return (NULL); } pv = doask(ckt, typecode, dev, mod, opt, ind); if (pv) vv = parmtovar(pv, opt); - return(vv); - } else - return(if_getstat(ckt, *name)); + return (vv); + } else { + return (if_getstat(ckt, *name)); + } } @@ -924,6 +931,7 @@ if_setparam_model(CKTcircuit *ckt, char **name, char *val) } } + void if_setparam(CKTcircuit *ckt, char **name, char *param, struct dvec *val, int do_model) { @@ -964,13 +972,17 @@ if_setparam(CKTcircuit *ckt, char **name, char *param, struct dvec *val, int do_ if ((do_model) && (ckt->CKTtime > 0)) { int error = 0; error = CKTtemp(ckt); - if (error) fprintf(stderr, "Error during changing a device model parameter!\n"); - if (error) controlled_exit(1); + if (error) + fprintf(stderr, "Error during changing a device model parameter!\n"); + if (error) + controlled_exit(1); } } + static struct variable * -parmtovar(IFvalue *pv, IFparm *opt) { +parmtovar(IFvalue *pv, IFparm *opt) +{ struct variable *vv = alloc(struct variable); struct variable *nv; int i = 0; @@ -1027,15 +1039,16 @@ parmtovar(IFvalue *pv, IFparm *opt) { fprintf(cp_err, "parmtovar: Internal Error: bad PARM type %d.\n", opt->dataType); - return(NULL); + return (NULL); } /* It's not clear whether we want the keyword or the desc here... */ vv->va_name = copy(opt->description); vv->va_next = NULL; - return(vv); + return (vv); } + /* Extract the parameter (IFparm structure) from the device or device's model. * If do_mode is TRUE then look in the device's parameters * If do_mode is FALSE then look in the device model's parameters @@ -1054,15 +1067,16 @@ parmlookup(IFdevice *dev, GENinstance **inptr, char *param, int do_model, int in if (!do_model && dev->numInstanceParms) { for (i = 0; i < *(dev->numInstanceParms); i++) { if (!param && (dev->instanceParms[i].dataType & IF_PRINCIPAL)) - return(&dev->instanceParms[i]); + return (&dev->instanceParms[i]); else if (!param) continue; - else if ((((dev->instanceParms[i].dataType & IF_SET) && inout == 1) - || ((dev->instanceParms[i].dataType & IF_ASK) && inout == 0)) - && cieq(dev->instanceParms[i].keyword, param)) { + else if ((((dev->instanceParms[i].dataType & IF_SET) && inout == 1) || + ((dev->instanceParms[i].dataType & IF_ASK) && inout == 0)) && + cieq(dev->instanceParms[i].keyword, param)) + { if (dev->instanceParms[i].dataType & IF_REDUNDANT) i -= 1; - return(&dev->instanceParms[i]); + return (&dev->instanceParms[i]); } } return NULL; @@ -1076,17 +1090,17 @@ parmlookup(IFdevice *dev, GENinstance **inptr, char *param, int do_model, int in { if (dev->modelParms[i].dataType & IF_REDUNDANT) i -= 1; - return(&dev->modelParms[i]); + return (&dev->modelParms[i]); } - return(NULL); + return (NULL); } + /* Perform the CKTask call. We have both 'fast' and 'modfast', so the other * parameters aren't necessary. */ - static IFvalue * doask(CKTcircuit *ckt, int typecode, GENinstance *dev, GENmodel *mod, IFparm *opt, int ind) { @@ -1106,17 +1120,17 @@ doask(CKTcircuit *ckt, int typecode, GENinstance *dev, GENmodel *mod, IFparm *op if (err != OK) { ft_sperror(err, "if_getparam"); - return(NULL); + return (NULL); } - return(&pv); + return (&pv); } + /* Perform the CKTset call. We have both 'fast' and 'modfast', so the other * parameters aren't necessary. */ - static int doset(CKTcircuit *ckt, int typecode, GENinstance *dev, GENmodel *mod, IFparm *opt, struct dvec *val) { @@ -1192,7 +1206,6 @@ doset(CKTcircuit *ckt, int typecode, GENinstance *dev, GENmodel *mod, IFparm *op } - /* Get pointers to a device, its model, and its type number given the name. If * there is no such device, try to find a model with that name. */ @@ -1205,19 +1218,20 @@ finddev(CKTcircuit *ck, char *name, GENinstance **devptr, GENmodel **modptr) err = ft_sim->findInstance (ck, &type, devptr, name, NULL, NULL); if (err == OK) - return(type); + return (type); type = -1; *devptr = NULL; err = ft_sim->findModel (ck, &type, modptr, name); if (err == OK) - return(type); + return (type); *modptr = NULL; - return(-1); + return (-1); } + /* get an analysis parameter by name instead of id */ int @@ -1226,11 +1240,12 @@ if_analQbyName(CKTcircuit *ckt, int which, JOB *anal, char *name, IFvalue *parm) int i; for (i = 0; i < ft_sim->analyses[which]->numParms; i++) if (strcmp(ft_sim->analyses[which]->analysisParms[i].keyword, name) == 0) - return(ft_sim->askAnalysisQuest + return (ft_sim->askAnalysisQuest (ckt, anal, ft_sim->analyses[which]->analysisParms[i].id, parm, NULL)); - return(E_BADPARM); + return (E_BADPARM); } + /* Get the parameters tstart, tstop, and tstep from the CKT struct. */ /* BLOW THIS AWAY TOO */ @@ -1246,53 +1261,55 @@ if_tranparams(struct circ *ci, double *start, double *stop, double *step) IFuid tranUid; if (!ci->ci_curTask) - return(FALSE); + return (FALSE); - for (i = 0; i < ft_sim->numAnalyses; i++) { + for (i = 0; i < ft_sim->numAnalyses; i++) if (strcmp(ft_sim->analyses[i]->name, "TRAN") == 0) { which = i; break; } - } + if (which == -1) - return(FALSE); + return (FALSE); err = IFnewUid(ci->ci_ckt, &tranUid, NULL, "Transient Analysis", UID_ANALYSIS, NULL); if (err != OK) - return(FALSE); + return (FALSE); err = ft_sim->findAnalysis (ci->ci_ckt, &which, &anal, tranUid, ci->ci_curTask, NULL); if (err != OK) - return(FALSE); + return (FALSE); err = if_analQbyName(ci->ci_ckt, which, anal, "tstart", &tmp); if (err != OK) - return(FALSE); + return (FALSE); *start = tmp.rValue; err = if_analQbyName(ci->ci_ckt, which, anal, "tstop", &tmp); if (err != OK) - return(FALSE); + return (FALSE); *stop = tmp.rValue; err = if_analQbyName(ci->ci_ckt, which, anal, "tstep", &tmp); if (err != OK) - return(FALSE); + return (FALSE); *step = tmp.rValue; - return(TRUE); + return (TRUE); } + /* Get the statistic called 'name'. If this is NULL get all statistics * available. */ struct variable * -if_getstat(CKTcircuit *ckt, char *name) { +if_getstat(CKTcircuit *ckt, char *name) +{ int i; struct variable *v, *vars; IFvalue parm; @@ -1306,7 +1323,7 @@ if_getstat(CKTcircuit *ckt, char *name) { if (which == -1) { fprintf(cp_err, "Warning: statistics unsupported\n"); - return(NULL); + return (NULL); } if (name) { @@ -1314,17 +1331,15 @@ if_getstat(CKTcircuit *ckt, char *name) { if (eq(ft_sim->analyses[which]->analysisParms[i].keyword, name)) break; if (i == ft_sim->analyses[which]->numParms) - return(NULL); + return (NULL); if (ft_sim->askAnalysisQuest (ckt, &(ft_curckt->ci_curTask->taskOptions), ft_sim->analyses[which]->analysisParms[i].id, &parm, NULL) == -1) { - fprintf(cp_err, - "if_getstat: Internal Error: can't get %s\n", - name); - return(NULL); + fprintf(cp_err, "if_getstat: Internal Error: can't get %s\n", name); + return (NULL); } - return(parmtovar(&parm, &(ft_sim->analyses[which]->analysisParms[i]))); + return (parmtovar(&parm, &(ft_sim->analyses[which]->analysisParms[i]))); } else { for (i = 0, vars = v = NULL; i < ft_sim->analyses[which]->numParms; i++) { if (!(ft_sim->analyses[which]->analysisParms[i].dataType & IF_ASK)) @@ -1335,7 +1350,7 @@ if_getstat(CKTcircuit *ckt, char *name) { fprintf(cp_err, "if_getstat: Internal Error: can't get %s\n", name); - return(NULL); + return (NULL); } if (v) { v->va_next = @@ -1346,10 +1361,11 @@ if_getstat(CKTcircuit *ckt, char *name) { parmtovar(&parm, &(ft_sim->analyses[which]->analysisParms[i])); } } - return(vars); + return (vars); } } + /* Some small updates to make it work, h_vogt, Feb. 2012 Still very experimental ! It is now possible to save a state during transient simulation, @@ -1414,17 +1430,14 @@ void com_loadsnap(wordlist *wl) file = fopen(wl->wl_next->wl_word, "rb"); if (!file) { - fprintf(cp_err, - "Error: Couldn't open \"%s\" for reading\n", - wl->wl_next->wl_word); + fprintf(cp_err, "Error: Couldn't open \"%s\" for reading\n", wl->wl_next->wl_word); return; } fread(&tmpI, sizeof(int), 1, file); - if (tmpI != sizeof(CKTcircuit) ) { + if (tmpI != sizeof(CKTcircuit)) { fprintf(cp_err, "loaded num: %d, expected num: %ld\n", tmpI, (long)sizeof(CKTcircuit)); - fprintf(cp_err, - "Error: snapshot saved with different version of spice\n"); + fprintf(cp_err, "Error: snapshot saved with different version of spice\n"); fclose(file); return; } @@ -1616,7 +1629,7 @@ void com_loadsnap(wordlist *wl) return; } } - return ; + return; } diff --git a/src/frontend/streams.c b/src/frontend/streams.c index 26d34beb9..66f9c7974 100644 --- a/src/frontend/streams.c +++ b/src/frontend/streams.c @@ -13,14 +13,15 @@ #include "ngspice/cpextern.h" #include "streams.h" + bool cp_debug = FALSE; char cp_gt = '>'; char cp_lt = '<'; char cp_amp = '&'; -FILE *cp_in=NULL; -FILE *cp_out=NULL; -FILE *cp_err=NULL; +FILE *cp_in = NULL; +FILE *cp_out = NULL; +FILE *cp_err = NULL; /* These are the fps that cp_ioreset resets the cp_* to. They are * changed by the source routines. */ diff --git a/src/frontend/subckt.c b/src/frontend/subckt.c index e46333853..857f72e43 100644 --- a/src/frontend/subckt.c +++ b/src/frontend/subckt.c @@ -82,18 +82,18 @@ extern void line_free_x(struct line * deck, bool recurse); } while(0) -/* ----- static declarations ----- */ + struct subs; -static struct line * doit(struct line *deck, wordlist *modnames); +static struct line *doit(struct line *deck, wordlist *modnames); static int translate(struct line *deck, char *formal, char *actual, char *scname, char *subname, struct subs *subs, wordlist const *modnames); struct bxx_buffer; static void finishLine(struct bxx_buffer *dst, char *src, char *scname); static int settrans(char *formal, char *actual, char *subname); -static char * gettrans(const char *name, const char *name_end); +static char *gettrans(const char *name, const char *name_end); static int numnodes(char *name, struct subs *subs, wordlist const *modnames); static int numdevs(char *s); -static bool modtranslate(struct line *deck, char *subname, wordlist **submod, wordlist ** const modnames); +static bool modtranslate(struct line *deck, char *subname, wordlist **submod, wordlist **const modnames); static void devmodtranslate(struct line *deck, char *subname, wordlist * const submod); static int inp_numnodes(char c); @@ -118,7 +118,7 @@ struct subs { int su_numargs; struct line *su_def; /* Pointer to the .subckt definition. */ struct subs *su_next; -} ; +}; /* submod is the list of original model names, modnames is the @@ -135,26 +135,26 @@ static char node[128][128]; static int numgnode; /*------------------------------------------------------------------- - inp_subcktexpand is the top level function which translates - .subckts into mainlined code. Note that there are several things - we need to do: 1. Find all .subckt definitions & stick them - into a list. 2. Find all subcircuit invocations (refdes X) - and replace them with the .subckt definition stored earlier. - 3. Do parameter substitution. + inp_subcktexpand is the top level function which translates + .subckts into mainlined code. Note that there are several things + we need to do: 1. Find all .subckt definitions & stick them + into a list. 2. Find all subcircuit invocations (refdes X) + and replace them with the .subckt definition stored earlier. + 3. Do parameter substitution. - The algorithm is as follows: - 1. Define some aliases for .subckt, .ends, etc. - 2. First numparam pass: substitute paramterized tokens by - intermediate values 1000000001 etc. - 3. Make a list node[] of global nodes - 4. Clean up parens around netnames - 5. Call doit, which does the actual translation. - 6. Second numparam pass: Do final substitution - 7. Check the results & return. - inp_subcktexpand takes as argument a pointer to deck, and - it returns a pointer to the same deck after the new subcircuits - are spliced in. --------------------------------------------------------------------*/ + The algorithm is as follows: + 1. Define some aliases for .subckt, .ends, etc. + 2. First numparam pass: substitute paramterized tokens by + intermediate values 1000000001 etc. + 3. Make a list node[] of global nodes + 4. Clean up parens around netnames + 5. Call doit, which does the actual translation. + 6. Second numparam pass: Do final substitution + 7. Check the results & return. + inp_subcktexpand takes as argument a pointer to deck, and + it returns a pointer to the same deck after the new subcircuits + are spliced in. + -------------------------------------------------------------------*/ struct line * inp_subcktexpand(struct line *deck) { struct line *ll, *c; @@ -181,7 +181,7 @@ inp_subcktexpand(struct line *deck) { use_numparams = TRUE; /* deck has .control sections already removed, but not comments */ - if ( use_numparams ) { + if (use_numparams) { #ifdef TRACE fprintf(stderr, "Numparams is processing this deck:\n"); @@ -192,13 +192,13 @@ inp_subcktexpand(struct line *deck) { } #endif /* TRACE */ - ok = nupa_signal( NUPADECKCOPY, NULL); + ok = nupa_signal(NUPADECKCOPY, NULL); /* get the subckt/model names from the deck */ c = deck; while (c) { /* first Numparam pass */ - if ( ciprefix( ".subckt", c->li_line ) ) + if (ciprefix(".subckt", c->li_line)) nupa_scan(c->li_line, c->li_linenum, TRUE); - if ( ciprefix( ".model", c->li_line ) ) + if (ciprefix(".model", c->li_line)) nupa_scan(c->li_line, c->li_linenum, FALSE); c = c->li_next; } @@ -232,7 +232,7 @@ inp_subcktexpand(struct line *deck) { #ifdef TRACE { - wordlist * w; + wordlist *w; printf("Models found:\n"); for (w = modnames; w; w = w->wl_next) printf("%s\n", w->wl_word); @@ -255,7 +255,8 @@ inp_subcktexpand(struct line *deck) { strncpy(node[numgnode], t, (size_t) i); if (i>0 && t[i-1] != '\0') node[numgnode][i] = '\0'; - while (isspace(*s)) s++; + while (isspace(*s)) + s++; numgnode++; } /* node[] holds name of global node */ #ifdef TRACE @@ -295,7 +296,7 @@ inp_subcktexpand(struct line *deck) { *s = ' '; break; } - } while(*s++); + } while(*s++); } } else if (*s == '.') { continue; /* skip .commands */ @@ -316,7 +317,7 @@ inp_subcktexpand(struct line *deck) { *s = ' '; break; } - } while(*s++); + } while(*s++); } /* if (*s == '(' . . . */ } /* any other line */ } /* for (c = deck . . . */ @@ -341,25 +342,24 @@ inp_subcktexpand(struct line *deck) { for (c = ll; c; c = c->li_next) { if (ciprefix(invoke, c->li_line)) { fprintf(cp_err, "Error: unknown subckt: %s\n", c->li_line); - if ( use_numparams ) { + if (use_numparams) ok = ok && nupa_signal(NUPAEVALDONE, NULL); - } return NULL; } } } - if ( use_numparams ) { + if (use_numparams) { /* the NUMPARAM final line translation pass */ ok = ok && nupa_signal(NUPASUBDONE, NULL); c = ll; while (c) { /* 'param' .meas statements can have dependencies on measurement values */ /* need to skip evaluating here and evaluate after other .meas statements */ - if ( ciprefix( ".meas", c->li_line ) ) { - if ( !strstr( c->li_line, "param" ) ) - nupa_eval( c->li_line, c->li_linenum, c->li_linenum_orig); + if (ciprefix(".meas", c->li_line)) { + if (!strstr(c->li_line, "param")) + nupa_eval(c->li_line, c->li_linenum, c->li_linenum_orig); } else { - nupa_eval( c->li_line, c->li_linenum, c->li_linenum_orig); + nupa_eval(c->li_line, c->li_linenum, c->li_linenum_orig); } c = c->li_next; } @@ -563,8 +563,7 @@ doit(struct line *deck, wordlist *modnames) { */ tofree2 = scname = gettok(&s); /*scname += strlen(invoke); */ - while ((*scname == ' ') || (*scname == '\t') || - (*scname == ':')) + while ((*scname == ' ') || (*scname == '\t') || (*scname == ':')) scname++; /* Now set s to point to last non-space chars in line (i.e. @@ -669,7 +668,7 @@ doit(struct line *deck, wordlist *modnames) { struct line *c = deck; printf("Converted deck\n"); for (; c; c = c->li_next) - printf( "%s\n", c->li_line); + printf("%s\n", c->li_line); } { wordlist *w = modnames; @@ -683,7 +682,7 @@ doit(struct line *deck, wordlist *modnames) { wl_free(submod); if (error) - return NULL; /* error message already reported; should free( ) */ + return NULL; /* error message already reported; should free() */ /* @@ -693,7 +692,7 @@ doit(struct line *deck, wordlist *modnames) { int su_numargs; struct line *su_def; struct subs *su_next; - } ; + }; */ while (subs) { struct subs *sss2 = subs; @@ -708,7 +707,6 @@ doit(struct line *deck, wordlist *modnames) { } - /*-------------------------------------------------------------------*/ /* Copy a deck, including the actual lines. */ /*-------------------------------------------------------------------*/ @@ -720,8 +718,9 @@ inp_deckcopy(struct line *deck) { if (nd) { d->li_next = alloc(struct line); d = d->li_next; - } else + } else { nd = d = alloc(struct line); + } d->li_linenum = deck->li_linenum; d->li_line = copy(deck->li_line); if (deck->li_error) @@ -784,18 +783,21 @@ bxx_init(struct bxx_buffer *t) t->limit = t->buffer + bxx_chunksize; } + static void bxx_free(struct bxx_buffer *t) { tfree(t->buffer); } + static void bxx_rewind(struct bxx_buffer *t) { t->dst = t->buffer; } + static void bxx_extend(struct bxx_buffer *t, int howmuch) { @@ -814,6 +816,7 @@ bxx_extend(struct bxx_buffer *t, int howmuch) t->limit = t->buffer + len; } + static void bxx_printf(struct bxx_buffer *t, const char *fmt, ...) { @@ -838,6 +841,7 @@ bxx_printf(struct bxx_buffer *t, const char *fmt, ...) va_end(ap); } + static inline char bxx_putc(struct bxx_buffer *t, char c) { @@ -846,6 +850,7 @@ bxx_putc(struct bxx_buffer *t, char c) return *(t->dst)++ = c; } + static void bxx_put_cstring(struct bxx_buffer *t, const char *cstring) { @@ -853,6 +858,7 @@ bxx_put_cstring(struct bxx_buffer *t, const char *cstring) bxx_putc(t, *cstring++); } + static void bxx_put_substring(struct bxx_buffer *t, const char *str, const char *end) { @@ -860,6 +866,7 @@ bxx_put_substring(struct bxx_buffer *t, const char *str, const char *end) bxx_putc(t, *str++); } + static char * bxx_buffer(struct bxx_buffer *t) { @@ -914,17 +921,17 @@ translate(struct line *deck, char *formal, char *actual, char *scname, char *sub #ifdef TRACE /* SDB debug statement */ - printf("\nIn translate, examining line (dev_type: %c, subname: %s, instance: %s) %s \n", dev_type, subname, scname, c->li_line ); + printf("\nIn translate, examining line (dev_type: %c, subname: %s, instance: %s) %s \n", dev_type, subname, scname, c->li_line); #endif - if ( ciprefix( ".ic", c->li_line ) || ciprefix( ".nodeset", c->li_line ) ) { + if (ciprefix(".ic", c->li_line) || ciprefix(".nodeset", c->li_line)) { paren_ptr = s = c->li_line; - while ( ( paren_ptr = strstr( paren_ptr, "(" ) ) != NULL) { + while ((paren_ptr = strstr(paren_ptr, "(")) != NULL) { *paren_ptr = '\0'; paren_ptr++; name = paren_ptr; - if ( ( paren_ptr = strstr( paren_ptr, ")" ) ) == NULL) { + if ((paren_ptr = strstr(paren_ptr, ")")) == NULL) { *(name-1) = '('; fprintf(cp_err, "Error: missing closing ')' for .ic|.nodeset statement %s\n", c->li_line); goto quit; @@ -934,10 +941,10 @@ translate(struct line *deck, char *formal, char *actual, char *scname, char *sub if (t) { new_str = TMALLOC(char, strlen(s) + strlen(t) + strlen(paren_ptr + 1) + 3); - sprintf( new_str, "%s(%s)%s", s, t, paren_ptr+1 ); + sprintf(new_str, "%s(%s)%s", s, t, paren_ptr+1); } else { new_str = TMALLOC(char, strlen(s) + strlen(scname) + strlen(name) + strlen(paren_ptr + 1) + 4); - sprintf( new_str, "%s(%s.%s)%s", s, scname, name, paren_ptr+1 ); + sprintf(new_str, "%s(%s.%s)%s", s, scname, name, paren_ptr+1); } paren_ptr = new_str + strlen(s) + 1; @@ -973,7 +980,7 @@ translate(struct line *deck, char *formal, char *actual, char *scname, char *sub name = MIFgettok(&s); bxx_rewind(&buffer); - bxx_printf(&buffer, "a.%s.%s ", scname, name ); + bxx_printf(&buffer, "a.%s.%s ", scname, name); /* Now translate the nodes, looking ahead one token to recognize */ @@ -995,7 +1002,7 @@ translate(struct line *deck, char *formal, char *actual, char *scname, char *sub /* Process the token in name. If it is special, then don't */ /* translate it. */ - switch(*name) { + switch (*name) { case '[': case ']': case '~': @@ -1019,11 +1026,10 @@ translate(struct line *deck, char *formal, char *actual, char *scname, char *sub if (t) { bxx_printf(&buffer, "%s ", t); } else { - if (name[0] == 'v' || name[0] == 'V') { + if (name[0] == 'v' || name[0] == 'V') bxx_printf(&buffer, "v.%s.%s ", scname, name); - } else { + else bxx_printf(&buffer, "%s.%s ", scname, name); - } } break; @@ -1105,8 +1111,8 @@ translate(struct line *deck, char *formal, char *actual, char *scname, char *sub /* get next token */ t = s; next_name = gettok_noparens(&t); - if ( (strcmp(next_name, "POLY") == 0) || - (strcmp(next_name, "poly") == 0)) { /* found POLY . . . . */ + if ((strcmp(next_name, "POLY") == 0) || + (strcmp(next_name, "poly") == 0)) { /* found POLY . . . . */ #ifdef TRACE /* SDB debug statement */ @@ -1114,7 +1120,7 @@ translate(struct line *deck, char *formal, char *actual, char *scname, char *sub #endif /* move pointer ahead of ( */ - if ( get_l_paren(&s) == 1 ) { + if (get_l_paren(&s) == 1) { fprintf(cp_err, "Error: no left paren after POLY %s\n", c->li_line); tfree(next_name); @@ -1126,7 +1132,7 @@ translate(struct line *deck, char *formal, char *actual, char *scname, char *sub tfree(nametofree); /* move pointer ahead of ) */ - if ( get_r_paren(&s) == 1 ) { + if (get_r_paren(&s) == 1) { fprintf(cp_err, "Error: no right paren after POLY %s\n", c->li_line); tfree(next_name); @@ -1136,7 +1142,7 @@ translate(struct line *deck, char *formal, char *actual, char *scname, char *sub /* Write POLY(dim) into buffer */ bxx_printf(&buffer, "POLY( %d ) ", dim); - } /* if ( (strcmp(next_name, "POLY") == 0) . . . */ + } /* if ((strcmp(next_name, "POLY") == 0) . . . */ else dim = 1; /* only one controlling source . . . */ tfree(next_name); @@ -1150,10 +1156,10 @@ translate(struct line *deck, char *formal, char *actual, char *scname, char *sub goto quit; } - if ( (dev_type == 'f') || - (dev_type == 'F') || - (dev_type == 'h') || - (dev_type == 'H') ) { + if ((dev_type == 'f') || + (dev_type == 'F') || + (dev_type == 'h') || + (dev_type == 'H')) { /* Handle voltage source name */ @@ -1213,11 +1219,10 @@ translate(struct line *deck, char *formal, char *actual, char *scname, char *sub bxx_rewind(&buffer); - if ( ch != 'x' ) { + if (ch != 'x') bxx_printf(&buffer, "%c.%s.%s ", ch, scname, name); - } else { + else bxx_printf(&buffer, "%s.%s ", scname, name); - } tfree(nametofree); @@ -1225,7 +1230,7 @@ translate(struct line *deck, char *formal, char *actual, char *scname, char *sub nnodes = numnodes(c->li_line, subs, modnames); while (nnodes-- > 0) { name = gettok_node(&s); - if (name == NULL ) { + if (name == NULL) { fprintf(cp_err, "Error: too few nodes: %s\n", c->li_line); goto quit; } @@ -1257,11 +1262,11 @@ translate(struct line *deck, char *formal, char *actual, char *scname, char *sub } ch = *name; - if ( ch != 'x' ) { + if (ch != 'x') bxx_printf(&buffer, "%c.%s.%s ", ch, scname, name); - } else { + else bxx_printf(&buffer, "%s ", scname); - } + tfree(t); } /* while (nnodes--. . . . */ @@ -1273,7 +1278,7 @@ translate(struct line *deck, char *formal, char *actual, char *scname, char *sub finishLine(&buffer, s, scname); s = ""; - } /* switch(c->li_line . . . . */ + } /* switch (c->li_line . . . . */ bxx_printf(&buffer, "%s", s); tfree(c->li_line); @@ -1299,7 +1304,6 @@ quit: } - /*-------------------------------------------------------------------* * finishLine now doesn't handle current or voltage sources. * Therefore, it just writes out the final netnames, if required. @@ -1337,10 +1341,8 @@ finishLine(struct bxx_buffer *t, char *src, char *scname) bxx_putc(t, *src++); while (isspace(*src)) src++; - for (buf = src; *src && !isspace(*src) && *src != ',' && (*src != ')'); - ) { + for (buf = src; *src && !isspace(*src) && *src != ',' && *src != ')'; ) src++; - } buf_end = src; if ((which == 'v') || (which == 'V')) @@ -1394,6 +1396,7 @@ finishLine(struct bxx_buffer *t, char *src, char *scname) } } + /*------------------------------------------------------------------------------* * settrans builds the table which holds the old and new netnames. * it also compares the number of nets present in the .subckt definition against @@ -1428,12 +1431,13 @@ settrans(char *formal, char *actual, char *subname) return 0; } + /* compare a substring, with a '\0' terminated string * the substring itself is required to be free of a '\0' */ static int -eq_substr(const char* str, const char *end, const char *cstring) +eq_substr(const char *str, const char *end, const char *cstring) { while (str < end) if (*str++ != *cstring++) @@ -1441,6 +1445,7 @@ eq_substr(const char* str, const char *end, const char *cstring) return (*cstring == '\0'); } + /*------------------------------------------------------------------------------* * gettrans returns the name of the top level net if it is in the list, * otherwise it returns NULL. @@ -1467,28 +1472,31 @@ gettrans(const char *name, const char *name_end) if (eq_substr(name, name_end, "0")) return ("0"); + for (i = 0; table[i].t_old; i++) if (eq_substr(name, name_end, table[i].t_old)) return (table[i].t_new); + return (NULL); } + /* check if current token matches model bin name -- .[0-9]+ */ static bool -model_bin_match( char* token, char* model_name ) +model_bin_match(char *token, char *model_name) { - char* dot_char; + char *dot_char; bool flag = FALSE; /* continue evaluation if toeken is part of model_name */ - if ( strncmp( model_name, token, strlen(token) ) == 0 ) { + if (strncmp(model_name, token, strlen(token)) == 0) { /* find last dot in model_name */ - if ( (dot_char = strrchr( model_name, '.' )) != NULL ) { + if ((dot_char = strrchr(model_name, '.')) != NULL) { flag = TRUE; dot_char++; - while ( *dot_char != '\0' ) { - if ( !isdigit( *dot_char ) ) { + while (*dot_char != '\0') { + if (!isdigit(*dot_char)) { flag = FALSE; break; } @@ -1499,6 +1507,7 @@ model_bin_match( char* token, char* model_name ) return flag; } + /*-------------------------------------------------------------------*/ /*-------------------------------------------------------------------*/ static int @@ -1574,7 +1583,7 @@ numnodes(char *name, struct subs *subs, wordlist const *modnames) t = gettok_node(&s); /* get nodenames . . . */ for (wl = modnames; wl; wl = wl->wl_next) { /* also need to check if binnable device mos model */ - if (eq(t, wl->wl_word) || model_bin_match( t, wl->wl_word ) ) + if (eq(t, wl->wl_word) || model_bin_match(t, wl->wl_word)) gotit = 1; } i++; @@ -1587,9 +1596,9 @@ numnodes(char *name, struct subs *subs, wordlist const *modnames) if (i < 5) { fprintf(cp_err, "Error: too few nodes for MOS or CPL: %s\n", name); - return(0); + return (0); } - return(i-1); /* compensate the unnecessary increment in the while cycle */ + return (i-1); /* compensate the unnecessary increment in the while cycle */ } /* if (c == 'm' . . . */ if (nobjthack || (c != 'q')) @@ -1600,7 +1609,6 @@ numnodes(char *name, struct subs *subs, wordlist const *modnames) if (i == 3) return (3); - else if (i < 4) { fprintf(cp_err, "Error: too few nodes for BJT: %s\n", name); return (0); @@ -1635,7 +1643,7 @@ numdevs(char *s) case 'g': case 'E': case 'e': - return(2); + return (2); /* one source per current controlled source */ case 'F': @@ -1652,6 +1660,7 @@ numdevs(char *s) } } + /*----------------------------------------------------------------------* * modtranslate -- translates .model lines found in subckt definitions. * Calling arguments are: @@ -1715,7 +1724,7 @@ modtranslate(struct line *deck, char *subname, wordlist **submod, wordlist ** co } } - return(gotone); + return (gotone); } @@ -1959,18 +1968,18 @@ devmodtranslate(struct line *deck, char *subname, wordlist * const submod) int i = (int) strlen(wlsub->wl_word); int j = 0; /* Now, have we a binned model? */ char* dot_char; - if ( (dot_char = strstr( wlsub->wl_word, "." )) != NULL) { + if ((dot_char = strstr(wlsub->wl_word, ".")) != NULL) { dot_char++; j++; - while ( *dot_char != '\0' ) { - if ( !isdigit( *dot_char ) ) { + while (*dot_char != '\0') { + if (!isdigit(*dot_char)) { break; } dot_char++; j++; } } - if ( strncmp( name, wlsub->wl_word, (size_t) (i - j) ) == 0 ) + if (strncmp(name, wlsub->wl_word, (size_t) (i - j)) == 0) break; } @@ -2003,24 +2012,22 @@ devmodtranslate(struct line *deck, char *subname, wordlist * const submod) wlsub = wl_find(name, submod); - if (!wlsub) { + if (!wlsub) if (*t) { /* There is another token - perhaps a model */ (void) sprintf(buffer + strlen(buffer), "%s ", name); tfree(name); name = gettok(&t); wlsub = wl_find(name, submod); } - } #ifdef ADMS - if (!wlsub) { + if (!wlsub) if (*t) { /* There is another token - perhaps a model */ (void) sprintf(buffer + strlen(buffer), "%s ", name); tfree(name); name = gettok(&t); wlsub = wl_find(name, submod); } - } #endif if (!wlsub) /* Fallback w/o subckt name before */ @@ -2077,6 +2084,7 @@ devmodtranslate(struct line *deck, char *subname, wordlist * const submod) return; } + /*----------------------------------------------------------------------* * inp_numnodes returns the number of nodes (netnames) attached to the * component. diff --git a/src/frontend/terminal.c b/src/frontend/terminal.c index 61f441b25..ad90c099b 100644 --- a/src/frontend/terminal.c +++ b/src/frontend/terminal.c @@ -13,10 +13,12 @@ Author: 1986 Wayne A. Christopher, U. C. Berkeley CAD Group #include + #ifdef HAVE_ASPRINTF #ifdef HAVE_LIBIBERTY_H /* asprintf */ #include -#elif defined(__MINGW32__) || defined(__SUNPRO_C) /* we have asprintf, but not libiberty.h */ +#elif defined(__MINGW32__) || defined(__SUNPRO_C) +/* we have asprintf, but not libiberty.h */ #include extern int asprintf(char **out, const char *fmt, ...); extern int vasprintf(char **out, const char *fmt, va_list ap); @@ -51,18 +53,18 @@ extern int vasprintf(char **out, const char *fmt, va_list ap); #include "variable.h" #include "terminal.h" + bool out_moremode = TRUE; bool out_isatty = TRUE; #ifndef TCL_MODULE #ifdef HAVE_TERMCAP - static char *motion_chars; static char *clear_chars; static char *home_chars; static char *cleol_chars; -#endif /* HAVE_TERMCAP */ +#endif #define DEF_SCRHEIGHT 24 #define DEF_SCRWIDTH 80 @@ -72,7 +74,6 @@ static int xpos, ypos; static bool noprint, nopause; - /* Start output... */ void @@ -87,7 +88,8 @@ out_init(void) if (cp_getvar("nomoremode", CP_BOOL, NULL)) out_moremode = FALSE; else - out_moremode = TRUE; + out_moremode = TRUE; + if (!out_moremode || !cp_interactive) out_isatty = FALSE; @@ -118,44 +120,48 @@ out_init(void) if (!ysize) ysize = DEF_SCRHEIGHT; ysize -= 2; /* Fudge room... */ + xpos = ypos = 0; return; } + /* Putc may not be buffered (sp?), so we do it ourselves. */ static char staticbuf[BUFSIZ]; + struct { int count; char *ptr; } ourbuf = { BUFSIZ, staticbuf }; + /* send buffer out */ void outbufputc(void) { - if (ourbuf.count != BUFSIZ) { - fputs(staticbuf, cp_out); - memset(staticbuf, 0, (size_t) (BUFSIZ - ourbuf.count)); - ourbuf.count = BUFSIZ; - ourbuf.ptr = staticbuf; + fputs(staticbuf, cp_out); + memset(staticbuf, 0, (size_t) (BUFSIZ - ourbuf.count)); + ourbuf.count = BUFSIZ; + ourbuf.ptr = staticbuf; } } + static void bufputc(char c) { if (--ourbuf.count >= 0) { - *ourbuf.ptr++ = c; + *ourbuf.ptr++ = c; } else { - /* Flush and reset the buffer */ - outbufputc(); - /* and store the character. */ - ourbuf.count--; - *ourbuf.ptr++ = c; + /* Flush and reset the buffer */ + outbufputc(); + /* and store the character. */ + ourbuf.count--; + *ourbuf.ptr++ = c; } } @@ -165,39 +171,41 @@ void promptreturn(void) { char buf[16]; + moe: - fprintf(cp_out, - "\n\t-- hit return for more, ? for help -- "); + fprintf(cp_out, "\n\t-- hit return for more, ? for help -- "); + if (!fgets(buf, 16, cp_in)) { clearerr(cp_in); *buf = 'q'; } + switch (*buf) { - case '\n': - break; - case 'q': - noprint = TRUE; - break; - case 'c': - nopause = TRUE; - break; - case ' ': - break; - case '?': - fprintf(cp_out, -"\nPossible responses:\n\ + case '\n': + break; + case 'q': + noprint = TRUE; + break; + case 'c': + nopause = TRUE; + break; + case ' ': + break; + case '?': + fprintf(cp_out, + "\nPossible responses:\n\ \t : Print another screenful\n\ \tq : Discard the rest of the output\n\ \tc : Continuously print the rest of the output\n\ \t? : Print this help message\n"); - goto moe; - default: - fprintf(cp_out, "Character %d is no good\n", *buf); - goto moe; + goto moe; + default: + fprintf(cp_out, "Character %d is no good\n", *buf); + goto moe; } - } + /* Print a string to the output. If this would cause the screen to scroll, * print "more". */ @@ -205,48 +213,54 @@ moe: void out_send(char *string) { - if (noprint) return; + if (!out_isatty || nopause) { fputs(string, cp_out); return; } + while (*string) { switch (*string) { - case '\n': - xpos = 0; - ypos++; - break; - case '\f': - ypos = ysize; - xpos = 0; - break; - case '\t': - xpos = xpos / 8 + 1; - xpos *= 8; - break; - default: - xpos++; - break; + case '\n': + xpos = 0; + ypos++; + break; + case '\f': + ypos = ysize; + xpos = 0; + break; + case '\t': + xpos = xpos / 8 + 1; + xpos *= 8; + break; + default: + xpos++; + break; } + while (xpos >= xsize) { xpos -= xsize; ypos++; } + if (ypos >= ysize) { outbufputc(); /* out goes buffer */ promptreturn(); (void) fflush(cp_out); ypos = xpos = 0; } + bufputc(*string); /* we need to buffer these */ string++; } + (void) outbufputc(); return; } + /* Printf some stuff using more mode. */ void @@ -283,12 +297,13 @@ out_printf(char *fmt, ...) static int outfn(int c) { - putc(c, stdout); - return c; + putc(c, stdout); + return c; } -#endif /* HAVE_TERMCAP */ +#endif -void + +void tcap_init(void) { char *s; @@ -299,18 +314,17 @@ tcap_init(void) charbuf = buf2; - if ((s = getenv("TERM")) != NULL) { - if (tgetent(tbuf, s) != -1) { - xsize = tgetnum("co"); - ysize = tgetnum("li"); - if ((xsize <= 0) || (ysize <= 0)) - xsize = ysize = 0; - clear_chars = tgetstr("cl", &charbuf); - motion_chars = tgetstr("cm", &charbuf); - home_chars = tgetstr("ho", &charbuf); - cleol_chars = tgetstr("ce", &charbuf); - } - } + if ((s = getenv("TERM")) != NULL) + if (tgetent(tbuf, s) != -1) { + xsize = tgetnum("co"); + ysize = tgetnum("li"); + if ((xsize <= 0) || (ysize <= 0)) + xsize = ysize = 0; + clear_chars = tgetstr("cl", &charbuf); + motion_chars = tgetstr("cm", &charbuf); + home_chars = tgetstr("ho", &charbuf); + cleol_chars = tgetstr("ce", &charbuf); + } #endif if (!xsize) { @@ -329,38 +343,38 @@ tcap_init(void) } -void +void term_clear(void) { #ifdef HAVE_TERMCAP if (*clear_chars) - tputs(clear_chars, 1, outfn); + tputs(clear_chars, 1, outfn); else - fputs("\n", stdout); + fputs("\n", stdout); #endif } -void +void term_home(void) { #ifdef HAVE_TERMCAP if (*home_chars) - tputs(home_chars, 1, outfn); + tputs(home_chars, 1, outfn); else if (*motion_chars) - tputs(tgoto(motion_chars, 1, 1), 1, outfn); + tputs(tgoto(motion_chars, 1, 1), 1, outfn); else - fputs("\n", stdout); + fputs("\n", stdout); #endif } -void +void term_cleol(void) { #ifdef HAVE_TERMCAP if (*cleol_chars) - tputs(cleol_chars, 1, outfn); + tputs(cleol_chars, 1, outfn); #endif } @@ -374,25 +388,28 @@ void term_home(void) {} void term_cleol(void) {} void tcap_init(void) {} + void out_send(char *string) { fprintf(cp_out, "%s", string); } + void out_vprintf(const char *fmt, va_list ap) { vfprintf(cp_out, fmt, ap); } + void out_printf(char *fmt, ...) { - va_list ap; - va_start (ap, fmt); - out_vprintf(fmt, ap); - va_end (ap); + va_list ap; + va_start(ap, fmt); + out_vprintf(fmt, ap); + va_end(ap); } #endif /* TCL_MODULE */ diff --git a/src/frontend/testcommands.c b/src/frontend/testcommands.c index da24b5edc..fe22a7ba0 100644 --- a/src/frontend/testcommands.c +++ b/src/frontend/testcommands.c @@ -9,13 +9,14 @@ print_struct_comm(struct comm coms[]) int i; for (i = 0; coms[i].co_comname != NULL; i++) { - printf("Command: %s\n" - "help: %s\n\n", - coms[i].co_comname, - coms[i].co_help); + printf("Command: %s\n" + "help: %s\n\n", + coms[i].co_comname, + coms[i].co_help); } } + int main(void) { diff --git a/src/frontend/trannoise/1-f-code.c b/src/frontend/trannoise/1-f-code.c index 0d827b059..a0bff6de5 100644 --- a/src/frontend/trannoise/1-f-code.c +++ b/src/frontend/trannoise/1-f-code.c @@ -1,6 +1,6 @@ /* Copyright: Holger Vogt, 2008 Generates 1/f noise values according to: - "Discrete simulation of colored noise and stochastic + "Discrete simulation of colored noise and stochastic processes and 1/fa power law noise generation" Kasdin, N.J.; Proceedings of the IEEE @@ -11,7 +11,7 @@ #include #include #include -#include // var. argumente +#include // var. argumente #include "ngspice/ngspice.h" #include "ngspice/cpextern.h" #include "ngspice/cktdefs.h" @@ -20,72 +20,73 @@ #include "ngspice/fftext.h" #include "ngspice/wallace.h" + extern void controlled_exit(int status); -void f_alpha(int n_pts, int n_exp, double X[], double Q_d, -double alpha) +void +f_alpha(int n_pts, int n_exp, double X[], double Q_d, double alpha) { - int i; - double *hfa, *wfa; - double ha; - - ha = alpha/2.0f ; -// Q_d = sqrt(Q_d); /* find the deviation of the noise */ - hfa = TMALLOC(double,n_pts); - wfa = TMALLOC(double,n_pts); - hfa[0] = 1.0f; - wfa[0] = Q_d * GaussWa; - /* generate the coefficients hk */ - for (i=1 ; i < n_pts; i++) { - /* generate the coefficients hk */ - hfa[i] = hfa[i-1] * (ha + (double)(i-1)) / ( (double)(i) ); - /* fill the sequence wk with white noise */ - wfa[i] = Q_d * GaussWa; - } + int i; + double *hfa, *wfa; + double ha; -// for (i=0 ; i < n_pts; i++) -// printf("rnd %e, hk %e\n", wfa[i], hfa[i]); + ha = alpha/2.0f; + // Q_d = sqrt(Q_d); /* find the deviation of the noise */ + hfa = TMALLOC(double,n_pts); + wfa = TMALLOC(double,n_pts); + hfa[0] = 1.0f; + wfa[0] = Q_d * GaussWa; + /* generate the coefficients hk */ + for (i = 1; i < n_pts; i++) { + /* generate the coefficients hk */ + hfa[i] = hfa[i-1] * (ha + (double)(i-1)) / ((double)(i)); + /* fill the sequence wk with white noise */ + wfa[i] = Q_d * GaussWa; + } - /* perform the discrete Fourier transform */ - fftInit(n_exp); - rffts(hfa, n_exp, 1); - rffts(wfa, n_exp, 1) ; + // for (i = 0; i < n_pts; i++) + // printf("rnd %e, hk %e\n", wfa[i], hfa[i]); - /* multiply the two complex vectors */ - rspectprod(hfa, wfa, X, n_pts); - /* inverse transform */ - riffts(X, n_exp, 1); + /* perform the discrete Fourier transform */ + fftInit(n_exp); + rffts(hfa, n_exp, 1); + rffts(wfa, n_exp, 1); - free(hfa) ; - free(wfa); - /* fft tables will be freed in vsrcaccept.c and isrcaccept.c - fftFree(); */ - fprintf(stdout,"%d (2e%d) one over f values created\n", n_pts, n_exp); + /* multiply the two complex vectors */ + rspectprod(hfa, wfa, X, n_pts); + /* inverse transform */ + riffts(X, n_exp, 1); + + free(hfa); + free(wfa); + /* fft tables will be freed in vsrcaccept.c and isrcaccept.c + fftFree(); */ + fprintf(stdout, "%d (2e%d) one over f values created\n", n_pts, n_exp); } - /*-----------------------------------------------------------------------------*/ void trnoise_state_gen(struct trnoise_state *this, CKTcircuit *ckt) { - if(this->top == 0) { + if (this->top == 0) { - if(cp_getvar("notrnoise", CP_BOOL, NULL)) + if (cp_getvar("notrnoise", CP_BOOL, NULL)) this -> NA = this -> TS = this -> NALPHA = this -> NAMP = - this -> RTSAM = this -> RTSCAPT = this -> RTSEMT = 0.0; + this -> RTSAM = this -> RTSCAPT = this -> RTSEMT = 0.0; - if((this->NALPHA > 0.0) && (this->NAMP > 0.0)) { + if ((this->NALPHA > 0.0) && (this->NAMP > 0.0)) { // add 10 steps for start up sequence size_t nosteps = (size_t) (ckt->CKTfinalTime / this->TS) + 10; size_t newsteps = 1; int newexp = 0; + // generate number of steps as power of 2 - while(newsteps < nosteps) { + while (newsteps < nosteps) { newsteps <<= 1; newexp++; } @@ -109,13 +110,13 @@ trnoise_state_gen(struct trnoise_state *this, CKTcircuit *ckt) double ra1, ra2; double NA = this -> NA; - if(NA != 0.0) { + if (NA != 0.0) { #ifdef FastRand // use FastNorm3 ra1 = NA * FastNorm; ra2 = NA * FastNorm; -#elif defined (WaGauss) +#elif defined(WaGauss) // use WallaceHV ra1 = NA * GaussWa; ra2 = NA * GaussWa; @@ -132,10 +133,10 @@ trnoise_state_gen(struct trnoise_state *this, CKTcircuit *ckt) } - if(this -> oneof) { + if (this -> oneof) { - if(this->top + 1 >= this->oneof_length) { - fprintf(stderr,"ouch, noise data exhausted\n"); + if (this->top + 1 >= this->oneof_length) { + fprintf(stderr, "ouch, noise data exhausted\n"); controlled_exit(1); } @@ -146,7 +147,6 @@ trnoise_state_gen(struct trnoise_state *this, CKTcircuit *ckt) trnoise_state_push(this, ra1); trnoise_state_push(this, ra2); } - } @@ -162,12 +162,13 @@ trnoise_state_init(double NA, double TS, double NALPHA, double NAMP, double RTSA this->RTSAM = RTSAM; this->RTSCAPT = RTSCAPT; this->RTSEMT = RTSEMT; + if (RTSAM > 0) { this->RTScapTime = exprand(RTSCAPT); this->RTSemTime = this->RTScapTime + exprand(RTSEMT); } - this -> top = 0; + this -> top = 0; this -> oneof = NULL; return this; diff --git a/src/frontend/trannoise/1-f-code_d.c b/src/frontend/trannoise/1-f-code_d.c index 70451761e..7a50f46b5 100644 --- a/src/frontend/trannoise/1-f-code_d.c +++ b/src/frontend/trannoise/1-f-code_d.c @@ -1,5 +1,5 @@ /* Copyright: Holger Vogt, 2008 - Discrete simulation of colored noise and stochastic + Discrete simulation of colored noise and stochastic processes and 1/fa power law noise generation Kasdin, N.J.; Proceedings of the IEEE @@ -10,7 +10,7 @@ #include #include #include -#include // var. argumente +#include // var. argumente #include "ngspice/1-f-code.h" #include "ngspice/ngspice.h" @@ -18,44 +18,43 @@ #include "ngspice/wallace.h" -void f_alpha(int n_pts, int n_exp, double X[], double Q_d, -double alpha) +void +f_alpha(int n_pts, int n_exp, double X[], double Q_d, double alpha) { - unsigned int i; - double *hfa, *wfa; - double ha; - - ha = alpha/2.0f ; -// Q_d = sqrt(Q_d); /* find the deviation of the noise */ - hfa = TMALLOC(double,n_pts); - wfa = TMALLOC(double,n_pts); - hfa[0] = 1.0f; - wfa[0] = Q_d * GaussWa; - /* generate the coefficients hk */ - for (i=1 ; i < n_pts; i++) { - /* generate the coefficients hk */ - hfa[i] = hfa[i-1] * (ha + (double)(i-1)) / ( (double)(i) ); - /* fill the sequence wk with white noise */ - wfa[i] = Q_d * GaussWa; - } + unsigned int i; + double *hfa, *wfa; + double ha; -// for (i=0 ; i < n_pts; i++) -// printf("rnd %e, hk %e\n", wfa[i], hfa[i]); + ha = alpha/2.0f; + // Q_d = sqrt(Q_d); /* find the deviation of the noise */ + hfa = TMALLOC(double,n_pts); + wfa = TMALLOC(double,n_pts); + hfa[0] = 1.0f; + wfa[0] = Q_d * GaussWa; + /* generate the coefficients hk */ + for (i = 1; i < n_pts; i++) { + /* generate the coefficients hk */ + hfa[i] = hfa[i-1] * (ha + (double)(i-1)) / (double)(i)); + /* fill the sequence wk with white noise */ + wfa[i] = Q_d * GaussWa; + } - /* perform the discrete Fourier transform */ - fftInit(n_exp); - rffts(hfa, n_exp, 1); - rffts(wfa, n_exp, 1) ; + // for (i = 0; i < n_pts; i++) + // printf("rnd %e, hk %e\n", wfa[i], hfa[i]); - /* multiply the two complex vectors */ - rspectprod(hfa, wfa, X, n_pts); - /* inverse transform */ - riffts(X, n_exp, 1); + /* perform the discrete Fourier transform */ + fftInit(n_exp); + rffts(hfa, n_exp, 1); + rffts(wfa, n_exp, 1); - free(hfa) ; - free(wfa); - /* fft tables will be freed in vsrcaccept.c and isrcaccept.c - fftFree(); */ - fprintf(stdout,"%d (2e%d) one over f values created\n", n_pts, n_exp); + /* multiply the two complex vectors */ + rspectprod(hfa, wfa, X, n_pts); + /* inverse transform */ + riffts(X, n_exp, 1); + + free(hfa); + free(wfa); + /* fft tables will be freed in vsrcaccept.c and isrcaccept.c + fftFree(); */ + fprintf(stdout, "%d (2e%d) one over f values created\n", n_pts, n_exp); } - diff --git a/src/frontend/trannoise/FastNorm3.c b/src/frontend/trannoise/FastNorm3.c index 2fb0201ff..6be7aea7f 100644 --- a/src/frontend/trannoise/FastNorm3.c +++ b/src/frontend/trannoise/FastNorm3.c @@ -1,19 +1,20 @@ -/* This is file FastNorm3.c */ -/* SUPERCEDES FastNorm.c, FastNorm2.c. Use with FastNorm3.h */ -/* 24 June 2003 */ +/* This is file FastNorm3.c */ +/* SUPERCEDES FastNorm.c, FastNorm2.c. Use with FastNorm3.h */ +/* 24 June 2003 */ -/* A package containing a very fast generator of pseudo-random - Unit NORMAL variates, and some fairly high-quality UNIFORM - generators. It also contains a straightforward implementation of - a ChiSquared and Gamma generator copied from Ahrens and Dieter. - */ +/* A package containing a very fast generator of pseudo-random + Unit NORMAL variates, and some fairly high-quality UNIFORM + generators. It also contains a straightforward implementation of + a ChiSquared and Gamma generator copied from Ahrens and Dieter. +*/ + +/* Version 3 with double transformations and controllable extension + to repeat the double transformations for higher quality at lower + speed. + Dated 17 May 20003. + Copyright Christopher Stewart Wallace. +*/ -/* Version 3 with double transformations and controllable extension - to repeat the double transformations for higher quality at lower - speed. - Dated 17 May 20003. - Copyright Christopher Stewart Wallace. - */ /* %A C. S. Wallace %T Fast Pseudo-Random Generators for Normal and Exponential Variates. @@ -28,37 +29,38 @@ jrnl, TOMS, numbers, normal, probability, distribution, PRNG, RNG, Gaussian, distribution, jrnl, ACM, TOMS, TR 94 197, TR197, c1996, c199x, c19xx */ -/* Use of this package requires the file "FastNorm3.h" which must be - #include-ed in any C files using this package. - The main purpose of this package is to provide a very fast source +/* Use of this package requires the file "FastNorm3.h" which must be + #include-ed in any C files using this package. + + The main purpose of this package is to provide a very fast source of pseudo-random variates from the Unit Normal N(0,1) distribution, having the density function - f(x) = (1/sqrt(2*PI)) * exp (-0.5 * x^2) + f(x) = (1/sqrt(2*PI)) * exp (-0.5 * x^2) Variates are obtained not by calling a function, but by use of a macro "FastNorm" defined in FastNorm3.h. In a C program, this macro may appear anywhere a (double) expression could appear, e.g in statements like - z += FastNorm; - if (FastNorm < 1.1) ..... - q = fabs (FastNorm); etc. + z += FastNorm; + if (FastNorm < 1.1) ..... + q = fabs (FastNorm); etc. The revision history, and a reference to the method description, is given later in this file under the heading "Revision history Fastnorm". - Major sections of this file, such as the revision history and the + Major sections of this file, such as the revision history and the major subroutines, are all headed by a line containing a row of minus signs (-) and the name of the section or subroutine. - The generators included are: + The generators included are: a Uniform source of integers, unsigned integers and doubles. Chi-sq(N) (based on Ahrens and Dieter) -Gamma(N) (= 0.5 * Chi-sq(2N)) -Normal (a very fast routine) - */ +Gamma(N) (= 0.5 * Chi-sq(2N)) +Normal (a very fast routine) +*/ -/* ----------------- inclusions and some definitions ------------ */ +/* ----------------- inclusions and some definitions ------------ */ #include #ifndef NOSPICE #include "ngspice/ngspice.h" @@ -66,337 +68,356 @@ Normal (a very fast routine) #include "ngspice/FastNorm3.h" -/* --------------- (Uniform) c7rand, irandm, urandm ---------- */ +/* --------------- (Uniform) c7rand, irandm, urandm ---------- */ /* -c A random number generator called as a function by -c c7rand (iseed) or irandm (iseed) or urandm (iseed) +c A random number generator called as a function by +c c7rand (iseed) or irandm (iseed) or urandm (iseed) -c The parameter should be a pointer to a 2-element Sw vector. -c The first call gives a double uniform in 0 .. 1. -c The second gives an Sw integer uniform in 0 .. 2**31-1 -c The third gives an Sw integer with 32 bits, so unif in -c -2**31 .. 2**31-1 if used in 32-bit signed arithmetic. -c All update iseed[] in exactly the same way. -c iseed[] must be a 2-element Sw vector. -c The initial value of iseed[1] may be any 32-bit integer. -c The initial value of iseed[0] may be any 32-bit integer except -1. +c The parameter should be a pointer to a 2-element Sw vector. +c The first call gives a double uniform in 0 .. 1. +c The second gives an Sw integer uniform in 0 .. 2**31-1 +c The third gives an Sw integer with 32 bits, so unif in +c -2**31 .. 2**31-1 if used in 32-bit signed arithmetic. +c All update iseed[] in exactly the same way. +c iseed[] must be a 2-element Sw vector. +c The initial value of iseed[1] may be any 32-bit integer. +c The initial value of iseed[0] may be any 32-bit integer except -1. c -c The period of the random sequence is 2**32 * (2**32-1) -c Its quality is quite good. It is based on the mixed multiplicative -c congruential (Lehmer) generator - x[n+1] = (69069 * x[n] + odd constant) MOD 2^32 -c but avoids most of the well-known defects of this type of generator -c by, in effect, generating x[n+k] from x[n] as defined by the -c sequence above, where k is chosen randomly in 1 ... 128 with the -c help of a subsidiary Tauseworth-type generator. -c For the positve integer generator irandm, the less -c significant digits are more random than is usual for a Lehmer -c generator. The last n<31 digits do not repeat with a period of 2^n. -c This is also true of the unsigned integer generator urandm, but less -c so. +c The period of the random sequence is 2**32 * (2**32-1) +c Its quality is quite good. It is based on the mixed multiplicative +c congruential (Lehmer) generator + x[n+1] = (69069 * x[n] + odd constant) MOD 2^32 +c but avoids most of the well-known defects of this type of generator +c by, in effect, generating x[n+k] from x[n] as defined by the +c sequence above, where k is chosen randomly in 1 ... 128 with the +c help of a subsidiary Tauseworth-type generator. +c For the positve integer generator irandm, the less +c significant digits are more random than is usual for a Lehmer +c generator. The last n<31 digits do not repeat with a period of 2^n. +c This is also true of the unsigned integer generator urandm, but less +c so. -c This is an implementation in C of the algorithm described in -c Technical Report "A Long-Period Pseudo-Random Generator" -c TR89/123, Computer Science, Monash University, -c Clayton, Vic 3168 AUSTRALIA -c by +c This is an implementation in C of the algorithm described in +c Technical Report "A Long-Period Pseudo-Random Generator" +c TR89/123, Computer Science, Monash University, +c Clayton, Vic 3168 AUSTRALIA +c by c -c C.S.Wallace csw@cs.monash.edu.au +c C.S.Wallace csw@cs.monash.edu.au + +c The table mt[0:127] is defined by mt[i] = 69069 ** (128-i) +*/ -c The table mt[0:127] is defined by mt[i] = 69069 ** (128-i) - */ #define MASK ((Sw) 0x12DD4922) -/* or in decimal, 316492066 */ +/* or in decimal, 316492066 */ #define SCALE ((double) 1.0 / (1024.0 * 1024.0 * 1024.0 * 2.0)) -/* i.e. 2 to power -31 */ +/* i.e. 2 to power -31 */ -static Sw mt [128] = { - 902906369, - 2030498053, - -473499623, - 1640834941, - 723406961, - 1993558325, - -257162999, - -1627724755, - 913952737, - 278845029, - 1327502073, - -1261253155, - 981676113, - -1785280363, - 1700077033, - 366908557, - -1514479167, - -682799163, - 141955545, - -830150595, - 317871153, - 1542036469, - -946413879, - -1950779155, - 985397153, - 626515237, - 530871481, - 783087261, - -1512358895, - 1031357269, - -2007710807, - -1652747955, - -1867214463, - 928251525, - 1243003801, - -2132510467, - 1874683889, - -717013323, - 218254473, - -1628774995, - -2064896159, - 69678053, - 281568889, - -2104168611, - -165128239, - 1536495125, - -39650967, - 546594317, - -725987007, - 1392966981, - 1044706649, - 687331773, - -2051306575, - 1544302965, - -758494647, - -1243934099, - -75073759, - 293132965, - -1935153095, - 118929437, - 807830417, - -1416222507, - -1550074071, - -84903219, - 1355292929, - -380482555, - -1818444007, - -204797315, - 170442609, - -1636797387, - 868931593, - -623503571, - 1711722209, - 381210981, - -161547783, - -272740131, - -1450066095, - 2116588437, - 1100682473, - 358442893, - -1529216831, - 2116152005, - -776333095, - 1265240893, - -482278607, - 1067190005, - 333444553, - 86502381, - 753481377, - 39000101, - 1779014585, - 219658653, - -920253679, - 2029538901, - 1207761577, - -1515772851, - -236195711, - 442620293, - 423166617, - -1763648515, - -398436623, - -1749358155, - -538598519, - -652439379, - 430550625, - -1481396507, - 2093206905, - -1934691747, - -962631983, - 1454463253, - -1877118871, - -291917555, - -1711673279, - 201201733, - -474645415, - -96764739, - -1587365199, - 1945705589, - 1303896393, - 1744831853, - 381957665, - 2135332261, - -55996615, - -1190135011, - 1790562961, - -1493191723, - 475559465, - 69069 - }; -double c7rand (Sw *is) +static Sw mt [128] = { + 902906369, + 2030498053, + -473499623, + 1640834941, + 723406961, + 1993558325, + -257162999, + -1627724755, + 913952737, + 278845029, + 1327502073, + -1261253155, + 981676113, + -1785280363, + 1700077033, + 366908557, + -1514479167, + -682799163, + 141955545, + -830150595, + 317871153, + 1542036469, + -946413879, + -1950779155, + 985397153, + 626515237, + 530871481, + 783087261, + -1512358895, + 1031357269, + -2007710807, + -1652747955, + -1867214463, + 928251525, + 1243003801, + -2132510467, + 1874683889, + -717013323, + 218254473, + -1628774995, + -2064896159, + 69678053, + 281568889, + -2104168611, + -165128239, + 1536495125, + -39650967, + 546594317, + -725987007, + 1392966981, + 1044706649, + 687331773, + -2051306575, + 1544302965, + -758494647, + -1243934099, + -75073759, + 293132965, + -1935153095, + 118929437, + 807830417, + -1416222507, + -1550074071, + -84903219, + 1355292929, + -380482555, + -1818444007, + -204797315, + 170442609, + -1636797387, + 868931593, + -623503571, + 1711722209, + 381210981, + -161547783, + -272740131, + -1450066095, + 2116588437, + 1100682473, + 358442893, + -1529216831, + 2116152005, + -776333095, + 1265240893, + -482278607, + 1067190005, + 333444553, + 86502381, + 753481377, + 39000101, + 1779014585, + 219658653, + -920253679, + 2029538901, + 1207761577, + -1515772851, + -236195711, + 442620293, + 423166617, + -1763648515, + -398436623, + -1749358155, + -538598519, + -652439379, + 430550625, + -1481396507, + 2093206905, + -1934691747, + -962631983, + 1454463253, + -1877118871, + -291917555, + -1711673279, + 201201733, + -474645415, + -96764739, + -1587365199, + 1945705589, + 1303896393, + 1744831853, + 381957665, + 2135332261, + -55996615, + -1190135011, + 1790562961, + -1493191723, + 475559465, + 69069 +}; + + +double +c7rand(Sw *is) { - Sw it, leh; + Sw it, leh; - it = is [0]; - leh = is [1]; -/* Do a 7-place right cyclic shift of it */ - it = ((it >> 7) & 0x01FFFFFF) + ((it & 0x7F) << 25); - if (!(it & 0x80000000)) it = it ^ MASK; - leh = (leh * mt[it & 127] + it) & 0xFFFFFFFF; - is [0] = it; is [1] = leh; - if (leh & 0x80000000) leh = leh ^ 0xFFFFFFFF; - return (SCALE * leh); + it = is [0]; + leh = is [1]; + /* Do a 7-place right cyclic shift of it */ + it = ((it >> 7) & 0x01FFFFFF) + ((it & 0x7F) << 25); + if (!(it & 0x80000000)) + it = it ^ MASK; + leh = (leh * mt[it & 127] + it) & 0xFFFFFFFF; + is [0] = it; is [1] = leh; + if (leh & 0x80000000) + leh = leh ^ 0xFFFFFFFF; + return (SCALE * leh); } - -Sw irandm (Sw *is) +Sw +irandm(Sw *is) { - Sw it, leh; + Sw it, leh; - it = is [0]; - leh = is [1]; -/* Do a 7-place right cyclic shift of it */ - it = ((it >> 7) & 0x01FFFFFF) + ((it & 0x7F) << 25); - if (!(it & 0x80000000)) it = it ^ MASK; - leh = (leh * mt[it & 127] + it) & 0xFFFFFFFF; - is [0] = it; is [1] = leh; - if (leh & 0x80000000) leh = leh ^ 0xFFFFFFFF; - return (leh); + it = is [0]; + leh = is [1]; + /* Do a 7-place right cyclic shift of it */ + it = ((it >> 7) & 0x01FFFFFF) + ((it & 0x7F) << 25); + if (!(it & 0x80000000)) + it = it ^ MASK; + leh = (leh * mt[it & 127] + it) & 0xFFFFFFFF; + is [0] = it; is [1] = leh; + if (leh & 0x80000000) + leh = leh ^ 0xFFFFFFFF; + return (leh); } -unsigned int urandm (Sw *is) +unsigned int +urandm(Sw *is) { - Sw it, leh; + Sw it, leh; - it = is [0]; - leh = is [1]; -/* Do a 7-place right cyclic shift of it */ - it = ((it >> 7) & 0x01FFFFFF) + ((it & 0x7F) << 25); - if (!(it & 0x80000000)) it = it ^ MASK; - leh = (leh * mt[it & 127] + it) & 0xFFFFFFFF; - is [0] = it; is [1] = leh; - return (leh); + it = is [0]; + leh = is [1]; + /* Do a 7-place right cyclic shift of it */ + it = ((it >> 7) & 0x01FFFFFF) + ((it & 0x7F) << 25); + if (!(it & 0x80000000)) + it = it ^ MASK; + leh = (leh * mt[it & 127] + it) & 0xFFFFFFFF; + is [0] = it; is [1] = leh; + return (leh); } -/* --------------- (Chi-squared) adchi ----------------------- */ -/* Simple implementation of Ahrens and Dieter method for a chi-sq -random variate of order a >> 1. Uses c7rand, maths library */ -/* 13 July 1998 */ -/* Slightly faster if 'a' is the same as on previous call */ -/* This routine is no longer used in the fastnorm code, but is included -because it may be useful */ +/* --------------- (Chi-squared) adchi ----------------------- */ +/* Simple implementation of Ahrens and Dieter method for a chi-sq +random variate of order a >> 1. Uses c7rand, maths library */ +/* 13 July 1998 */ +/* Slightly faster if 'a' is the same as on previous call */ +/* This routine is no longer used in the fastnorm code, but is included +because it may be useful */ static double gorder, gm, rt2gm, aold; -double adchi (double a, int *is) +double +adchi(double a, int *is) { - double x, y, z, sq; + double x, y, z, sq; - if (a != aold) { - aold = a; gorder = 0.5 * a; - gm = gorder - 1.0; - rt2gm = sqrt (aold - 1.0); - } + if (a != aold) { + aold = a; gorder = 0.5 * a; + gm = gorder - 1.0; + rt2gm = sqrt (aold - 1.0); + } polar: - x = 2.0 * c7rand(is) - 1.0; z = c7rand(is); - sq = x*x + z*z; - if ((sq > 1.0) || (sq < 0.25)) goto polar; - y = x / z; - x = rt2gm * y + gm; - if (x < 0.0) goto polar; + x = 2.0 * c7rand(is) - 1.0; z = c7rand(is); + sq = x*x + z*z; + if ((sq > 1.0) || (sq < 0.25)) + goto polar; + y = x / z; + x = rt2gm * y + gm; + if (x < 0.0) + goto polar; - z = (1.0 + y*y) * exp (gm * log(x/gm) - rt2gm * y); - if (c7rand(is) > z) goto polar; + z = (1.0 + y*y) * exp (gm * log(x/gm) - rt2gm * y); + if (c7rand(is) > z) + goto polar; - return (2.0 * x); -} - -/* -------------------- (Gamma) rgamma (g, is) ----------- */ - -double rgamma (double g, int *is) -{ - double x, y, z, sq; - - if (g != gorder) { - gorder = g; - gm = gorder - 1.0; aold = 2.0 * gorder; - rt2gm = sqrt (aold - 1.0); - } - -polar: - x = 2.0 * c7rand(is) - 1.0; z = c7rand(is); - sq = x*x + z*z; - if ((sq > 1.0) || (sq < 0.25)) goto polar; - y = x / z; - x = rt2gm * y + gm; - if (x < 0.0) goto polar; - - z = (1.0 + y*y) * exp (gm * log(x/gm) - rt2gm * y); - if (c7rand(is) > z) goto polar; - - return (x); + return (2.0 * x); } -/* ------------------ Revision history Fastnorm ------------- */ -/* Items in this revision history appear in chronological order, +/* -------------------- (Gamma) rgamma (g, is) ----------- */ + +double +rgamma(double g, int *is) +{ + double x, y, z, sq; + + if (g != gorder) { + gorder = g; + gm = gorder - 1.0; aold = 2.0 * gorder; + rt2gm = sqrt (aold - 1.0); + } + +polar: + x = 2.0 * c7rand(is) - 1.0; z = c7rand(is); + sq = x*x + z*z; + if ((sq > 1.0) || (sq < 0.25)) + goto polar; + y = x / z; + x = rt2gm * y + gm; + if (x < 0.0) + goto polar; + + z = (1.0 + y*y) * exp (gm * log(x/gm) - rt2gm * y); + if (c7rand(is) > z) + goto polar; + + return (x); +} + + +/* ------------------ Revision history Fastnorm ------------- */ +/* Items in this revision history appear in chronological order, so the most recent revsion appears last. - Revision items are separated by a line of '+' characters. + Revision items are separated by a line of '+' characters. - ++++++++++++++++++++++++++++++++++++++++++++++++++++++ - This is a revised version of the algorithm decribed in + ++++++++++++++++++++++++++++++++++++++++++++++++++++++ + This is a revised version of the algorithm decribed in - ACM Transactions on Mathematical Software, Vol 22, No 1 - March 1996, pp 119-127. + ACM Transactions on Mathematical Software, Vol 22, No 1 + March 1996, pp 119-127. - A fast generator of pseudo-random variates from the unit Normal + A fast generator of pseudo-random variates from the unit Normal distribution. It keeps a pool of about 1000 variates, and generates new ones by picking 4 from the pool, rotating the 4-vector with these as its components, and replacing the old variates with the components of the rotated vector. - The program should initialize the generator by calling initnorm(seed) + The program should initialize the generator by calling initnorm(seed) with seed a Sw integer seed value. Different seed values will give different sequences of Normals. Seed may be any 32-bit integer. - BUT SEE REVISION of 17 May 2003 for initnorm() parameters. - The revised initnorm requires two integer parameters, iseed and - quoll, the latter specifying a tradeoff between speed and - quality. - Then, wherever the program needs a new Normal variate, it should + BUT SEE REVISION of 17 May 2003 for initnorm() parameters. + The revised initnorm requires two integer parameters, iseed and + quoll, the latter specifying a tradeoff between speed and + quality. + Then, wherever the program needs a new Normal variate, it should use the macro FastNorm, e.g. in statements like: - x = FastNorm; (Sets x to a random Normal value) + x = FastNorm; (Sets x to a random Normal value) or - x += a + FastNorm * b; (Adds a normal with mean a, SD b, to x) - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - Changed basic formula, which was: - t = (p+q+r+s)*0.5; p = p-t; q = t-q; r = t-r; s = t-s; - This gives sum of new p+q+r+s = 2p(old) which may not be a great + x += a + FastNorm * b; (Adds a normal with mean a, SD b, to x) + +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + Changed basic formula, which was: + t = (p+q+r+s)*0.5; p = p-t; q = t-q; r = t-r; s = t-s; + This gives sum of new p+q+r+s = 2p(old) which may not be a great choice. The new version is: - t = (p+q+r+s)*0.5; p = p-t; q = q-t; r = t-r; s = t-s; - which gives new p+q+r+s = p+q-r-s (old) which may be better. - +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + t = (p+q+r+s)*0.5; p = p-t; q = q-t; r = t-r; s = t-s; + which gives new p+q+r+s = p+q-r-s (old) which may be better. + +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - Revision 14 November 1998 - The older version "FastNorm" which was available via ftp was found + Revision 14 November 1998 + The older version "FastNorm" which was available via ftp was found to have a defect which could affect some applications. - Dr Christine Rueb, (Max Planck Institut fur Infomatik, - Im Stadtwald W 66123 Saabrucken, F.G.R., - (rueb@mpi-sb.mpg.de) + Dr Christine Rueb, (Max Planck Institut fur Infomatik, + Im Stadtwald W 66123 Saabrucken, F.G.R., + (rueb@mpi-sb.mpg.de) found that if a large number N of consecutive variates were summed to give a variate S with nominally N(0,N) distribution, the variance of S was in some @@ -405,11 +426,11 @@ for N=1023 if the first several (about 128) variates from FastNorm were discarded. Dr. Rueb traced the effect to an unexpected tendency of FastNorm to concentrate values with an anomolous correlation into the first 128 elements of the variate pool. - With the help of her analysis, the algorithm has been revised in a + With the help of her analysis, the algorithm has been revised in a way which appears to overcome the problem, at the cost of about a 19% reduction in speed (which still leaves the method very fast.) - IT MUST BE RECOGNISED THAT THIS ALGORITHM IS NOVEL + IT MUST BE RECOGNISED THAT THIS ALGORITHM IS NOVEL AND WHILE IT PASSES A NUMBER OF STANDARD TESTS FOR DISTRIBUTIONAL FORM, LACK OF SERIAL CORRELATION ETC., IT MAY STILL HAVE DEFECTS. @@ -421,24 +442,24 @@ WOULD BE WISE IN ANY CRITICAL APPLICATION TO COMPARE RESULTS OBTAINED USING IT WITH RESULTS OBTAINED USING A "STANDARD" FORM OF GENERATOR OF NORMAL VARIATES COUPLED WITH A WELL-DOCUMENTED GENERATOR OF UNIFORM VARIATES. - ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - Revision 1 April 2003. - Trying a scanning process proposed by R.P.Brent. It needs 2 pool + Revision 1 April 2003. + Trying a scanning process proposed by R.P.Brent. It needs 2 pool vectors, as it cannot update in-situ, but may be more robust. - It is a bit slower on a 133 Mhz PC but just as fast on a newer PC + It is a bit slower on a 133 Mhz PC but just as fast on a newer PC (moggie) at about 16 ns per call in the 'speed.c' test. - The extreme-value defect is the same on old and new versions. + The extreme-value defect is the same on old and new versions. If one finds a value 'A' such that a batch of B genuine Normal variates has probability 0.2 of containing a variate with abolute value greater than A, then the probability that both of two consecive batches of B will contain such a value should be 0.2 times 0.2, or 0.04. Instead, both versions give the extreme value prob. as 0.200 (over a million batches) but give the consective-pair prob as 0.050 for batch size B = 1024. - ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ - Revision 17 May 2003. - The fundamental defect of the method, namely an inadequate 'mixing' + Revision 17 May 2003. + The fundamental defect of the method, namely an inadequate 'mixing' of squared value ('energy') between one generation of the pool and the next, cannot readily be removed. In going from one pool to the next, the energy in an old variate is shared among just 4 variates in the new pool. Hence it @@ -447,7 +468,7 @@ distributed across the whole pool. The number of generations needed cannot be less than the log to base 4 of the pool size, or 5 for a pool size of 1024. In fact, the pseudo-random indexing of the pool means that rather more generations are needed on average. - The defect is readily revealed by the following test. One picks a + The defect is readily revealed by the following test. One picks a "batch size" comparable to the pool size, say 500 or 1000. One then computes a value A such that a batch will with probability 0.2 contain one or more variates with absolute value exceeding A. @@ -460,80 +481,80 @@ be higher than the proper value (0.2)^2 = 0.04. For batch sizes round the pool size, it can be as high as 0.05. That is, although the frequncy of extreme values is about right, their occurrence in the stream is correlated over a scale of the order of the pool size. - The same correlation effect is seen in the average 4th moment of + The same correlation effect is seen in the average 4th moment of successive batches. - Since this inter-generational correlation cannot be avoided, the + Since this inter-generational correlation cannot be avoided, the this revision seeks to reduce it by performing at least two simple rotations of the pool at each generation. Obviously, some speed is lost, but the correlations are reduced. - To allow the user to trade off speed and quality, the initialization + To allow the user to trade off speed and quality, the initialization function initnorm() now provides a QUALITY parameter 'quoll' which controls how many double-rotations are done for each generation. - See the comments in initnorm() for more detail. - ++++++++++ End of revision notes +++++++++ */ + See the comments in initnorm() for more detail. + ++++++++++ End of revision notes +++++++++ */ -/* ----------------- Some test results ------------------------ */ +/* ----------------- Some test results ------------------------ */ /* General form: - Some simple tests were conducted by transforming FastNorm variates + Some simple tests were conducted by transforming FastNorm variates in several ways to yield a variable nominally uniformly distributed in 0 ... 1. Uniformity of the derived variate was then tested by a ChiSquared test on a 100-cell histogram with cell counts around 10000. These tests are crude, but showed no untoward results on the present version. - Transformations included: - y = 0.5 * (1.0 + erf (n1 / sqrt(2)) + Transformations included: + y = 0.5 * (1.0 + erf (n1 / sqrt(2)) - y = 0.5 * (n1 / (n1^2 + n2^2 + n3^2) - 1) + y = 0.5 * (n1 / (n1^2 + n2^2 + n3^2) - 1) - y = exp (-0.5 * (n1^2 + n2^2)) + y = exp (-0.5 * (n1^2 + n2^2)) - y = (n1^2 + n2^2) / (n1^2 + n2^2 + n3^2 + n4^2) + y = (n1^2 + n2^2) / (n1^2 + n2^2 + n3^2 + n4^2) - where n1, n2 etc are successive Normal variates. + where n1, n2 etc are successive Normal variates. It may be noted that some of these are sensitive to serial correlation if present. Fourth moment of batches: - Extensive tests for correlation among the fourth moments of successive + Extensive tests for correlation among the fourth moments of successive batches of variates were made, with batch sizes comparabe to or (worst case) equal to the size of the variate pool (4096 in this revision). - With 'quality' 1, significant correlation appears after 10^6 batches + With 'quality' 1, significant correlation appears after 10^6 batches of worst-case size. - With quality 2, no significant correlation is evident after 10^7 + With quality 2, no significant correlation is evident after 10^7 batches. A just-significant correlation appears after 3.6*10^7 batches. As this requires some 1.4*10^11 deviates to be drawn, it may be irrelevent for many applications. The observed correlation coefficent was 0.0008. - With quality 3, results are OK after 10^8 batches, or more than + With quality 3, results are OK after 10^8 batches, or more than 4*10^11 variates. - No tests have been done with quality 4 as yet. + No tests have been done with quality 4 as yet. Speed: - Speed tests were done on a PC running RedHat Linux, using "-O" + Speed tests were done on a PC running RedHat Linux, using "-O" compiler optimization. The test loop was - for (i = 0; i < 500000000; i++) { - a += FastNorm; a -= FastNorm; - } - Thus the test makes 10^9 uses of FastNorm. The time taken, (which + for (i = 0; i < 500000000; i++) { + a += FastNorm; a -= FastNorm; + } + Thus the test makes 10^9 uses of FastNorm. The time taken, (which includes time for a call in 'initnorm' and the loop overhead) depends on the 'quality' set by initnorm. - Quality 1: 21.5 sec - Quality 2: 32.1 sec - Quality 3: 42.5 sec - Quality 4: 53.1 sec + Quality 1: 21.5 sec + Quality 2: 32.1 sec + Quality 3: 42.5 sec + Quality 4: 53.1 sec By way of comparison, the same 10^9 call loop was timed with the Unix library "random()" routine substituted for FastNorm, and the variable 'a' defined as integer rather than double. Also, since most use of a Uniform generator such as "random()" requires that the returned integer be scaled into a floating- point number in 0 ... 1, the timing was repeated with - "a += random" ('a' integer) replaced by "a += Scale*random()" where + "a += random" ('a' integer) replaced by "a += Scale*random()" where 'a' is double and Scale = 2^(-31). The times obtained were: - Random (integer): 44.1 sec - Random (double) : 47.7 sec + Random (integer): 44.1 sec + Random (double) : 47.7 sec - It can be seen that FastNorm (even at quality 3) is faster than a + It can be seen that FastNorm (even at quality 3) is faster than a commonly-used Uniform generator. To some extent, this result may vary on different computers and compilers. Since FastNorm (at least for qualities above 1) no doubt does more arithmetic per variate than "random()", much of @@ -541,18 +562,18 @@ its speed advantage must come from its replacement of a function call per variate by a macro which makes only one function call every 4095 variates. Computers with lower 'call' overheads than the PC used here might show differnt results. - Incidently, the Uniform generator 'c7rand()' included in this + Incidently, the Uniform generator 'c7rand()' included in this package, which returns a double uniform in 0 ... 1, and is of fairly high quality, gives a time in the same test of 36.8 sec, a little faster than 'random()'. - */ +*/ -/* ----------------- globals ------------------------- */ -/* A pool must have a length which is a multiple of 4. - * During regeneration of a new pool, the pool is treated as 4 - * consecutive vectors, each of length VL. - */ +/* ----------------- globals ------------------------- */ +/* A pool must have a length which is a multiple of 4. + * During regeneration of a new pool, the pool is treated as 4 + * consecutive vectors, each of length VL. + */ #define VE 10 #define VL (1 << VE) @@ -563,284 +584,308 @@ quality, gives a time in the same test of 36.8 sec, a little faster than Sw gaussfaze; Sf *gausssave; Sf GScale; -/* GScale,fastnorm,gaussfaze, -save must be visible to callers*/ -static Sf chic1, chic2; /* Constants used in getting ChiSq_WL */ -Sw gslew; /* Counts generations */ -static Sw qual; /* Sets number of double transforms per generation. */ -static Sw c7g [2]; /* seed values for c7rand */ +/* GScale,fastnorm,gaussfaze, -save must be visible to callers */ +static Sf chic1, chic2; /* Constants used in getting ChiSq_WL */ +Sw gslew; /* Counts generations */ +static Sw qual; /* Sets number of double transforms per generation. */ +static Sw c7g [2]; /* seed values for c7rand */ -Sf wk1 [WL], wk2 [WL]; /* Pools of variates. */ +Sf wk1 [WL], wk2 [WL]; /* Pools of variates. */ -/* ------------------ regen ---------------------- */ -/* Takes variates from wk1[], transforms to wk[2], then back to wk1[]. - */ -static void regen (void) +/* ------------------ regen ---------------------- */ +/* Takes variates from wk1[], transforms to wk[2], then back to wk1[]. */ + +static void +regen(void) { - Sw i, j, k, m; - Sf p, q, r, s, t; - Sw topv[6], ord[4], *top; - Sf *ppt[4], *ptn; + Sw i, j, k, m; + Sf p, q, r, s, t; + Sw topv[6], ord[4], *top; + Sf *ppt[4], *ptn; -/* Choose 4 random start points in the wk1[] vector - I want them all different. */ + /* Choose 4 random start points in the wk1[] vector + I want them all different. */ - top = topv + 1; -/* Set limiting values in top[-1], top[4] */ - top[-1] = VL; top[4] = 0; + top = topv + 1; + /* Set limiting values in top[-1], top[4] */ + top[-1] = VL; top[4] = 0; reran1: - m = irandm (c7g); /* positive 32-bit random */ -/* Extract two VE-sized randoms from m, which has 31 useable digits */ - m = m >> (31 - 2*VE); - top[0] = m & VM; m = m >> VE; top[1] = m & VM; - m = irandm (c7g); /* positive 32-bit random */ -/* Extract two VE-sized randoms from m, which has 31 useable digits */ - m = m >> (31 - 2*VE); - top[2] = m & VM; m = m >> VE; top[3] = m & VM; - for (i = 0; i < 4; i++) ord[i] = i; -/* Sort in decreasing size */ - for (i = 2; i >= 0; i--) { - for (j = 0; j <= i; j++) { - if (top[j] < top[j+1]) { - k = top[j]; top[j] = top[j+1]; - top[j+1] = k; - k = ord[j]; ord[j] = ord[j+1]; - ord[j+1] = k; - } - } - } -/* Ensure all different */ - for (i = 0; i < 3; i++) { if (top[i] == top[i+1]) goto reran1; } + m = irandm (c7g); /* positive 32-bit random */ + /* Extract two VE-sized randoms from m, which has 31 useable digits */ + m = m >> (31 - 2*VE); + top[0] = m & VM; m = m >> VE; top[1] = m & VM; + m = irandm (c7g); /* positive 32-bit random */ + /* Extract two VE-sized randoms from m, which has 31 useable digits */ + m = m >> (31 - 2*VE); + top[2] = m & VM; m = m >> VE; top[3] = m & VM; + for (i = 0; i < 4; i++) + ord[i] = i; + /* Sort in decreasing size */ + for (i = 2; i >= 0; i--) + for (j = 0; j <= i; j++) + if (top[j] < top[j+1]) { + k = top[j]; top[j] = top[j+1]; + top[j+1] = k; + k = ord[j]; ord[j] = ord[j+1]; + ord[j+1] = k; + } -/* Set pt pointers to their start values for the first chunk. */ - for (i = 0; i < 4; i++) { - j = ord[i]; - ppt[j] = wk2 + j * VL + top[i]; - } + /* Ensure all different */ + for (i = 0; i < 3; i++) + if (top[i] == top[i+1]) + goto reran1; -/* Set ptn to point into wk1 */ - ptn = wk1; + /* Set pt pointers to their start values for the first chunk. */ + for (i = 0; i < 4; i++) { + j = ord[i]; + ppt[j] = wk2 + j * VL + top[i]; + } -/* Now ready to do five chunks. The length of chunk i is - top[i-1] - top[i] (I hope) - At the end of chunk i, pointer ord[i] should have reached the end - of its part, and need to be wrapped down to the start of its part. - */ - i = 0; + /* Set ptn to point into wk1 */ + ptn = wk1; + + /* Now ready to do five chunks. The length of chunk i is + top[i-1] - top[i] (I hope) + At the end of chunk i, pointer ord[i] should have reached the end + of its part, and need to be wrapped down to the start of its part. + */ + i = 0; chunk: - j = top[i] - top[i-1]; /* Minus the chunk length */ - for (; j < 0; j++) { - p = *ptn++; s = *ptn++; q = *ptn++; r = *ptn++; - t = (p + q + r + s) * 0.5; - *ppt[0]++ = t - p; - *ppt[1]++ = t - q; - *ppt[2]++ = r - t; - *ppt[3]++ = s - t; - } -/* This should end the chunk. See if all done */ - if (i == 4) goto passdone; + j = top[i] - top[i-1]; /* Minus the chunk length */ + for (; j < 0; j++) { + p = *ptn++; s = *ptn++; q = *ptn++; r = *ptn++; + t = (p + q + r + s) * 0.5; + *ppt[0]++ = t - p; + *ppt[1]++ = t - q; + *ppt[2]++ = r - t; + *ppt[3]++ = s - t; + } + /* This should end the chunk. See if all done */ + if (i == 4) + goto passdone; -/* The pointer for part ord[i] should have passed its end */ - j = ord[i]; + /* The pointer for part ord[i] should have passed its end */ + j = ord[i]; #ifdef dddd -printf ("Chunk %1d done. Ptr %1d now %4d\n", i, j, ppt[j]-wk2); + printf ("Chunk %1d done. Ptr %1d now %4d\n", i, j, ppt[j]-wk2); #endif - ppt[j] -= VL; - i++; - goto chunk; + ppt[j] -= VL; + i++; + goto chunk; passdone: -/* wk1[] values have been transformed and placed in wk2[] - Transform from wk2 to wk1 with a simple shuffle */ - m = (irandm (c7g) >> (29 - VE)) & WM; - j = 0; - for (i = 0; i < 4; i++) ppt[i] = wk1 + i * VL; - for (i = 0; i < VL; i++) { - p = wk2[j^m]; j++; - s = wk2[j^m]; j++; - q = wk2[j^m]; j++; - r = wk2[j^m]; j++; - t = (p + q + r + s) * 0.5; - *ppt[0]++ = t - p; - *ppt[1]++ = q - t; - *ppt[2]++ = t - r; - *ppt[3]++ = s - t; - } + /* wk1[] values have been transformed and placed in wk2[] + Transform from wk2 to wk1 with a simple shuffle */ + m = (irandm (c7g) >> (29 - VE)) & WM; + j = 0; + for (i = 0; i < 4; i++) + ppt[i] = wk1 + i * VL; + for (i = 0; i < VL; i++) { + p = wk2[j^m]; j++; + s = wk2[j^m]; j++; + q = wk2[j^m]; j++; + r = wk2[j^m]; j++; + t = (p + q + r + s) * 0.5; + *ppt[0]++ = t - p; + *ppt[1]++ = q - t; + *ppt[2]++ = t - r; + *ppt[3]++ = s - t; + } -/* We have a new lot of variates in wk1 */ - return; + /* We have a new lot of variates in wk1 */ + return; } -/* ------------------- renormalize --------------------------- */ -/* Rescales wk1[] so sum of squares = WL */ -/* Returns the original sum-of-squares */ -Sf renormalize (void) -{ - Sf ts, vv; - Sw i; +/* ------------------- renormalize --------------------------- */ +/* Rescales wk1[] so sum of squares = WL */ +/* Returns the original sum-of-squares */ - ts = 0.0; - for (i = 0; i < WL; i++) { - ts += wk1[i] * wk1[i]; - } - vv = sqrt (WL / ts); - for (i = 0; i < WL; i++) wk1[i] *= vv; - return (ts); +Sf +renormalize(void) +{ + Sf ts, vv; + Sw i; + + ts = 0.0; + for (i = 0; i < WL; i++) + ts += wk1[i] * wk1[i]; + + vv = sqrt (WL / ts); + for (i = 0; i < WL; i++) + wk1[i] *= vv; + return (ts); } -/* ------------------------ BoxMuller ---------------------- */ -/* Fills block gvec of length ll with proper normals */ -static void boxmuller (Sf *gvec, Sw ll) -{ - Sw i; - Sf tx, ty, tr, tz; +/* ------------------------ BoxMuller ---------------------- */ +/* Fills block gvec of length ll with proper normals */ -/* Here, replace the whole pool with conventional Normal variates */ - i = 0; +static void +boxmuller(Sf *gvec, Sw ll) +{ + Sw i; + Sf tx, ty, tr, tz; + + /* Here, replace the whole pool with conventional Normal variates */ + i = 0; nextpair: - tx = 2.0 * c7rand(c7g) - 1.0; /* Uniform in -1..1 */ - ty = 2.0 * c7rand(c7g) - 1.0; /* Uniform in -1..1 */ - tr = tx * tx + ty * ty; - if ((tr > 1.0) || (tr < 0.25)) goto nextpair; - tz = -2.0 * log (c7rand(c7g)); /* Sum of squares */ - tz = sqrt ( tz / tr ); - gvec [i++] = tx * tz; gvec [i++] = ty * tz; - if (i < ll) goto nextpair; -/* Horrid, but good enough */ - return; + tx = 2.0 * c7rand(c7g) - 1.0; /* Uniform in -1..1 */ + ty = 2.0 * c7rand(c7g) - 1.0; /* Uniform in -1..1 */ + tr = tx * tx + ty * ty; + if ((tr > 1.0) || (tr < 0.25)) + goto nextpair; + tz = -2.0 * log (c7rand(c7g)); /* Sum of squares */ + tz = sqrt(tz / tr); + gvec [i++] = tx * tz; gvec [i++] = ty * tz; + if (i < ll) + goto nextpair; + /* Horrid, but good enough */ + return; } -/* ------------------------- initnorm ---------------------- */ -/* To initialize, given a seed integer and a quality level. - The seed can be any integer. The quality level quoll should be - between 1 and 4. Quoll = 1 gives high speed, but leaves some - correlation between the 4th moments of successive batches of values. - Higher values of quoll give lower speed but less correlation. +/* ------------------------- initnorm ---------------------- */ +/* To initialize, given a seed integer and a quality level. + The seed can be any integer. The quality level quoll should be + between 1 and 4. Quoll = 1 gives high speed, but leaves some + correlation between the 4th moments of successive batches of values. + Higher values of quoll give lower speed but less correlation. + + If called with quoll = 0, initnorm performs a check that the + most crucial routine (regen) is performing correctly. In this + case, the value of 'iseed' is ignored. Initnorm will report the + results of the test, which compares pool values with check17 and + check98, which are defined below. + When a check call is made, a proper call on initnorm must then + be made before using the FastNorm macro. A check call does not + properly initialize the routines even if it succeeds. +*/ - If called with quoll = 0, initnorm performs a check that the - most crucial routine (regen) is performing correctly. In this - case, the value of 'iseed' is ignored. Initnorm will report the - results of the test, which compares pool values with check17 and - check98, which are defined below. - When a check call is made, a proper call on initnorm must then - be made before using the FastNorm macro. A check call does not - properly initialize the routines even if it succeeds. - */ static Sf check17 = 0.1255789; static Sf check98 = -0.7113293; -void initnorm (Sw seed, Sw quoll) +void +initnorm(Sw seed, Sw quoll) { - Sw i; + Sw i; -/* At one stage, we need to generate a random variable Z such that - (WL * Z*Z) has a Chi-squared-WL density. Now, a var with - an approximate Chi-sq-K distn can be got as - (A + B*n)**2 where n has unit Normal distn, - A**2 = K * sqrt (1 - 1/K), A**2 + B**2 = K. (For large K) - So we form Z as (1/sqrt(WL)) * (A + B*n) - or chic1 + chic2 * n where - chic1 = A / sqrt(WL), chic2 = B / sqrt(WL). - Hence - chic1 = sqrt (A*A / WL) = sqrt ( sqrt (1 - 1/WL)), - chic2 = sqrt (1 - chic1*chic1) - */ + /* At one stage, we need to generate a random variable Z such that + (WL * Z*Z) has a Chi-squared-WL density. Now, a var with + an approximate Chi-sq-K distn can be got as + (A + B*n)**2 where n has unit Normal distn, + A**2 = K * sqrt (1 - 1/K), A**2 + B**2 = K. (For large K) + So we form Z as (1/sqrt(WL)) * (A + B*n) + or chic1 + chic2 * n where + chic1 = A / sqrt(WL), chic2 = B / sqrt(WL). + Hence + chic1 = sqrt(A*A / WL) = sqrt(sqrt(1 - 1/WL)), + chic2 = sqrt(1 - chic1*chic1) + */ - chic1 = sqrt ( sqrt (1.0 - 1.0 / WL)); - chic2 = sqrt (1.0 - chic1 * chic1); + chic1 = sqrt(sqrt(1.0 - 1.0 / WL)); + chic2 = sqrt(1.0 - chic1 * chic1); -/* Set regen counter "gslew" which will affect renormalizations. - Since pools are OK already, we wont't need to renorm for a - while */ - gslew = 1; -/* Finally, set "gaussfaze" to return all of wk1 - * except the last entry at WL-1 */ - gaussfaze = WL-1; - gausssave = wk1; + /* Set regen counter "gslew" which will affect renormalizations. + Since pools are OK already, we wont't need to renorm for a + while */ + gslew = 1; + /* Finally, set "gaussfaze" to return all of wk1 + * except the last entry at WL-1 */ + gaussfaze = WL-1; + gausssave = wk1; -/* If quoll = 0, do a check on installation */ - if (quoll == 0) goto docheck; - qual = quoll; -/* Check sensible values for quoll, say 1 to 4 */ - if ((quoll < 0) || (quoll > 4)) { - printf ("From initnorm(): quoll parameter %d out of\ + /* If quoll = 0, do a check on installation */ + if (quoll == 0) + goto docheck; + qual = quoll; + /* Check sensible values for quoll, say 1 to 4 */ + if ((quoll < 0) || (quoll > 4)) { + printf ("From initnorm(): quoll parameter %d out of\ range 1 to 4\n", quoll); - return; - } - c7g[0] = seed; c7g[1] = -3337792; + return; + } + c7g[0] = seed; c7g[1] = -3337792; -/* Fill wk1[] with good normals */ - boxmuller (wk1, WL); -/* Scale so sum-of-squares = WL */ - GScale = sqrt (renormalize () / WL); -/* We have set - GScale to restore the original ChiSq_WL sum-of-squares */ - return; + /* Fill wk1[] with good normals */ + boxmuller (wk1, WL); + /* Scale so sum-of-squares = WL */ + GScale = sqrt (renormalize () / WL); + /* We have set + GScale to restore the original ChiSq_WL sum-of-squares */ + return; docheck: -/* Set a simple pattern in wk1[] and test results of regen */ - for (i = 0; i < WL; i++) wk1[i] = wk2[i] = 0.0; - wk1[0] = sqrt ((double) WL); - c7g[0] = 1234567; c7g[1] = 9876543; - for (i = 0; i < 60; i++) regen(); -/* Check a couple of values */ - if ((fabs (wk1[17] - check17) > 0.00001) || - (fabs (wk1[98] - check98) > 0.00001)) { - printf ("\nInitnorm check failed.\n"); - printf ("Expected %8.5f got %10.7f\n", check17, wk1[17]); - printf ("Expected %8.5f got %10.7f\n", check98, wk1[98]); - } - else printf ("\nInitnorm check OK\n"); - return; + /* Set a simple pattern in wk1[] and test results of regen */ + for (i = 0; i < WL; i++) + wk1[i] = wk2[i] = 0.0; + wk1[0] = sqrt ((double) WL); + c7g[0] = 1234567; c7g[1] = 9876543; + for (i = 0; i < 60; i++) + regen(); + /* Check a couple of values */ + if ((fabs (wk1[17] - check17) > 0.00001) || + (fabs (wk1[98] - check98) > 0.00001)) + { + printf ("\nInitnorm check failed.\n"); + printf ("Expected %8.5f got %10.7f\n", check17, wk1[17]); + printf ("Expected %8.5f got %10.7f\n", check98, wk1[98]); + } else { + printf ("\nInitnorm check OK\n"); + } + return; } -/* ---------------------- fastnorm -------------------------- */ -/* If gslew shows time is ripe, renormalizes the pool - fastnorm() returns the value GScale*gausssave[0]. - */ +/* ---------------------- fastnorm -------------------------- */ +/* If gslew shows time is ripe, renormalizes the pool + fastnorm() returns the value GScale*gausssave[0]. */ -Sf fastnorm (void) +Sf +fastnorm(void) { - Sf sos; - Sw n1; + Sf sos; + Sw n1; - if (! (gslew & 0xFFFF)) { - sos = renormalize (); - } + if (!(gslew & 0xFFFF)) + sos = renormalize (); -/* The last entry of gausssave, at WL-1, will not have been used. - Use it to get an approx. to sqrt (ChiSq_WL / WL). - See initnorm() code for details */ - GScale = chic1 + chic2 * GScale * gausssave [WL-1]; - for (n1 = 0; n1 < qual; n1++) regen (); - gslew++; + /* The last entry of gausssave, at WL-1, will not have been used. + Use it to get an approx. to sqrt (ChiSq_WL / WL). + See initnorm() code for details */ + GScale = chic1 + chic2 * GScale * gausssave [WL-1]; + for (n1 = 0; n1 < qual; n1++) + regen (); + gslew++; - gaussfaze = WL - 1; + gaussfaze = WL - 1; - return (GScale * gausssave [0]); + return (GScale * gausssave [0]); } -/* --------------------- (test) main ------------------------- */ +/* --------------------- (test) main ------------------------- */ + #ifdef Main #include "ngspice/FastNorm3.h" -int main() + +int +main() { - Sf x; Sw i; - initnorm (0, 0); - initnorm (77, 2); - printf ("SoS %20.6f\n", renormalize()); -// for (i = 0; i < 2000000; i++) x = FastNorm; - for (i = 0; i < 200; i++) { - x = FastNorm; - printf("%d\t%f\n", i, x); - } - printf ("SoS %20.6f\n", renormalize()); - exit (1); + Sf x; Sw i; + initnorm (0, 0); + initnorm (77, 2); + printf ("SoS %20.6f\n", renormalize()); + // for (i = 0; i < 2000000; i++) + // x = FastNorm; + for (i = 0; i < 200; i++) { + x = FastNorm; + printf("%d\t%f\n", i, x); + } + printf ("SoS %20.6f\n", renormalize()); + exit (1); } + #endif diff --git a/src/frontend/trannoise/wallace.c b/src/frontend/trannoise/wallace.c index f1b5f8b50..058b1b763 100644 --- a/src/frontend/trannoise/wallace.c +++ b/src/frontend/trannoise/wallace.c @@ -1,7 +1,6 @@ /* Wallace generator for normally distributed random variates Copyright: Holger Vogt, 2008 - -*/ +*/ //#define FASTNORM_ORIG @@ -52,25 +51,26 @@ extern void TausSeed(void); extern unsigned int CombLCGTausInt2(void); -void PolarGauss(double* py1, double* py2) +void +PolarGauss(double* py1, double* py2) { - double x1, x2, w; + double x1, x2, w; - do { - x1 = drand(); - x2 = drand(); - w = x1 * x1 + x2 * x2; - } while (( w > 1.0 ) || ( w < 0.25)); + do { + x1 = drand(); + x2 = drand(); + w = x1 * x1 + x2 * x2; + } while ((w > 1.0) || (w < 0.25)); - w = sqrt( (-2.0 * log( w ) ) / w ); + w = sqrt((-2.0 * log(w)) / w); - *py1 = (double)(x1 * w); - *py2 = (double)(x2 * w); -} + *py1 = (double)(x1 * w); + *py2 = (double)(x2 * w); +} - -static void destroy_wallace(void) +static void +destroy_wallace(void) { tfree(pool1); tfree(pool2); @@ -79,214 +79,220 @@ static void destroy_wallace(void) } -void initw(void) +void +initw(void) { - unsigned i; - double totsqr, nomsqr; - unsigned long int coa, cob, s; - - /* initialize the uniform generator */ - srand((unsigned int) getpid()); -// srand(17); - TausSeed(); - - ScaleGauss = 1.; - newpools = 1; - - /* set up the two pools */ - pool1 = TMALLOC(double, n); - pool2 = TMALLOC(double, n); - addrif = TMALLOC(unsigned int, (n + NOTRANS)); - addrib = TMALLOC(unsigned int, (n + NOTRANS)); + unsigned i; + double totsqr, nomsqr; + unsigned long int coa, cob, s; - atexit(destroy_wallace); + /* initialize the uniform generator */ + srand((unsigned int) getpid()); + // srand(17); + TausSeed(); - /* fill the first pool with normally distributed values */ - PolarGauss(&pool1[0], &pool1[1]); - for (i = 1; i < n>>1; i++) { - PolarGauss(&pool1[i<<1], &pool1[(i<<1) + 1]); - } - /* normalize pool content */ -/* totsqr = totsum = 0.0; - for (i = 0; i < n; i++) { - totsqr += pool1[i] * pool1[i]; - totsum += pool1[i]; - } - totsum = totsum/n; - for (i = 0; i < n; i++) { - totsqr += (pool1[i] - totsum) * (pool1[i] - totsum); - } - nomsqr = sqrt(n / totsqr); - for (i = 0; i < n; i++) - pool1[i] = (pool1[i] - totsum) * nomsqr; -*/ - totsqr = 0.0; - for (i = 0; i < n; i++) - totsqr += pool1[i] * pool1[i]; - nomsqr = sqrt(n / totsqr); - for (i = 0; i < n; i++) - pool1[i] *= nomsqr; - - /* calculate ch^2 value */ - chi1 = sqrt ( sqrt (1.0 - 1.0/n)); - chi2 = sqrt ( 1.0 - chi1*chi1); - - /* first scaling, based on unused pool1[n-2] */ - ScaleGauss = chi1 + chi2 * ScaleGauss * pool1[n-2]; - /* access to first pool */ - outgauss = pool1; - /* set data counter, we return n-2 values here */ - variate_used = n - 2; + ScaleGauss = 1.; + newpools = 1; - /* generate random reading addresses using a LCG */ - s = 0; - coa = 241; - cob = 59; - for (i=0; i < (n + NOTRANS); i++) { -// addrif[i] = s = (s * coa + cob) % ( n ); - coa = CombLCGTausInt(); - addrif[i] = coa >> (32 - LPOOLSIZE); -// printf ("Random add:\t%ld\n" , s); - } - s = 0; - coa = 193; - cob = 15; - for (i=0; i < (n + NOTRANS); i++) { -// addrib[i] = s = (s * coa + cob) % ( n ); - coa = CombLCGTausInt(); - addrib[i] = coa >> (32 - LPOOLSIZE); -// printf ("Random add:\t%ld\n" , addrib[i]); - } - -// printf("norm for orig. Gauss: %e, chi^2 scale: %e\n", nomsqr, ScaleGauss); -// NewWa(); + /* set up the two pools */ + pool1 = TMALLOC(double, n); + pool2 = TMALLOC(double, n); + addrif = TMALLOC(unsigned int, (n + NOTRANS)); + addrib = TMALLOC(unsigned int, (n + NOTRANS)); + + atexit(destroy_wallace); + + /* fill the first pool with normally distributed values */ + PolarGauss(&pool1[0], &pool1[1]); + for (i = 1; i < n>>1; i++) + PolarGauss(&pool1[i<<1], &pool1[(i<<1) + 1]); + + /* normalize pool content */ + /* totsqr = totsum = 0.0; + * for (i = 0; i < n; i++) { + * totsqr += pool1[i] * pool1[i]; + * totsum += pool1[i]; + * } + * totsum = totsum/n; + * for (i = 0; i < n; i++) { + * totsqr += (pool1[i] - totsum) * (pool1[i] - totsum); + * } + * nomsqr = sqrt(n / totsqr); + * for (i = 0; i < n; i++) + * pool1[i] = (pool1[i] - totsum) * nomsqr; + */ + totsqr = 0.0; + for (i = 0; i < n; i++) + totsqr += pool1[i] * pool1[i]; + nomsqr = sqrt(n / totsqr); + for (i = 0; i < n; i++) + pool1[i] *= nomsqr; + + /* calculate ch^2 value */ + chi1 = sqrt(sqrt(1.0 - 1.0/n)); + chi2 = sqrt(1.0 - chi1*chi1); + + /* first scaling, based on unused pool1[n-2] */ + ScaleGauss = chi1 + chi2 * ScaleGauss * pool1[n-2]; + /* access to first pool */ + outgauss = pool1; + /* set data counter, we return n-2 values here */ + variate_used = n - 2; + + /* generate random reading addresses using a LCG */ + s = 0; + coa = 241; + cob = 59; + for (i = 0; i < (n + NOTRANS); i++) { + // addrif[i] = s = (s * coa + cob) % (n); + coa = CombLCGTausInt(); + addrif[i] = coa >> (32 - LPOOLSIZE); + // printf ("Random add:\t%ld\n" , s); + } + s = 0; + coa = 193; + cob = 15; + for (i = 0; i < (n + NOTRANS); i++) { + // addrib[i] = s = (s * coa + cob) % (n); + coa = CombLCGTausInt(); + addrib[i] = coa >> (32 - LPOOLSIZE); + // printf ("Random add:\t%ld\n" , addrib[i]); + } + + // printf("norm for orig. Gauss: %e, chi^2 scale: %e\n", nomsqr, ScaleGauss); + // NewWa(); } + /* original FastNorm3.c code */ #ifdef FASTNORM_ORIG -float NewWa () +float +NewWa() { - int i, j, k, m; - float p, q, r, s, t; - int topv[6], ord[4], *top; - float *ppt[4], *ptn; + int i, j, k, m; + float p, q, r, s, t; + int topv[6], ord[4], *top; + float *ppt[4], *ptn; - float nulval, endval; - float totsqr, nomsqr; - nulval = ScaleGauss * pool1[0]; - endval = pool1[n-1]; + float nulval, endval; + float totsqr, nomsqr; + nulval = ScaleGauss * pool1[0]; + endval = pool1[n-1]; -/* Choose 4 random start points in the wk1[] vector - I want them all different. */ + /* Choose 4 random start points in the wk1[] vector + I want them all different. */ - top = topv + 1; -/* Set limiting values in top[-1], top[4] */ - top[-1] = VL; top[4] = 0; + top = topv + 1; + /* Set limiting values in top[-1], top[4] */ + top[-1] = VL; top[4] = 0; reran1: - m = CombLCGTausInt(); /* positive 32-bit random */ -/* Extract two VE-sized randoms from m, which has 31 useable digits */ - m = m >> (31 - 2*VE); - top[0] = m & VM; m = m >> VE; top[1] = m & VM; - m = CombLCGTausInt(); /* positive 32-bit random */ -/* Extract two VE-sized randoms from m, which has 31 useable digits */ - m = m >> (31 - 2*VE); - top[2] = m & VM; m = m >> VE; top[3] = m & VM; - for (i = 0; i < 4; i++) ord[i] = i; -/* Sort in decreasing size */ - for (i = 2; i >= 0; i--) { - for (j = 0; j <= i; j++) { - if (top[j] < top[j+1]) { - k = top[j]; top[j] = top[j+1]; - top[j+1] = k; - k = ord[j]; ord[j] = ord[j+1]; - ord[j+1] = k; - } - } - } -/* Ensure all different */ - for (i = 0; i < 3; i++) { if (top[i] == top[i+1]) goto reran1; } + m = CombLCGTausInt(); /* positive 32-bit random */ + /* Extract two VE-sized randoms from m, which has 31 useable digits */ + m = m >> (31 - 2*VE); + top[0] = m & VM; m = m >> VE; top[1] = m & VM; + m = CombLCGTausInt(); /* positive 32-bit random */ + /* Extract two VE-sized randoms from m, which has 31 useable digits */ + m = m >> (31 - 2*VE); + top[2] = m & VM; m = m >> VE; top[3] = m & VM; + for (i = 0; i < 4; i++) + ord[i] = i; + /* Sort in decreasing size */ + for (i = 2; i >= 0; i--) + for (j = 0; j <= i; j++) + if (top[j] < top[j+1]) { + k = top[j]; top[j] = top[j+1]; + top[j+1] = k; + k = ord[j]; ord[j] = ord[j+1]; + ord[j+1] = k; + } -/* Set pt pointers to their start values for the first chunk. */ - for (i = 0; i < 4; i++) { - j = ord[i]; - ppt[j] = pool2 + j * VL + top[i]; - } + /* Ensure all different */ + for (i = 0; i < 3; i++) + if (top[i] == top[i+1]) + goto reran1; -/* Set ptn to point into wk1 */ - ptn = pool1; + /* Set pt pointers to their start values for the first chunk. */ + for (i = 0; i < 4; i++) { + j = ord[i]; + ppt[j] = pool2 + j * VL + top[i]; + } -/* Now ready to do five chunks. The length of chunk i is - top[i-1] - top[i] (I hope) - At the end of chunk i, pointer ord[i] should have reached the end - of its part, and need to be wrapped down to the start of its part. - */ - i = 0; + /* Set ptn to point into wk1 */ + ptn = pool1; + + /* Now ready to do five chunks. The length of chunk i is + top[i-1] - top[i] (I hope) + At the end of chunk i, pointer ord[i] should have reached the end + of its part, and need to be wrapped down to the start of its part. + */ + i = 0; chunk: - j = top[i] - top[i-1]; /* Minus the chunk length */ - for (; j < 0; j++) { - p = *ptn++; s = *ptn++; q = *ptn++; r = *ptn++; - t = (p + q + r + s) * 0.5; - *ppt[0]++ = t - p; - *ppt[1]++ = t - q; - *ppt[2]++ = r - t; - *ppt[3]++ = s - t; - } -/* This should end the chunk. See if all done */ - if (i == 4) goto passdone; + j = top[i] - top[i-1]; /* Minus the chunk length */ + for (; j < 0; j++) { + p = *ptn++; s = *ptn++; q = *ptn++; r = *ptn++; + t = (p + q + r + s) * 0.5; + *ppt[0]++ = t - p; + *ppt[1]++ = t - q; + *ppt[2]++ = r - t; + *ppt[3]++ = s - t; + } + /* This should end the chunk. See if all done */ + if (i == 4) + goto passdone; -/* The pointer for part ord[i] should have passed its end */ - j = ord[i]; + /* The pointer for part ord[i] should have passed its end */ + j = ord[i]; #ifdef dddd -printf ("Chunk %1d done. Ptr %1d now %4d\n", i, j, ppt[j]-pool2); + printf ("Chunk %1d done. Ptr %1d now %4d\n", i, j, ppt[j]-pool2); #endif - ppt[j] -= VL; - i++; - goto chunk; + ppt[j] -= VL; + i++; + goto chunk; passdone: -/* wk1[] values have been transformed and placed in wk2[] - Transform from wk2 to wk1 with a simple shuffle */ - m = (CombLCGTausInt2() >> (29 - VE)) & WM; - j = 0; - for (i = 0; i < 4; i++) ppt[i] = pool1 + i * VL; - for (i = 0; i < VL; i++) { - p = pool2[j^m]; j++; - s = pool2[j^m]; j++; - q = pool2[j^m]; j++; - r = pool2[j^m]; j++; - t = (p + q + r + s) * 0.5; - *ppt[0]++ = t - p; - *ppt[1]++ = q - t; - *ppt[2]++ = t - r; - *ppt[3]++ = s - t; - } + /* wk1[] values have been transformed and placed in wk2[] + Transform from wk2 to wk1 with a simple shuffle */ + m = (CombLCGTausInt2() >> (29 - VE)) & WM; + j = 0; + for (i = 0; i < 4; i++) + ppt[i] = pool1 + i * VL; + for (i = 0; i < VL; i++) { + p = pool2[j^m]; j++; + s = pool2[j^m]; j++; + q = pool2[j^m]; j++; + r = pool2[j^m]; j++; + t = (p + q + r + s) * 0.5; + *ppt[0]++ = t - p; + *ppt[1]++ = q - t; + *ppt[2]++ = t - r; + *ppt[3]++ = s - t; + } - /* renormalize again if number of pools beyond limit */ - if (!(newpools & 0xFFFF)) { - totsqr = 0.0; - for (i = 0; i < n; i++) - totsqr += pool1[i] * pool1[i]; - nomsqr = sqrt(n / totsqr); - for (i = 0; i < n; i++) - pool1[i] *= nomsqr; - } + /* renormalize again if number of pools beyond limit */ + if (!(newpools & 0xFFFF)) { + totsqr = 0.0; + for (i = 0; i < n; i++) + totsqr += pool1[i] * pool1[i]; + nomsqr = sqrt(n / totsqr); + for (i = 0; i < n; i++) + pool1[i] *= nomsqr; + } - outgauss = pool1; - /* reset data counter */ - variate_used = n - 1; - - /* set counter counting nomber of pools made */ - newpools++; - - /* new scale factor using ch^2 correction, - using pool1[n-1] from last pool */ - ScaleGauss = chi1 + chi2 * ScaleGauss * endval; + outgauss = pool1; + /* reset data counter */ + variate_used = n - 1; -// printf("Pool number: %d, chi^2 scale: %e\n", newpools, ScaleGauss); - - return nulval; /* use old scale */ + /* set counter counting nomber of pools made */ + newpools++; + /* new scale factor using ch^2 correction, + using pool1[n-1] from last pool */ + ScaleGauss = chi1 + chi2 * ScaleGauss * endval; + + // printf("Pool number: %d, chi^2 scale: %e\n", newpools, ScaleGauss); + + return nulval; /* use old scale */ } #else @@ -296,246 +302,248 @@ passdone: ACM Transactions on Mathmatical Software, Vol. 22, No. 1, March 1996, pp. 119-127. Transform pool1 to pool2 and back to pool1 NOTRANS times by orthogonal 4 x 4 Hadamard-Matrix. - Mixing of values is very important: Any value in the pool should contribute to + Mixing of values is very important: Any value in the pool should contribute to every value in the new pools, at least after several passes (number of passes is set by NOTRANS to 2 or 3). 4 values are read in a continuous sequence from the total of POOLSIZE values. Values are stored in steps modulo POOLSIZE/4. During backward transformation the values are shuffled by a random number jj. */ - -double NewWa(void) + +double +NewWa(void) { - double nulval, endval; - double bl1, bl2, bl3, bl4; /* the four values to be transformed */ - double bsum; - double totsqr, nomsqr; - unsigned int i, j, jj, m, mm, mmm; - - nulval = ScaleGauss * pool1[0]; - endval = pool1[n-1]; - m = n >> 2; -// printf("New pool after next value\n"); - - /* generate new pool by transformation - Transformation is repeated NOTRANS times */ - for (i=0; i < NOTRANS; i++) { - mm = m << 1; - mmm = mm + m; - /* forward transformation */ -// for (j=0; j < n; j += 4) { - for (j=0; j < m; j++) { - bl1 = pool1[j]; - bl2 = pool1[j+m]; - bl3 = pool1[j+mm]; - bl4 = pool1[j+mmm]; - /* Hadamard-Matrix */ - bsum = (bl1 + bl2 + bl3 + bl4) * 0.5f; - jj = j<<2; - pool2[jj] = bl1 - bsum; - pool2[jj+1] = bl2 - bsum; - pool2[jj+2] = bsum - bl3; - pool2[jj+3] = bsum - bl4; - } - /* backward transformation */ - jj = (CombLCGTausInt2() >> (31 - LPOOLSIZE)) & (n - 1); - for (j=0; j < m; j++) { - bl1 = pool2[j^jj]; - bl2 = pool2[(j+m)^jj]; - bl3 = pool2[(j+mm)^jj]; - bl4 = pool2[(j+mmm)^jj]; - /* Hadamard-Matrix */ - bsum = (bl1 + bl2 + bl3 + bl4) * 0.5f; - jj = j<<2; - pool1[jj] = bl1 - bsum; - pool1[jj+1] = bl2 - bsum; - pool1[jj+2] = bsum - bl3; - pool1[jj+3] = bsum - bl4; - } - } - - /* renormalize again if number of pools beyond limit */ - if (!(newpools & 0xFFFF)) { - totsqr = 0.0; - for (i = 0; i < n; i++) - totsqr += pool1[i] * pool1[i]; - nomsqr = sqrt(n / totsqr); - for (i = 0; i < n; i++) - pool1[i] *= nomsqr; - } + double nulval, endval; + double bl1, bl2, bl3, bl4; /* the four values to be transformed */ + double bsum; + double totsqr, nomsqr; + unsigned int i, j, jj, m, mm, mmm; - outgauss = pool1; - /* reset data counter */ - variate_used = n - 1; - - /* set counter counting nomber of pools made */ - newpools++; - - /* new scale factor using ch^2 correction, - using pool1[n-1] from previous pool */ - ScaleGauss = chi1 + chi2 * ScaleGauss * endval; + nulval = ScaleGauss * pool1[0]; + endval = pool1[n-1]; + m = n >> 2; + // printf("New pool after next value\n"); -// printf("Pool number: %d, chi^2 scale: %e\n", newpools, ScaleGauss); - - return nulval; /* use old scale */ -// return pool1[0]; /* use new scale */ + /* generate new pool by transformation + Transformation is repeated NOTRANS times */ + for (i = 0; i < NOTRANS; i++) { + mm = m << 1; + mmm = mm + m; + /* forward transformation */ + // for (j = 0; j < n; j += 4) { + for (j = 0; j < m; j++) { + bl1 = pool1[j]; + bl2 = pool1[j+m]; + bl3 = pool1[j+mm]; + bl4 = pool1[j+mmm]; + /* Hadamard-Matrix */ + bsum = (bl1 + bl2 + bl3 + bl4) * 0.5f; + jj = j<<2; + pool2[jj] = bl1 - bsum; + pool2[jj+1] = bl2 - bsum; + pool2[jj+2] = bsum - bl3; + pool2[jj+3] = bsum - bl4; + } + /* backward transformation */ + jj = (CombLCGTausInt2() >> (31 - LPOOLSIZE)) & (n - 1); + for (j = 0; j < m; j++) { + bl1 = pool2[j^jj]; + bl2 = pool2[(j+m)^jj]; + bl3 = pool2[(j+mm)^jj]; + bl4 = pool2[(j+mmm)^jj]; + /* Hadamard-Matrix */ + bsum = (bl1 + bl2 + bl3 + bl4) * 0.5f; + jj = j<<2; + pool1[jj] = bl1 - bsum; + pool1[jj+1] = bl2 - bsum; + pool1[jj+2] = bsum - bl3; + pool1[jj+3] = bsum - bl4; + } + } + + /* renormalize again if number of pools beyond limit */ + if (!(newpools & 0xFFFF)) { + totsqr = 0.0; + for (i = 0; i < n; i++) + totsqr += pool1[i] * pool1[i]; + nomsqr = sqrt(n / totsqr); + for (i = 0; i < n; i++) + pool1[i] *= nomsqr; + } + + outgauss = pool1; + /* reset data counter */ + variate_used = n - 1; + + /* set counter counting nomber of pools made */ + newpools++; + + /* new scale factor using ch^2 correction, + using pool1[n-1] from previous pool */ + ScaleGauss = chi1 + chi2 * ScaleGauss * endval; + + // printf("Pool number: %d, chi^2 scale: %e\n", newpools, ScaleGauss); + + return nulval; /* use old scale */ + // return pool1[0]; /* use new scale */ } #endif #ifdef FASTNORMTEST -float NewWa_not(void) +float +NewWa_not(void) { - float nulval, endval; - float bl1, bl2, bl3, bl4; /* the four values to be transformed */ - float bsum; - float totsqr, nomsqr; - unsigned int i, j, jj; - nulval = ScaleGauss * pool1[0]; - endval = pool1[n-1]; - -// printf("New pool after next value\n"); - - /* generate new pool by transformation - Transformation is repeated NOTRANS times */ - for (i=0; i < NOTRANS; i++) { - - /* forward transformation */ - for (j=0; j < n; j += 4) { - jj = j + i; - bl1 = pool1[addrif[jj]]; - bl2 = pool1[addrif[jj+1]]; - bl3 = pool1[addrif[jj+2]]; - bl4 = pool1[addrif[jj+3]]; -/* s = (s*coa + cob) & (n - 1); - bl1 = pool1[s]; - s = (s*coa + cob) & (n - 1); - bl2 = pool1[s + 1]; - s = (s*coa + cob) & (n - 1); - bl3 = pool1[s + 2]; - s = (s*coa + cob) & (n - 1); - bl4 = pool1[s + 3]; */ -/* jj = j + i; - bl1 = pool1[addrif[jj]]; - bl2 = pool1[addrif[jj+1]]; - bl3 = pool1[addrif[jj+2]]; - bl4 = pool1[addrif[jj+3]]; */ -/* bl1 = pool1[j]; - bl2 = pool1[j+1]; - bl3 = pool1[j+2]; - bl4 = pool1[j+3]; */ - /* Hadamard-Matrix */ - bsum = (bl1 + bl2 + bl3 + bl4) * 0.5; -/* pool2[j] = bl1 - bsum; - pool2[j+1] = bl2 - bsum; - pool2[j+2] = bsum - bl3; - pool2[j+3] = bsum - bl4; */ - pool2[addrib[jj]] = bl1 - bsum; - pool2[addrib[jj+1]] = bl2 - bsum; - pool2[addrib[jj+2]] = bsum - bl3; - pool2[addrib[jj+3]] = bsum - bl4; - } - /* backward transformation */ - for (j=0; j < n; j += 4) { - bl1 = pool2[j]; - bl2 = pool2[j+1]; - bl3 = pool2[j+2]; - bl4 = pool2[j+3]; -/* bl1 = pool2[addrib[j]]; - bl2 = pool2[addrib[j+1]]; - bl3 = pool2[addrib[j+2]]; - bl4 = pool2[addrib[j+3]]; */ - /* Hadamard-Matrix */ - bsum = (bl1 + bl2 + bl3 + bl4) * 0.5; - pool1[j] = bl1 - bsum; - pool1[j+1] = bl2 - bsum; - pool1[j+2] = bsum - bl3; - pool1[j+3] = bsum - bl4; - } - } + float nulval, endval; + float bl1, bl2, bl3, bl4; /* the four values to be transformed */ + float bsum; + float totsqr, nomsqr; + unsigned int i, j, jj; + nulval = ScaleGauss * pool1[0]; + endval = pool1[n-1]; - - /* renormalize again if number of pools beyond limit */ - if (!(newpools & 0xFFFF)) { - totsqr = 0.0; - for (i = 0; i < n; i++) - totsqr += pool1[i] * pool1[i]; - nomsqr = sqrt(n / totsqr); - for (i = 0; i < n; i++) - pool1[i] *= nomsqr; - } + // printf("New pool after next value\n"); - outgauss = pool1; - /* reset data counter */ - variate_used = n - 1; - - /* set counter counting nomber of pools made */ - newpools++; - - /* new scale factor using ch^2 correction, - using pool1[n-1] from last pool */ - ScaleGauss = chi1 + chi2 * ScaleGauss * endval; + /* generate new pool by transformation + Transformation is repeated NOTRANS times */ + for (i = 0; i < NOTRANS; i++) { -// printf("Pool number: %d, chi^2 scale: %e\n", newpools, ScaleGauss); - - return nulval; /* use old scale */ -// return pool1[0]; /* use new scale */ + /* forward transformation */ + for (j = 0; j < n; j += 4) { + jj = j + i; + bl1 = pool1[addrif[jj]]; + bl2 = pool1[addrif[jj+1]]; + bl3 = pool1[addrif[jj+2]]; + bl4 = pool1[addrif[jj+3]]; + /* s = (s*coa + cob) & (n - 1); + bl1 = pool1[s]; + s = (s*coa + cob) & (n - 1); + bl2 = pool1[s + 1]; + s = (s*coa + cob) & (n - 1); + bl3 = pool1[s + 2]; + s = (s*coa + cob) & (n - 1); + bl4 = pool1[s + 3]; */ + /* jj = j + i; + bl1 = pool1[addrif[jj]]; + bl2 = pool1[addrif[jj+1]]; + bl3 = pool1[addrif[jj+2]]; + bl4 = pool1[addrif[jj+3]]; */ + /* bl1 = pool1[j]; + bl2 = pool1[j+1]; + bl3 = pool1[j+2]; + bl4 = pool1[j+3]; */ + /* Hadamard-Matrix */ + bsum = (bl1 + bl2 + bl3 + bl4) * 0.5; + /* pool2[j] = bl1 - bsum; + pool2[j+1] = bl2 - bsum; + pool2[j+2] = bsum - bl3; + pool2[j+3] = bsum - bl4; */ + pool2[addrib[jj]] = bl1 - bsum; + pool2[addrib[jj+1]] = bl2 - bsum; + pool2[addrib[jj+2]] = bsum - bl3; + pool2[addrib[jj+3]] = bsum - bl4; + } + /* backward transformation */ + for (j = 0; j < n; j += 4) { + bl1 = pool2[j]; + bl2 = pool2[j+1]; + bl3 = pool2[j+2]; + bl4 = pool2[j+3]; + /* bl1 = pool2[addrib[j]]; + bl2 = pool2[addrib[j+1]]; + bl3 = pool2[addrib[j+2]]; + bl4 = pool2[addrib[j+3]]; */ + /* Hadamard-Matrix */ + bsum = (bl1 + bl2 + bl3 + bl4) * 0.5; + pool1[j] = bl1 - bsum; + pool1[j+1] = bl2 - bsum; + pool1[j+2] = bsum - bl3; + pool1[j+3] = bsum - bl4; + } + } + + /* renormalize again if number of pools beyond limit */ + if (!(newpools & 0xFFFF)) { + totsqr = 0.0; + for (i = 0; i < n; i++) + totsqr += pool1[i] * pool1[i]; + nomsqr = sqrt(n / totsqr); + for (i = 0; i < n; i++) + pool1[i] *= nomsqr; + } + + outgauss = pool1; + /* reset data counter */ + variate_used = n - 1; + + /* set counter counting nomber of pools made */ + newpools++; + + /* new scale factor using ch^2 correction, + using pool1[n-1] from last pool */ + ScaleGauss = chi1 + chi2 * ScaleGauss * endval; + + // printf("Pool number: %d, chi^2 scale: %e\n", newpools, ScaleGauss); + + return nulval; /* use old scale */ + // return pool1[0]; /* use new scale */ } #endif -/* --------------------- (test) main ------------------------- */ +/* --------------------- (test) main ------------------------- */ /* gcc -Wall -g -DHasMain -I../../include wallace.c CombTaus.o -o watest.exe */ #ifdef HasMain #include "ngspice/wallace.h" -struct timeb timenow; -struct timeb timebegin; +struct timeb timenow; +struct timeb timebegin; int sec, msec; - -void timediff(struct timeb *now, struct timeb *begin, int *sec, int *msec) + +void +timediff(struct timeb *now, struct timeb *begin, int *sec, int *msec) { *msec = now->millitm - begin->millitm; *sec = now->time - begin->time; if (*msec < 0) { - *msec += 1000; - (*sec)--; + *msec += 1000; + (*sec)--; } return; - } -int main() +int +main() { - float x; - unsigned int i; - long int count; - - initw(); - ftime(&timebegin); - count = 100000000; - for (i = 0; i < count; i++) { - x = GaussWa; -// printf("%d\t%f\n", i, x); - } - ftime(&timenow); - timediff(&timenow, &timebegin, &sec, &msec); - printf("WallaceHV: %ld normal variates: %f s\n", count, sec + (float) msec / 1000.0); + float x; + unsigned int i; + long int count; - initnorm(0, 0); - initnorm(77, 3); - ftime(&timebegin); - count = 100000000; - for (i = 0; i < count; i++) { - x = FastNorm; -// printf("%d\t%f\n", i, x); - } - ftime(&timenow); - timediff(&timenow, &timebegin, &sec, &msec); - printf("FastNorm3: %ld normal variates: %f s\n", count, sec + (float) msec / 1000.0); - - return (1); + initw(); + ftime(&timebegin); + count = 100000000; + for (i = 0; i < count; i++) { + x = GaussWa; + // printf("%d\t%f\n", i, x); + } + ftime(&timenow); + timediff(&timenow, &timebegin, &sec, &msec); + printf("WallaceHV: %ld normal variates: %f s\n", count, sec + (float) msec / 1000.0); + + initnorm(0, 0); + initnorm(77, 3); + ftime(&timebegin); + count = 100000000; + for (i = 0; i < count; i++) { + x = FastNorm; + // printf("%d\t%f\n", i, x); + } + ftime(&timenow); + timediff(&timenow, &timebegin, &sec, &msec); + printf("FastNorm3: %ld normal variates: %f s\n", count, sec + (float) msec / 1000.0); + + return (1); } #endif diff --git a/src/frontend/typesdef.c b/src/frontend/typesdef.c index 5f06a510e..e617f9725 100644 --- a/src/frontend/typesdef.c +++ b/src/frontend/typesdef.c @@ -43,15 +43,15 @@ struct type types[NUMTYPES] = { { "pole", NULL } , { "zero", NULL } , { "s-param", NULL } , - { "temp-sweep", "Celsius" } ,/* Added by HT */ - { "res-sweep", "Ohms" } , /* Added by HT */ - { "impedance", "Ohms" } , /* Added by A.Roldan */ - { "admittance", "Mhos" } , /* Added by A.Roldan */ - { "power", "W" } , /* Added by A.Roldan */ - { "phase", "Degree" } , /* Added by A.Roldan */ - { "decibel", "dB" } , /* Added by A.Roldan */ + { "temp-sweep", "Celsius" } , /* Added by HT */ + { "res-sweep", "Ohms" } , /* Added by HT */ + { "impedance", "Ohms" } , /* Added by A.Roldan */ + { "admittance", "Mhos" } , /* Added by A.Roldan */ + { "power", "W" } , /* Added by A.Roldan */ + { "phase", "Degree" } , /* Added by A.Roldan */ + { "decibel", "dB" } , /* Added by A.Roldan */ -} ; +}; /* The stuff for plot names. */ @@ -77,11 +77,12 @@ struct plotab plotabs[NUMPLOTTYPES] = { { "sp", "sp" } , { "harm", "harm" }, { "spect", "spect" }, -} ; +}; -int notypes = 19 ; +int notypes = 19; int noplotabs = 21; + /* A command to define types for vectors and plots. This will generally * be used in the Command: field of the rawfile. * The syntax is "deftype v typename abbrev", where abbrev will be used to @@ -98,8 +99,8 @@ com_dftype(wordlist *wl) int i; switch (*wl->wl_word) { - case 'v': - case 'V': + case 'v': + case 'V': wl = wl->wl_next; name = copy(wl->wl_word); wl = wl->wl_next; @@ -118,8 +119,8 @@ com_dftype(wordlist *wl) notypes++; break; - case 'p': - case 'P': + case 'p': + case 'P': wl = wl->wl_next; name = copy(wl->wl_word); wl = wl->wl_next; @@ -143,13 +144,15 @@ com_dftype(wordlist *wl) } break; - default: + default: fprintf(cp_err, "Error: missing 'p' or 'v' argument\n"); break; } + return; } + /* Return the abbreviation associated with a number. */ char * @@ -161,6 +164,7 @@ ft_typabbrev(int typenum) return (NULL); } + /* Return the typename associated with a number. */ char * @@ -172,6 +176,7 @@ ft_typenames(int typenum) return (NULL); } + /* Return the type number associated with the name. */ int @@ -181,12 +186,15 @@ ft_typnum(char *name) if (eq(name, "none")) name = "notype"; + for (i = 0; (i < NUMTYPES) && types[i].t_name; i++) if (cieq(name, types[i].t_name)) return (i); + return (0); } + /* For plots... */ char * @@ -209,6 +217,7 @@ ft_plotabbrev(char *string) return (NULL); } + /* Change the type of a vector. */ void @@ -219,24 +228,24 @@ com_stype(wordlist *wl) struct dvec *v, *vv; char *s; - for (tt = 0; ; tt++) { + for (tt = 0; ; tt++) if ((s = ft_typenames(tt)) == NULL || eq(type, s)) break; - } + if (!s) { fprintf(cp_err, "Error: no such type as '%s'\n", type); return; } + for (wl = wl->wl_next; wl; wl = wl->wl_next) { v = vec_get(wl->wl_word); if (!v) - fprintf(cp_err, "Error: no such vector %s.\n", - wl->wl_word); - else + fprintf(cp_err, "Error: no such vector %s.\n", wl->wl_word); + else for (vv = v; vv; vv = vv->v_link2) if (vv->v_flags & VF_PERMANENT) vv->v_type = tt; } + return; } - diff --git a/src/frontend/variable.c b/src/frontend/variable.c index 1882e479c..2e577c7d9 100644 --- a/src/frontend/variable.c +++ b/src/frontend/variable.c @@ -41,7 +41,7 @@ cp_varwl(struct variable *var) char buf[BSIZE_SP], *copystring; struct variable *vt; - switch(var->va_type) { + switch (var->va_type) { case CP_BOOL: /* Can't ever be FALSE. */ sprintf(buf, "%s", var->va_bool ? "TRUE" : "FALSE"); @@ -62,9 +62,9 @@ cp_varwl(struct variable *var) case CP_LIST: /* The tricky case. */ for (vt = var->va_vlist; vt; vt = vt->va_next) { w = cp_varwl(vt); - if (wl == NULL) + if (wl == NULL) { wl = wx = w; - else { + } else { wx->wl_next = w; w->wl_prev = wx; wx = w; @@ -106,9 +106,9 @@ cp_vset(char *varname, enum cp_types type, void *value) } if (alreadythere) { - if(v->va_type == CP_LIST) + if (v->va_type == CP_LIST) free_struct_variable(v->va_vlist); - if(v->va_type == CP_STRING) + if (v->va_type == CP_STRING) tfree(v->va_string); } @@ -123,14 +123,15 @@ cp_vset(char *varname, enum cp_types type, void *value) case CP_BOOL: if (* ((bool *) value) == FALSE) { cp_remvar(copyvarname); - if(v_free) { + if (v_free) { tfree(v->va_name); tfree(v); } tfree(copyvarname); return; - } else + } else { v->va_bool = TRUE; + } break; case CP_NUM: @@ -200,7 +201,7 @@ cp_vset(char *varname, enum cp_types type, void *value) case US_DONTRECORD: /* Do nothing... */ if (alreadythere) { - fprintf(cp_err, "cp_vset: Internal Error: " + fprintf(cp_err, "cp_vset: Internal Error: " "%s already there, but 'dont record'\n", v->va_name); } break; @@ -208,7 +209,7 @@ cp_vset(char *varname, enum cp_types type, void *value) case US_READONLY: fprintf(cp_err, "Error: %s is a read-only variable.\n", v->va_name); if (alreadythere) - fprintf(cp_err, "cp_vset: Internal Error: " + fprintf(cp_err, "cp_vset: Internal Error: " "it was already there too!!\n"); break; @@ -283,7 +284,7 @@ cp_setparse(wordlist *wl) while (wl) { - if(name) + if (name) tfree(name); name = cp_unquote(wl->wl_word); @@ -363,8 +364,9 @@ cp_setparse(wordlist *wl) if (listv) { lv->va_next = vv; lv = vv; - } else + } else { listv = lv = vv; + } wl = wl->wl_next; } if (balance && !wl) { @@ -402,7 +404,7 @@ cp_setparse(wordlist *wl) tfree(name); /* va: cp_unquote memory leak: free name for every loop */ } - if(name) + if (name) tfree(name); return (vars); } @@ -412,11 +414,11 @@ cp_setparse(wordlist *wl) void free_struct_variable(struct variable *v) { - while(v) { + while (v) { struct variable *next_v = v->va_next; - if(v->va_type == CP_LIST) + if (v->va_type == CP_LIST) free_struct_variable(v->va_vlist); - if(v->va_type == CP_STRING) + if (v->va_type == CP_STRING) tfree(v->va_string); tfree(v); v = next_v; @@ -562,7 +564,7 @@ cp_getvar(char *name, enum cp_types type, void *retval) #ifdef TRACE /* SDB debug statement */ - fprintf(stderr,"in cp_getvar, trying to get value of variable %s.\n", name); + fprintf(stderr, "in cp_getvar, trying to get value of variable %s.\n", name); #endif for (v = variables; v && !eq(name, v->va_name); v = v->va_next) @@ -584,7 +586,7 @@ cp_getvar(char *name, enum cp_types type, void *retval) if (v->va_type == type) { switch (type) { case CP_BOOL: - if(retval) + if (retval) * (bool *) retval = TRUE; break; case CP_NUM: { @@ -619,7 +621,7 @@ cp_getvar(char *name, enum cp_types type, void *retval) break; } free_struct_variable(uv1); -// tfree(uv2); + // tfree(uv2); return (TRUE); } else { diff --git a/src/frontend/variable.h b/src/frontend/variable.h index 14b3b2bed..27e80d5c8 100644 --- a/src/frontend/variable.h +++ b/src/frontend/variable.h @@ -21,7 +21,7 @@ struct variable { struct variable *vV_list; } va_V; struct variable *va_next; /* Link. */ -} ; +}; #define va_bool va_V.vV_bool #define va_num va_V.vV_num @@ -32,15 +32,15 @@ struct variable { struct xxx { struct variable *x_v; char x_char; -} ; +}; extern struct variable *variables; extern bool cp_echo; /* extern struct variable *variables; */ -wordlist * cp_varwl(struct variable *var); -wordlist * cp_variablesubst(wordlist *wlist); +wordlist *cp_varwl(struct variable *var); +wordlist *cp_variablesubst(wordlist *wlist); void free_struct_variable(struct variable *v); -#endif /* _VARIABLE_H */ +#endif diff --git a/src/frontend/vectors.c b/src/frontend/vectors.c index 64c48a897..40c03c2c6 100644 --- a/src/frontend/vectors.c +++ b/src/frontend/vectors.c @@ -27,6 +27,7 @@ struct dvec *EVTfindvec(char *node); /* gtri - end - add function prototype for EVTfindvec */ #endif + /* Find a named vector in a plot. We are careful to copy the vector if * v_link2 is set, because otherwise we will get screwed up. */ static struct dvec * @@ -44,8 +45,9 @@ findvec(char *word, struct plot *pl) if (d->v_link2) { v = vec_copy(d); vec_new(v); - } else + } else { v = d; + } if (end) end->v_link2 = v; else @@ -62,8 +64,9 @@ findvec(char *word, struct plot *pl) if (d->v_link2) { v = vec_copy(d); vec_new(v); - } else + } else { v = d; + } if (end) end->v_link2 = v; else @@ -80,8 +83,9 @@ findvec(char *word, struct plot *pl) if (d->v_link2) { v = vec_copy(d); vec_new(v); - } else + } else { v = d; + } if (end) end->v_link2 = v; else @@ -98,8 +102,9 @@ findvec(char *word, struct plot *pl) if (d->v_link2) { v = vec_copy(d); vec_new(v); - } else + } else { v = d; + } if (end) end->v_link2 = v; else @@ -122,7 +127,7 @@ findvec(char *word, struct plot *pl) #ifdef XSPICE /* gtri - begin - Add processing for getting event-driven vector */ - if(!d) + if (!d) d = EVTfindvec(word); /* gtri - end - Add processing for getting event-driven vector */ @@ -146,6 +151,7 @@ namecmp(const void *a, const void *b) const char *s = (const char *) a; const char *t = (const char *) b; + for (;;) { while ((*s == *t) && !isdigit(*s) && *s) s++, t++; @@ -197,7 +203,7 @@ sortvecs(struct dvec *d) for (t = d, i = 0; t; t = t->v_link2) array[i++] = t; - qsort(array, (size_t) i, sizeof (struct dvec *), veccmp); + qsort(array, (size_t) i, sizeof(struct dvec *), veccmp); /* Now string everything back together... */ for (j = 0; j < i - 1; j++) @@ -241,6 +247,7 @@ ft_loadfile(char *file) return; } + void plot_add(struct plot *pl) { @@ -278,6 +285,7 @@ plot_add(struct plot *pl) return; } + /* Remove a vector from the database, if it is there. */ void @@ -285,10 +293,10 @@ vec_remove(char *name) { struct dvec *ov; - for (ov = plot_cur->pl_dvecs; ov; ov = ov->v_next) { + for (ov = plot_cur->pl_dvecs; ov; ov = ov->v_next) if (cieq(name, ov->v_name) && (ov->v_flags & VF_PERMANENT)) break; - } + if (!ov) return; @@ -299,6 +307,7 @@ vec_remove(char *name) return; } + /* Get a vector by name. This deals with v(1), etc. almost properly. Also, * it checks for pre-defined vectors. */ @@ -323,8 +332,8 @@ vec_fromplot(char *word, struct plot *plot) /* scanf("%c(%s)" doesn't do what it should do. ) */ if (!d && (sscanf(word, "%c(%s", /* ) */ &cc, buf) == 2) && - /* ( */ ((s =strrchr(buf, ')')) != NULL) && - (*(s + 1) == '\0')) { + /* ( */ ((s = strrchr(buf, ')')) != NULL) && + (*(s + 1) == '\0')) { *s = '\0'; if (prefix("i(", /* ) */ word) || prefix("I(", /* ) */ word)) { /* Spice dependency... */ @@ -337,6 +346,7 @@ vec_fromplot(char *word, struct plot *plot) return (d); } + /* This is the main lookup routine for names. The possible types of names are: * name An ordinary vector. * plot.name A vector from a particular plot. @@ -383,8 +393,9 @@ vec_get(const char *vec_name) pl = plot_cur; } } - } else + } else { pl = plot_cur; + } if (pl) { d = vec_fromplot(word, pl); @@ -419,11 +430,11 @@ vec_get(const char *vec_name) if (ft_nutmeg) { fprintf(cp_err, "Error: circuit parameters only available with spice\n"); - tfree(wd); /* MW. Memory leak fixed again */ + tfree(wd); /* MW. Memory leak fixed again */ return (NULL); /* va: use NULL */ } - whole=copy(word); + whole = copy(word); name = ++word; for (param = name; *param && (*param != '['); param++) ; @@ -433,8 +444,9 @@ vec_get(const char *vec_name) for (s = param; *s && *s != ']'; s++) ; *s = '\0'; - } else + } else { param = NULL; + } if (ft_curckt) { @@ -445,7 +457,7 @@ vec_get(const char *vec_name) */ /* vv = if_getparam (ft_curckt->ci_ckt, &name, param, 0, 0); */ - vv = if_getparam (ft_curckt->ci_ckt, &name, param, 0, 0); + vv = if_getparam(ft_curckt->ci_ckt, &name, param, 0, 0); if (!vv) { tfree(whole); tfree(wd); @@ -481,7 +493,7 @@ vec_get(const char *vec_name) * int POTnegNode; // number of negative node of potenciometer (Nodo_3) * case POT_QUEST_POS_NODE: * value->rValue = (double)fast->POTposNode; - * return(OK); + * return (OK); * Works but with the format 1.00000E0 */ @@ -502,7 +514,7 @@ vec_get(const char *vec_name) * CP_STRING, * CP_LIST ° }; - */ + */ /* The variable is a vector */ if (vv->va_type == CP_LIST) { @@ -561,7 +573,7 @@ vec_get(const char *vec_name) fprintf(stdout, "%s=%d\n", nv->va_name, nv->va_num); break; default: { - fprintf(stderr, "ERROR: enumeration value `CP_BOOL' or `CP_LIST' not handled in vec_get\nAborting...\n" ); + fprintf(stderr, "ERROR: enumeration value `CP_BOOL' or `CP_LIST' not handled in vec_get\nAborting...\n"); controlled_exit(EXIT_FAILURE); } } @@ -591,6 +603,7 @@ vec_get(const char *vec_name) return (sortvecs(d)); } + /* Execute the commands for a plot. This is done whenever a plot becomes * the current plot. */ @@ -611,6 +624,7 @@ plot_docoms(wordlist *wl) return; } + /* Create a copy of a vector. */ struct dvec * @@ -630,7 +644,7 @@ vec_copy(struct dvec *v) if (isreal(v)) { nv->v_realdata = TMALLOC(double, v->v_length); bcopy(v->v_realdata, nv->v_realdata, - sizeof (double) * (size_t) v->v_length); + sizeof(double) * (size_t) v->v_length); nv->v_compdata = NULL; } else { nv->v_realdata = NULL; @@ -671,6 +685,7 @@ vec_copy(struct dvec *v) return (nv); } + /* Create a new plot structure. This just fills in the typename and sets up * the ccom struct. */ @@ -704,6 +719,7 @@ plot_alloc(char *name) return (pl); } + /* Stick a new vector in the proper place in the plot list. */ void @@ -730,6 +746,7 @@ vec_new(struct dvec *d) return; } + /* Because of the way that all vectors, including temporary vectors, * are linked together under the current plot, they can often be * left lying around. This gets rid of all vectors that don't have @@ -762,6 +779,7 @@ vec_gc(void) return; } + /* Free a dvector. This is sort of a pain because we also have to make sure * that it has been unlinked from its plot structure. If the name of the * vector is NULL, then we have already freed it so don't try again. (This @@ -782,9 +800,9 @@ vec_free_x(struct dvec *v) /* Now we have to take this dvec out of the plot list. */ if (pl != NULL) { - if (pl->pl_dvecs == v) + if (pl->pl_dvecs == v) { pl->pl_dvecs = v->v_next; - else { + } else { for (lv = pl->pl_dvecs; lv->v_next; lv = lv->v_next) if (lv->v_next == v) break; @@ -801,13 +819,19 @@ vec_free_x(struct dvec *v) pl->pl_scale = NULL; } } - if (v->v_name) tfree(v->v_name); - if (v->v_realdata) tfree(v->v_realdata); - if (v->v_compdata) tfree(v->v_compdata); + + if (v->v_name) + tfree(v->v_name); + if (v->v_realdata) + tfree(v->v_realdata); + if (v->v_compdata) + tfree(v->v_compdata); + tfree(v); return; } + /* This is something we do in a few places... Since vectors get copied a lot, * we can't just compare pointers to tell if two vectors are 'really' the same. */ @@ -834,6 +858,7 @@ vec_eq(struct dvec *v1, struct dvec *v2) return rtn; } + /* Return the name of the vector with the plot prefix stripped off. This * is no longer trivial since '.' doesn't always mean 'plot prefix'. */ @@ -852,8 +877,9 @@ vec_basename(struct dvec *v) (void) strcpy(buf, t + 1); else (void) strcpy(buf, v->v_name); - } else + } else { (void) strcpy(buf, v->v_name); + } strtolower(buf); for (t = buf; isspace(*t); t++) @@ -867,8 +893,6 @@ vec_basename(struct dvec *v) } - - /* Make a plot the current one. This gets called by cp_usrset() when one * does a 'set curplot = name'. * va: ATTENTION: has unlinked old keyword-class-tree from keywords[CT_VECTOR] @@ -884,7 +908,7 @@ plot_setcur(char *name) pl = plot_alloc("unknown"); pl->pl_title = copy("Anonymous"); pl->pl_name = copy("unknown"); - pl->pl_date = copy(datestring( )); + pl->pl_date = copy(datestring()); plot_new(pl); plot_cur = pl; return; @@ -900,15 +924,16 @@ plot_setcur(char *name) * repeated op-commands. When however cp_kwswitch is necessary for other * reasons, we should hold the original keyword table pointer in an * permanent variable, since it will lost here, and can never tfree'd. - if (plot_cur) - { - plot_cur->pl_ccom = cp_kwswitch(CT_VECTOR, pl->pl_ccom); - } + if (plot_cur) + { + plot_cur->pl_ccom = cp_kwswitch(CT_VECTOR, pl->pl_ccom); + } */ plot_cur = pl; return; } + /* Add a plot to the plot list. This is different from plot_add() in that * all this does is update the list and the variable $plots. */ @@ -922,6 +947,7 @@ plot_new(struct plot *pl) return; } + /* This routine takes a multi-dimensional vector, treats it as a * group of 2-dimensional matrices and transposes each matrix. * The data array is replaced with a new one that has the elements @@ -999,6 +1025,7 @@ vec_transpose(struct dvec *v) } } + /* This routine takes a multi-dimensional vector and turns it into a family * of 1-d vectors, linked together with v_link2. It is here so that plot * can do intelligent things. @@ -1062,6 +1089,7 @@ vec_mkfamily(struct dvec *v) return (vecs); } + /* This function will match "op" with "op1", but not "op1" with "op12". */ bool @@ -1069,15 +1097,16 @@ plot_prefix(char *pre, char *str) { if (!*pre) return (TRUE); + while (*pre && *str) { if (*pre != *str) break; pre++; str++; } + if (*pre || (*str && isdigit(pre[-1]))) return (FALSE); else return (TRUE); } - diff --git a/src/frontend/where.c b/src/frontend/where.c index 0b4b1e1b8..ef13fab8c 100644 --- a/src/frontend/where.c +++ b/src/frontend/where.c @@ -1,6 +1,6 @@ /********** Copyright 1990 Regents of the University of California. All rights reserved. -Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group +Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group **********/ #include "ngspice/ngspice.h" @@ -13,35 +13,33 @@ Author: 1985 Wayne A. Christopher, U. C. Berkeley CAD Group #include "circuits.h" #include "where.h" + void com_where(wordlist *wl) { - char *msg; + char *msg; - NG_IGNORE(wl); + NG_IGNORE(wl); - /*CDHW typing where with no current circuit caused crashes CDHW*/ - if (!ft_curckt) { - fprintf(cp_err, "There is no current circuit\n"); - return; } - else if (ft_curckt->ci_ckt != NULL) { - fprintf(cp_err, "No unconverged node found.\n"); - return; - } - msg = ft_sim->nonconvErr (ft_curckt->ci_ckt, 0); + /*CDHW typing where with no current circuit caused crashes CDHW*/ + if (!ft_curckt) { + fprintf(cp_err, "There is no current circuit\n"); + return; + } else if (ft_curckt->ci_ckt != NULL) { + fprintf(cp_err, "No unconverged node found.\n"); + return; + } - printf("%s", msg); + msg = ft_sim->nonconvErr (ft_curckt->ci_ckt, 0); + printf("%s", msg); - - -/* - if (ft_curckt) { - msg = ft_sim->nonconvErr (ft_curckt->ci_ckt, 0); - fprintf(cp_out, "%s", msg); - } else { - fprintf(cp_err, "Error: no circuit loaded.\n"); - } - -*/ + /* + if (ft_curckt) { + msg = ft_sim->nonconvErr (ft_curckt->ci_ckt, 0); + fprintf(cp_out, "%s", msg); + } else { + fprintf(cp_err, "Error: no circuit loaded.\n"); + } + */ }