File: main.cpp

package info (click to toggle)
contextfree 3.4.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,448 kB
  • sloc: cpp: 37,995; lex: 414; makefile: 123; sh: 43; python: 34
file content (642 lines) | stat: -rw-r--r-- 24,112 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
/*
 *
 
 Context Free Design Grammar - version 0.1
 
 Copyright (C) 2005 Chris Coyne - ccoyne77@gmail.com
 Copyright (C) 2005-2008 Mark Lentczner - markl@glyphic.com
 Copyright (C) 2008-2014 John Horigan - john@glyphic.com
 
 [Send me anything cool you make with it or of it.]
 
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License as published
 by the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 02111-1307  USA
 
 *
 */

#define NOMINMAX 1
#include <iostream>
#include <sstream>
#include <fstream>
#include <time.h>
#include "args.hxx"
#include <cstdlib>
#include <cstdio>
#include "cfdg.h"
#include "variation.h"
#ifdef _WIN32
#include "WinPngCanvas.h"
#else
#include "pngCanvas.h"
#endif
#include "SVGCanvas.h"
#include "ffCanvas.h"
#include "commandLineSystem.h"
#include "version.h"
#include "Rand64.h"
#include "makeCFfilename.h"
#include <cassert>
#include <memory>
#include <string>
#include "astexpression.h"
#include "prettyint.h"

using std::string;
using std::cerr;
using std::endl;

void setupTimer(std::shared_ptr<Renderer>& renderer);
void cleanupTimer();

std::ostream* myCout = &cerr;

static std::weak_ptr<Renderer> gRenderer;

static bool processInterrupt()
{
    auto TheRenderer = gRenderer.lock();
    if (!TheRenderer) return false;
    
    if (!TheRenderer->requestFinishUp) {
        TheRenderer->requestFinishUp = true;
        cerr << endl << "Render interrupted, drawing current shapes" << endl;
    } else if (!TheRenderer->requestStop) {
        TheRenderer->requestStop = true;
        cerr << endl << "Render interrupted, skipping drawing, cleaning up temporary files" << endl;
    } else {
        exit(9);
    }
    return true;
}

#ifdef _WIN32
#include <Windows.h>

BOOL __stdcall CtrlHandler(DWORD ctrlType) 
{
    if (ctrlType != CTRL_C_EVENT && ctrlType != CTRL_BREAK_EVENT)
        return FALSE;
    return processInterrupt();
}
#else
#include <csignal>

void termination_handler(int)
{
    processInterrupt();
}
#endif


struct options {
    enum OutputFormat { PNGfile = 0, SVGfile = 1, MOVfile = 2, BMPfile = 3, JSONfile = 4 };
    int   width;
    int   height;
    int   widthMult;
    int   heightMult;
    int   maxShapes;
    double minSize;
    double borderSize;
    std::string definitions;
    
    int   variation;
    bool  crop;
    bool  check;
    int   animationFrames;
    int   animationTime;
    int   animationFPS;
    bool  animationZoom;
    int   animateFrame;
    ffCanvas::QTcodec animationCodec;
    
    std::string input;
    std::string output;
    OutputFormat format;
    std::string displayExec;
    
    bool quiet;
    bool outputTime;
    bool outputStdout;
    bool outputTemp;
    bool outputWallpaper;
    bool paramTest;
    bool deleteTemps;
    
    options()
    : width(500), height(500), widthMult(1), heightMult(1), maxShapes(0), 
      minSize(0.3F), borderSize(2.0F), variation(-1), crop(false), check(false), 
      animationFrames(0), animationTime(0), animationFPS(15), animationZoom(false), 
      animateFrame(0), animationCodec(ffCanvas::H264), format(PNGfile), quiet(false),
      outputTime(false), outputStdout(false), outputTemp(false), outputWallpaper(false),
      paramTest(false), deleteTemps(false)
    { }
};

