#include <stdio.h>
#include "ps_include.h"
#define var(x) fprintf(fout, "/%s %g def\n", #x, x)
#define has(word) (strncmp(buf, word, strlen(word)) == 0)
#define grab(n) ((Section *)(nglobal \
? realloc((char *)global, n * sizeof (Section)) \
: calloc(n, sizeof (Section))))
char buf[512];
typedef struct {
long start;
long end;
} Section;
extern char *calloc(), *realloc();
static void print(FILE *, char **);
static void copy(FILE *, FILE *, Section *);
void
ps_include(FILE *fin, FILE *fout, int page_no, int whiteout,
int outline, int scaleboth, double cx, double cy,
double sx, double sy, double ax, double ay, double rot)
{
int foundpage = 0;
int nglobal = 0;
int maxglobal = 0;
Section prolog, page, trailer;
Section *global;
double llx, lly;
double urx, ury;
double w = whiteout != 0;
double o = outline != 0;
double s = scaleboth != 0;
int i;
llx = lly = 0;
urx = 72 * 8.5;
ury = 72 * 11.0;
prolog.start = prolog.end = 0;
page.start = page.end = 0;
trailer.start = 0;
fseek(fin, 0L, 0);
while (fgets(buf, sizeof (buf), fin) != NULL)
if (!has("%%"))
continue;
else if (has("%%Page: ")) {
if (!foundpage)
page.start = ftell(fin);
sscanf(buf, "%*s %*s %d", &i);
if (i == page_no)
foundpage = 1;
else if (foundpage && page.end <= page.start)
page.end = ftell(fin);
} else if (has("%%EndPage: ")) {
sscanf(buf, "%*s %*s %d", &i);
if (i == page_no) {
foundpage = 1;
page.end = ftell(fin);
}
if (!foundpage)
page.start = ftell(fin);
} else if (has("%%BoundingBox:"))
sscanf(buf, "%%%%BoundingBox: %lf %lf %lf %lf",
&llx, &lly, &urx, &ury);
else if (has("%%EndProlog") || has("%%EndSetup") ||
has("%%EndDocumentSetup"))
prolog.end = page.start = ftell(fin);
else if (has("%%Trailer"))
trailer.start = ftell(fin);
else if (has("%%BeginGlobal")) {
if (page.end <= page.start) {
if (nglobal >= maxglobal) {
maxglobal += 20;
global = grab(maxglobal);
}
global[nglobal].start = ftell(fin);
}
} else if (has("%%EndGlobal"))
if (page.end <= page.start)
global[nglobal++].end = ftell(fin);
fseek(fin, 0L, 2);
if (trailer.start == 0)
trailer.start = ftell(fin);
trailer.end = ftell(fin);
if (page.end <= page.start)
page.end = trailer.start;
print(fout, PS_head);
var(llx); var(lly); var(urx); var(ury); var(w); var(o); var(s);
var(cx); var(cy); var(sx); var(sy); var(ax); var(ay); var(rot);
print(fout, PS_setup);
copy(fin, fout, &prolog);
for (i = 0; i < nglobal; i++)
copy(fin, fout, &global[i]);
copy(fin, fout, &page);
copy(fin, fout, &trailer);
print(fout, PS_tail);
if (nglobal)
free(global);
}
static void
print(FILE *fout, char **s)
{
while (*s)
fprintf(fout, "%s\n", *s++);
}
static void
copy(FILE *fin, FILE *fout, Section *s)
{
if (s->end <= s->start)
return;
fseek(fin, s->start, 0);
while (ftell(fin) < s->end && fgets(buf, sizeof (buf), fin) != NULL)
if (buf[0] != '%')
fprintf(fout, "%s", buf);
}