int
intArg2(const std::string& arg, const std::string& sstr, int& x, int& y)
{
    char* end;
    const char* str = sstr.c_str();
    long int v = -1;
    
    v = strtol(str, &end, 10);
    if (end == str || v <= 0) {
        cerr << "Option " << arg << " takes a positive integer argument or a pair of positive integers (e.g., 500x300)" << endl;
        return 0;
    }
    x = static_cast<int>(v);
    if (*end == 'x') {
        str = end + 1;
        v = strtol(str, &end, 10);
        if (end == str || v <= 0) {
            cerr << "Option -" << arg << " takes a positive integer argument or a pair of positive integers (e.g., 500x300)" << endl;
            return 0;
        }
        y = static_cast<int>(v);
    } else {
        y = x;
        return 1;
    }
    return 2;
}

void
processCommandLine(int argc, char* argv[], options& opt)
{
    std::ostringstream name, epilog;
    name << APP_NAME(argv[0]) << " - " << APP_VERSION() << "(v" << APP_BUILD()
         << ") - Context Free Design Grammar";
    epilog << "If '-' is specified for the CFDG FILE then the input cfdg file is piped "
              "from standard input. If the output file name is omitted and the "
           << APP_OPTCHAR() << "o option and the " << APP_OPTCHAR()
           << "C option are not used then the output will be sent to stdout.";
    args::ArgumentParser parser(name.str(), epilog.str());
    parser.ShortPrefix(APP_OPTCHAR());      // Set Windows/posix command syntax
    parser.LongPrefix(APP_OPTLONG());
    parser.LongSeparator(APP_OPTSEP());
    parser.Terminator(APP_OPTLONG());
    parser.Prog(APP_NAME(argv[0]));         // Set app name minus path
    args::HelpFlag help(parser, "HELP", "Show this help menu.", {'?', "help"});
    args::Flag version(parser, "version", "Output version and quit.", {"version"});
    args::ValueFlag<int> width(parser, "WIDTH", "Output width", {'w', "width"}, 500);
    args::ValueFlag<int> height(parser, "HEIGHT", "Output height", {'h', "height"}, 500);
    args::ValueFlag<string> size(parser, "SIZE or WIDTHxHEIGHT",
                                 "Set output size to SIZExSIZE or WIDTHxHEIGHT",
                                 {'s', "size"}, "");
    args::ValueFlag<string> tile(parser, "SIZE or WIDTHxHEIGHT",
                                 "Multiply output by SIZExSIZE or WIDTHxHEIGHT",
                                 {'T', "tile"}, "");
    args::ValueFlag<int> maxShapes(parser, "MAXSHAPES",
                                   "Maximum number of shapes", {'m', "maxshapes"}, 0);
    args::ValueFlag<double> minSize(parser, "MINIMUM SIZE",
                                    "Minimum size of shapes in pixels/mm (default 0.3)",
                                    {'x', "minimumsize"}, 0.3);
    args::ValueFlag<double> borderSize(parser, "BORDER SIZE", "Border size [-1,2]: "
                                       "-1=-8 pixel border, 0=no border, 1=8 pixel "
                                       "border, 2=variable-sized border",
                                       {'b', "bordersize"}, 2.0);
    args::ValueFlag<string> variation(parser, "VARIATION",
        "Set the variation code (default is random)", {'v', "variation"}, "");
    args::ValueFlagList<string> definition(parser, "NAME=VALUE",
        "Define a variable, configuration, or function. Overrides definitions in the input file.", {'D'});
    args::ValueFlag<string> outputFileTemplate(parser, "NAME TEMPLATE",
        "Set the output file name, supports variable expansion %f expands to the "
        "animation frame number, %v and %V expands to the variation code in lower "
        "or upper case, %% expands to %", {'o', "outputtemplate"}, "");
    args::ValueFlag<string> animation(parser, "NUM or TIMExFPS",
        "Generate NUM animation frames at 15fps or TIMExFPS animation frames",
        {'a',"animate"}, "");
    args::ValueFlag<int> frame(parser, "FRAME", "Animate a particular frame", {'f', "frame"}, 0);
    args::Flag zoom(parser, "zoom", "Zoom out during animation", {'z', "zoom"});
    args::Flag makeSVG(parser, "SVG", "Generate SVG output (not allowed for animation)",
                       {'V', "svg"});
    args::Flag makeJSON(parser, "JSON", "Generate JSON output of parsed cfdg file",
                       {'J', "json"});
    args::Flag makeQT(parser, "quicktime", "Make QuickTime output", {'Q', "quicktime"});
    args::Flag makeProRes(parser, "ProRes", "Use ProRes codec for QuickTime output", { "prores" });
#ifdef _WIN32
    args::Flag wallpaper(parser, "wallpaper", "Generate desktop wallpaper output",
                         {'W', "wallpaper"});
#else
    const bool wallpaper = false;
#endif
    args::ValueFlag<string> display(parser, "display executable", "Display output with specified program", {"display"}, "");
    args::Flag crop(parser, "crop", "Crop output", {'c', "crop"});
    args::Flag quiet(parser, "quiet", "Quiet mode, suppress non-error output", {'q', "quiet"});
    args::Flag check(parser, "check", "Check syntax of cfdg file and exit", {'C', "check"});
    args::Flag timer(parser, "time", "Output the time taken to render the cfdg file", {'t', "time"});
    args::Flag paramDebug(parser, "param debug", "Parameter allocation debug, test "
        "whether all the parameter blocks were cleaned up", {'P', "paramdebug"});
    args::Flag cleanup(parser, "cleanup", "Delete old temporary files", {'d', "cleanup"});
    args::Positional<std::string> inputFile(parser, "CFDG FILE", "Input cfdg file", "");
    args::Positional<std::string> outputFile(parser, "OUTPUT FILE", "Output image file", "");
    
    auto bailout = [&](const char * msg) {
        if (msg && *msg)
            cerr << msg << endl;
        cerr << parser;
        exit(2);
    };
    
    try {
        if (!parser.ParseCLI(argc, argv))
            bailout("Too many arguments.");
    } catch (args::Help&) {
        std::cout << parser;
        exit(0);
    } catch (args::Error& e) {
        bailout(e.what());
    }
    
    if (version) {
        std::cout << name.str() << endl;
        exit(0);
    }
    if (width) opt.width = args::get(width);
    if (height) opt.height = args::get(height);
    if (opt.width < 10 || opt.height < 10)
        bailout("Minimum output dimensions are 10 pixels.");
    if (size && intArg2(parser.ShortPrefix() + 's', args::get(size), opt.width, opt.height) < 1)
        bailout(nullptr);
    if (tile && intArg2(parser.ShortPrefix() + 'T', args::get(tile), opt.widthMult, opt.heightMult) < 1)
        bailout(nullptr);
    if (maxShapes) {
        opt.maxShapes = args::get(maxShapes);
        if (opt.maxShapes < 1)
            bailout("Must specify at least one shape.");
    }
    if (minSize) opt.minSize = args::get(minSize);
    if (borderSize) {
        opt.borderSize = args::get(borderSize);
        if (opt.borderSize < -1.0 || opt.borderSize > 2.0)
            bailout("Border size must be between -1 and 2");
    }
    if (variation) {
        opt.variation = Variation::fromString(args::get(variation).c_str());
        if (opt.variation == -1)
            bailout("Error parsing variation");
    }
    if (definition) {
        auto defs = definition.Get();
        for (auto&& def: defs) {
            auto equal = def.find("=");
            if (equal == std::string::npos || equal == 0 || equal == def.length() - 1)
                bailout("Definitions must be of the form -Dname=value");
            opt.definitions.append(def);
            opt.definitions += ' ';
        }
    }
    if (outputFileTemplate) opt.output = args::get(outputFileTemplate);
    if (display) opt.displayExec = args::get(display);
    if (animation) {
        if (makeSVG) bailout("Animation cannot output to SVG files.");
        if (crop) bailout("Animation cannot output cropped files.");
        if (makeQT) opt.format = options::MOVfile;
        if (makeProRes) opt.animationCodec = ffCanvas::ProRes;
        opt.animationZoom = zoom;
        int fps = 15, time = 0;
        switch (intArg2(parser.ShortPrefix() + 'a', args::get(animation), time, fps)) {
            case 2:
                opt.animationTime = time;
                opt.animationFPS = fps;
                opt.animationFrames = time * fps;
                break;
            case 1:
                opt.animationTime = time / opt.animationFPS;
                opt.animationFrames = time;
                break;
            default:
                bailout(nullptr);
        }
        if (display && !makeQT)
            bailout("Only QuickTime animations can be displayed.");
        if (makeQT && !ffCanvas::Available())
            bailout("FFmpeg DLLs not found, QuickTime output is unavailable.");
        if (makeProRes && !makeQT)
            bailout("ProRes codec only available with QuickTime output.");
        if (frame) {
            if (makeQT)
                bailout("Single frame animation only outputs PNG files.");
            opt.animateFrame = args::get(frame);
            if (opt.animateFrame < 1)
                bailout("Animation frame must be a positive integer.");
            if (opt.animateFrame > opt.animationFrames)
                bailout("Animation frame is after the end of the animation.");
        }
    } else {
        if (makeQT)
            bailout("QuickTime output is only available when animating.");
        if (zoom)
            bailout("Zoomed output is only available when animating.");
        if (frame)
            bailout("Animation frame can only be rendered when animating.");
    }
    if (makeSVG) opt.format = options::SVGfile;
    if (wallpaper) {
        if (makeSVG || animation || crop)
            bailout("Wallpaper output must be uncropped, not animated, and not SVG.");
        opt.format = options::BMPfile;
        opt.outputWallpaper = true;
    }
    if (makeJSON) opt.format = options::JSONfile;
    opt.crop = crop;
    opt.check = check;
    opt.quiet = quiet;
    opt.outputTime = timer;
    opt.paramTest = paramDebug;
    opt.deleteTemps = cleanup;
    if (quiet && cleanup)
        bailout("Cannot clean up temporary files quietly.");
    if (inputFile) opt.input = args::get(inputFile);
    if (outputFile) {
        if (!opt.output.empty())
            bailout("Two output files specified.");
        
        // If a static output file name is provided then generate an output
        // file name format string by escaping any '%' characters. If this is
        // an animation run with PNG output then add "_%f" before the extension.
        opt.output.reserve(args::get(outputFile).length());
        for (char c: args::get(outputFile)) {
            opt.output.append(c == '%' ? 2 : 1, c);
        }
        if (opt.animationFrames && opt.animateFrame == 0 && opt.format != options::MOVfile) {
            std::size_t ext = opt.output.find_last_of('.');
            std::size_t dir = opt.output.find_last_of(APP_DIRCHAR());
            if (ext != string::npos && (dir == string::npos || ext > dir)) {
                opt.output.insert(ext, "_%f");
            } else {
                opt.output.append("_%f");
            }
        }
    }
    if (!inputFile && !cleanup)
        bailout("Missing input file.");
    if (!outputFile && !outputFileTemplate && display) 
        opt.outputTemp = true;
    if ((!outputFile || opt.output == "-") && !outputFileTemplate && !check && !opt.outputTemp) {
        opt.outputStdout = true;
        opt.output = "-";
        opt.quiet = true;
    }
}

class nullstreambuf : public std::streambuf
{
protected:
    int overflow(int c) { return c; }
};
class nullostream : public std::ostream
{
public:
    nullostream() : std::ostream(new nullstreambuf()) {}
};

static nullostream cnull;

namespace {
    struct OstreamCloser
    {
        void operator()(std::ostream* ptr) const {
            if (ptr != &std::cout)
                delete ptr;        // Not called if nullptr
        }
    };
}


int main (int argc, char* argv[]) {
    options opts;
    int var = Variation::random(6);
    
#ifdef _WIN32
    SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE);
#else
    struct sigaction new_action, old_action;
    new_action.sa_handler = termination_handler;
    sigemptyset(&new_action.sa_mask);
    new_action.sa_flags = 0;

    sigaction(SIGINT, nullptr, &old_action);
    if (old_action.sa_handler != SIG_IGN)
        sigaction(SIGINT, &new_action, nullptr);
#endif    
    
    processCommandLine(argc, argv, opts);
    
    if (opts.quiet) myCout = &cnull;
    
    clock_t startTime = clock();
    clock_t fromTime = startTime;
    clock_t clocksPerMsec = CLOCKS_PER_SEC / 1000;
    
    if (opts.variation < 0) opts.variation = var;
    std::string code = Variation::toString(opts.variation, false);
    
    CommandLineSystem system(opts.quiet);
    
    if (!opts.quiet || opts.deleteTemps) {
        auto temps = system.findTempFiles();
        if (temps.empty()) {
            if (opts.deleteTemps)
                cerr << "No temporary files found." << endl;
        } else {
            if (opts.deleteTemps) {
                cerr << "Old temporary files deleted:\n";
                for (auto&& temp : temps)
                    if (system.deleteTempFile(temp))
                        fprintf(stderr, "Failed to delete: " FileFormat "\n", temp.c_str());
                    else 
                        fprintf(stderr, FileFormat "\n", temp.c_str());
                cerr << endl;
            } else {
                cerr << "Old temporary files found:\n";
                for (auto&& temp: temps)
                    fprintf(stderr, FileFormat "\n", temp.c_str());
                cerr << endl;
            }
        }
        
        if (opts.input.empty()) exit(0);
    }
    
    AST::ASTfunction::RandStaticIsConst = opts.format != options::JSONfile;
    cfdg_ptr myDesign = CFDG::ParseFile(opts.input.c_str(), &system,
                                        opts.variation, opts.definitions);
    if (!myDesign) return 3;
    if (opts.check) return 0;
    if (opts.format == options::JSONfile) {
        std::unique_ptr<std::ostream, OstreamCloser> out(nullptr);
        if (opts.outputStdout)
            out.reset(&std::cout);
        else
            out.reset(new std::ofstream(opts.output));
        myDesign->serialize(*out);
        return 0;
    }
    if (opts.widthMult != 1 || opts.heightMult != 1) {
        if (!myDesign->isTiled() && !myDesign->isFrieze()) {
            cerr << "Tiled output multiplication only allowed for tiled or frieze designs." << endl;
            return 6;
        }
        if (opts.format != options::PNGfile && opts.format != options::BMPfile) {
            cerr << "Tiled output multiplication only allowed for PNG output." << endl;
            return 6;
        }
    }

    bool useRGBA = myDesign->usesColor;
    aggCanvas::PixelFormat pixfmt = aggCanvas::SuggestPixelFormat(myDesign.get());
    bool use16bit = (pixfmt & aggCanvas::Has_16bit_Color) != 0;
    bool usecustom = (pixfmt & aggCanvas::Has_Custom_Blend) != 0;
    const char* fmtnames[4] = { "PNG image", "SVG vector output", "Quicktime movie", "Wallpaper BMP image" };
    
    *myCout << "Generating " << (use16bit ? "16bit " : "8bit ") 
        << (useRGBA ? "color" : "gray-scale")
        << (usecustom ? ", custom blend" : "")
        << ' ' << fmtnames[opts.format]
        << ", variation " 
        << code << "..." << endl;

    std::string actualFileName;

    { // Scope for canvas & renderer
    std::unique_ptr<pngCanvas> png;
    std::unique_ptr<SVGCanvas> svg;
    std::unique_ptr<ffCanvas>  mov;
    Canvas* myCanvas = nullptr;
        
    std::shared_ptr<Renderer> TheRenderer(myDesign->renderer(myDesign,
                                          opts.width, opts.height, opts.minSize,
                                          opts.variation, opts.borderSize));
    
    if (TheRenderer == nullptr) {
        return 9;
    }
        
    gRenderer = TheRenderer;    // weak pointer for interrupt signal handler

    if (!opts.quiet) setupTimer(TheRenderer);
    
    if (opts.maxShapes > 0)
        TheRenderer->setMaxShapes(opts.maxShapes);
        
    if (opts.animationFrames == 0)
        TheRenderer->run(nullptr, false);
    
    opts.width = TheRenderer->m_width;
    opts.height = TheRenderer->m_height;
    opts.crop = opts.crop && !(myDesign->isTiled() || myDesign->isFrieze());
    
    switch (opts.format) {
        case options::BMPfile:
        case options::PNGfile: {
            png = std::make_unique<pngCanvas>(
                                    opts.output.c_str(), opts.quiet, opts.width, opts.height,
                                    pixfmt, opts.crop, opts.animationFrames, opts.variation,
                                    opts.format == options::BMPfile, TheRenderer.get(),
                                    opts.widthMult, opts.heightMult, opts.outputTemp);
            myCanvas = static_cast<Canvas*>(png.get());
            if (png->mWidth != opts.width || png->mHeight != opts.height) {
                TheRenderer->resetSize(png->mWidth, png->mHeight);
                opts.width = TheRenderer->m_width;
                opts.height = TheRenderer->m_height;
            }
            break;
        }
        case options::SVGfile: {
            string name = makeCFfilename(opts.output.c_str(), 0, 0, opts.variation);
            svg = std::make_unique<SVGCanvas>(name.c_str(), opts.width, opts.height, opts.crop, 
                                              nullptr, -1, opts.outputTemp);
            myCanvas = static_cast<Canvas*>(svg.get());
            if (svg->mError)
                cerr << "Failed to open SVG file." << endl;
            break;
        }
        case options::MOVfile: {
            string name = makeCFfilename(opts.output.c_str(), 0, 0, opts.variation);
            mov = std::make_unique<ffCanvas>(name.c_str(), pixfmt, opts.width, opts.height,
                                             opts.animationFPS, opts.animationCodec, 
                                             opts.outputTemp);
            if (mov->mErrorMsg) {
                cerr << "Failed to create movie file: " << mov->mErrorMsg << endl;
                exit(8);
            }
            myCanvas = static_cast<Canvas*>(mov.get());
            break;
        }
        case options::JSONfile:
            break;
    }
    
    if (myCanvas->mError || system.error(false) || TheRenderer->requestStop) {
        cleanupTimer();
        Renderer::AbortEverything = true;
        return 5;
    }
    
    if (opts.outputTime) {
        clock_t toTime = clock();
        clock_t runTime = (toTime - fromTime) / clocksPerMsec;
        *myCout << "The cfdg file took " << prettyInt(runTime) << " msec to execute." << endl;
        fromTime = toTime;
    }
    
    if (opts.animationFrames) {
        TheRenderer->animate(myCanvas, opts.animationFrames, opts.animateFrame, opts.animationZoom);
    } else {
        TheRenderer->draw(myCanvas);
    }
    *myCout << endl;
    
    if (!opts.quiet) cleanupTimer();
    
    *myCout << "DONE!" << endl;
    *myCout << "The output file name is " << 
    makeCFfilename(opts.output.c_str(), 0, 0, opts.variation) << endl;
    
    if (opts.outputTime) {
        clock_t toTime = clock();
        clock_t runTime = (toTime - fromTime) / clocksPerMsec;
        *myCout << "The cfdg file took " << prettyInt(runTime) << " msec to render." << endl;
        runTime = (toTime - startTime) / clocksPerMsec;
        *myCout << "The cfdg file took a total of " << prettyInt(runTime) << " msec to process." << endl;
    }

        Renderer::AbortEverything = !(opts.paramTest);
        actualFileName = myCanvas->mFileName;
    }   // delete canvas & renderer
    
    if (!opts.displayExec.empty()) {
        opts.displayExec += ' ';
        opts.displayExec += actualFileName;
        if (std::system(opts.displayExec.c_str()) != 0)
            cerr << "\n\nError viewing the output file.\n" << endl;
    }
    
    if (opts.paramTest) {
        myDesign.reset();   // Delete the AST and its parameters before checking
        if (Renderer::ParamCount) {
            cerr << "Left-over parameter blocks in memory:" << prettyInt(static_cast<unsigned long>(Renderer::ParamCount)) << endl;
			return 88;
		} else {
            *myCout << "All parameter blocks deleted" << endl;
		}
    }
    
    return 0;
}