From: Henry Gabryjelski <henrygab@users.noreply.github.com>
Date: Mon, 21 Aug 2023 02:17:04 -0700
Subject: Automated formatting using `clang-format`

Origin: https://github.com/gerbv/gerbv/commit/43018416b2a809658dce2bfa67c20aff1d89e90f
---
 src/amacro.c            |  493 ++-
 src/amacro.h            |    7 +-
 src/attribute.c         |  813 +++--
 src/attribute.h         |    7 +-
 src/callbacks.c         | 7783 +++++++++++++++++++++-----------------------
 src/callbacks.h         |  299 +-
 src/common.h            |   19 +-
 src/csv.c               |  623 ++--
 src/csv.h               |   16 +-
 src/csv_defines.h       |   52 +-
 src/draw-gdk.c          | 1783 +++++-----
 src/draw-gdk.h          |   13 +-
 src/draw.c              | 2495 +++++++-------
 src/draw.h              |   11 +-
 src/drill.c             | 3307 +++++++++----------
 src/drill.h             |  163 +-
 src/drill_stats.c       |  349 +-
 src/drill_stats.h       |   33 +-
 src/dynload.c           |  179 +-
 src/dynload.h           |    2 +-
 src/export-drill.c      |  176 +-
 src/export-dxf.cpp      |  517 ++-
 src/export-geda-pcb.c   |  467 ++-
 src/export-image.c      |  145 +-
 src/export-isel-drill.c |  239 +-
 src/export-rs274x.c     |  672 ++--
 src/gerb_file.c         |  305 +-
 src/gerb_file.h         |   31 +-
 src/gerb_image.c        | 2109 ++++++------
 src/gerb_image.h        |   21 +-
 src/gerb_stats.c        |  416 +--
 src/gerb_stats.h        |   34 +-
 src/gerber.c            | 4449 +++++++++++++------------
 src/gerber.h            |   66 +-
 src/gerbv.c             | 1645 +++++-----
 src/gerbv.h             | 1119 ++++---
 src/gerbv_icon.h        |  813 +++--
 src/gettext.h           |  234 +-
 src/icons.h             |  857 ++---
 src/interface.c         | 4498 +++++++++++++------------
 src/interface.h         |  332 +-
 src/lrealpath.c         |  188 +-
 src/lrealpath.h         |    4 +-
 src/main.c              | 2039 ++++++------
 src/main.h              |  167 +-
 src/opdefines.h         |  360 +-
 src/pick-and-place.c    | 1203 ++++---
 src/pick-and-place.h    |   45 +-
 src/project.c           | 1465 ++++-----
 src/project.h           |   49 +-
 src/render.c            | 1062 +++---
 src/render.h            |   54 +-
 src/scheme-private.h    |  274 +-
 src/scheme.c            | 8298 ++++++++++++++++++++++++-----------------------
 src/scheme.h            |  287 +-
 src/selection.c         |   49 +-
 src/selection.h         |   16 +-
 src/table.c             |  345 +-
 src/table.h             |   24 +-
 src/tooltable.c         |  127 +-
 60 files changed, 25870 insertions(+), 27778 deletions(-)

diff --git a/src/amacro.c b/src/amacro.c
index 752281d..7a260d7 100644
--- a/src/amacro.c
+++ b/src/amacro.c
@@ -37,64 +37,55 @@
 /*
  * Allocates a new instruction structure
  */
-static gerbv_instruction_t *
-new_instruction(void)
-{
-    gerbv_instruction_t *instruction;
+static gerbv_instruction_t*
+new_instruction(void) {
+    gerbv_instruction_t* instruction;
 
-    instruction = (gerbv_instruction_t *)malloc(sizeof(gerbv_instruction_t));
+    instruction = (gerbv_instruction_t*)malloc(sizeof(gerbv_instruction_t));
     if (instruction == NULL) {
-	free(instruction);
-	return NULL;
+        free(instruction);
+        return NULL;
     }
 
     memset(instruction, 0, sizeof(gerbv_instruction_t));
-    
+
     return instruction;
 } /* new_instruction */
 
-
 /*
  * Allocates a new amacro structure
  */
-static gerbv_amacro_t *
-new_amacro(void)
-{
-    gerbv_amacro_t *amacro;
+static gerbv_amacro_t*
+new_amacro(void) {
+    gerbv_amacro_t* amacro;
 
-    amacro = (gerbv_amacro_t *)malloc(sizeof(gerbv_amacro_t));
+    amacro = (gerbv_amacro_t*)malloc(sizeof(gerbv_amacro_t));
     if (amacro == NULL) {
-	free(amacro);
-	return NULL;
+        free(amacro);
+        return NULL;
     }
 
     memset(amacro, 0, sizeof(gerbv_amacro_t));
-    
+
     return amacro;
 } /* new_amacro */
 
-
 /*
  * Defines precedence of operators used in aperture macros
  */
 static int
-math_op_prec(gerbv_opcodes_t math_op)
-{
+math_op_prec(gerbv_opcodes_t math_op) {
     switch (math_op) {
-    case GERBV_OPCODE_ADD:
-    case GERBV_OPCODE_SUB:
-	return 1;
-    case GERBV_OPCODE_MUL:
-    case GERBV_OPCODE_DIV:
-	return 2;
-    default:
-	;
+        case GERBV_OPCODE_ADD:
+        case GERBV_OPCODE_SUB: return 1;
+        case GERBV_OPCODE_MUL:
+        case GERBV_OPCODE_DIV: return 2;
+        default:;
     }
 
     return 0;
 } /* math_op_prec */
 
-
 /*
  * Operations on the operator stack. The operator stack is used in the
  * "shunting yard algorithm" to achive precedence.
@@ -102,27 +93,25 @@ math_op_prec(gerbv_opcodes_t math_op)
  * so it is solved by a small array and an index to that array.
  */
 #define MATH_OP_STACK_SIZE 2
-#define MATH_OP_PUSH(val) math_op[math_op_idx++] = val
-#define MATH_OP_POP math_op[--math_op_idx]
-#define MATH_OP_TOP (math_op_idx > 0)?math_op[math_op_idx - 1]:GERBV_OPCODE_NOP
-#define MATH_OP_EMPTY (math_op_idx == 0)
-
+#define MATH_OP_PUSH(val)  math_op[math_op_idx++] = val
+#define MATH_OP_POP        math_op[--math_op_idx]
+#define MATH_OP_TOP        (math_op_idx > 0) ? math_op[math_op_idx - 1] : GERBV_OPCODE_NOP
+#define MATH_OP_EMPTY      (math_op_idx == 0)
 
 /*
  * Parses the definition of an aperture macro
  */
-gerbv_amacro_t *
-parse_aperture_macro(gerb_file_t *fd)
-{
-    gerbv_amacro_t *amacro;
-    gerbv_instruction_t *ip = NULL;
-    int primitive = 0, c, found_primitive = 0;
-    gerbv_opcodes_t math_op[MATH_OP_STACK_SIZE];
-    int math_op_idx = 0;
-    int comma = 0; /* Just read an operator (one of '*+X/) */
-    int neg = 0; /* negative numbers succeding , */
-    unsigned char continueLoop = 1;
-    int equate = 0;
+gerbv_amacro_t*
+parse_aperture_macro(gerb_file_t* fd) {
+    gerbv_amacro_t*      amacro;
+    gerbv_instruction_t* ip        = NULL;
+    int                  primitive = 0, c, found_primitive = 0;
+    gerbv_opcodes_t      math_op[MATH_OP_STACK_SIZE];
+    int                  math_op_idx  = 0;
+    int                  comma        = 0; /* Just read an operator (one of '*+X/) */
+    int                  neg          = 0; /* negative numbers succeding , */
+    unsigned char        continueLoop = 1;
+    int                  equate       = 0;
 
     amacro = new_amacro();
 
@@ -132,246 +121,218 @@ parse_aperture_macro(gerb_file_t *fd)
      * Get macroname
      */
     amacro->name = gerb_fgetstring(fd, '*');
-    c = gerb_fgetc(fd);	/* skip '*' */
+    c            = gerb_fgetc(fd); /* skip '*' */
     if (c == EOF) {
-	continueLoop = 0;
+        continueLoop = 0;
     }
-    
+
     /*
-     * Since I'm lazy I have a dummy head. Therefore the first 
+     * Since I'm lazy I have a dummy head. Therefore the first
      * instruction in all programs will be NOP.
      */
     amacro->program = new_instruction();
-    ip = amacro->program;
-    
-    while(continueLoop) {
-	
-	c = gerb_fgetc(fd);
-	switch (c) {
-	case '$':
-	    if (found_primitive) {
-		ip->next = new_instruction(); /* XXX Check return value */
-		ip = ip->next;
-		ip->opcode = GERBV_OPCODE_PPUSH;
-		amacro->nuf_push++;
-		ip->data.ival = gerb_fgetint(fd, NULL);
-		comma = 0;
-	    } else {
-		equate = gerb_fgetint(fd, NULL);
-	    }
-	    break;
-	case '*':
-	    while (!MATH_OP_EMPTY) {
-		ip->next = new_instruction(); /* XXX Check return value */
-		ip = ip->next;
-		ip->opcode = MATH_OP_POP;
-	    }
-	    /*
-	     * Check is due to some gerber files has spurious empty lines.
-	     * (EagleCad of course).
-	     */
-	    if (found_primitive) {
-		ip->next = new_instruction(); /* XXX Check return value */
-		ip = ip->next;
-		if (equate) {
-		    ip->opcode = GERBV_OPCODE_PPOP;
-		    ip->data.ival = equate;
-		} else {
-		    ip->opcode = GERBV_OPCODE_PRIM;
-		    ip->data.ival = primitive;
-		}
-		equate = 0;
-		primitive = 0;
-		found_primitive = 0;
-	    }
-	    break;
-	case '=':
-	    if (equate) {
-		found_primitive = 1;
-	    }
-	    break;
-	case ',':
-	    if (!found_primitive) {
-		found_primitive = 1;
-		break;
-	    }
-	    while (!MATH_OP_EMPTY) {
-		ip->next = new_instruction(); /* XXX Check return value */
-		ip = ip->next;
-		ip->opcode = MATH_OP_POP;
-	    }
-	    comma = 1;
-	    break;
-	case '+':
-	    while ((!MATH_OP_EMPTY) &&
-		   (math_op_prec(MATH_OP_TOP) >= math_op_prec(GERBV_OPCODE_ADD))) {
-		ip->next = new_instruction(); /* XXX Check return value */
-		ip = ip->next;
-		ip->opcode = MATH_OP_POP;
-	    }
-	    MATH_OP_PUSH(GERBV_OPCODE_ADD);
-	    comma = 1;
-	    break;
-	case '-':
-	    if (comma) {
-		neg = 1;
-		comma = 0;
-		break;
-	    }
-	    while((!MATH_OP_EMPTY) &&
-		  (math_op_prec(MATH_OP_TOP) >= math_op_prec(GERBV_OPCODE_SUB))) {
-		ip->next = new_instruction(); /* XXX Check return value */
-		ip = ip->next;
-		ip->opcode = MATH_OP_POP;
-	    }
-	    MATH_OP_PUSH(GERBV_OPCODE_SUB);
-	    break;
-	case '/':
-	    while ((!MATH_OP_EMPTY)  &&
-		   (math_op_prec(MATH_OP_TOP) >= math_op_prec(GERBV_OPCODE_DIV))) {
-		ip->next = new_instruction(); /* XXX Check return value */
-		ip = ip->next;
-		ip->opcode = MATH_OP_POP;
-	    }
-	    MATH_OP_PUSH(GERBV_OPCODE_DIV);
-	    comma = 1;
-	    break;
-	case 'X':
-	case 'x':
-	    while ((!MATH_OP_EMPTY) &&
-		   (math_op_prec(MATH_OP_TOP) >= math_op_prec(GERBV_OPCODE_MUL))) {
-		ip->next = new_instruction(); /* XXX Check return value */
-		ip = ip->next;
-		ip->opcode = MATH_OP_POP;
-	    }
-	    MATH_OP_PUSH(GERBV_OPCODE_MUL);
-	    comma = 1;
-	    break;
-	case '0':
-	    /*
-	     * Comments in aperture macros are a definition starting with
-	     * zero and ends with a '*'
-	     */
-	    if (!found_primitive && (primitive == 0)) {
-		/* Comment continues 'til next *, just throw it away */
-		free(gerb_fgetstring(fd, '*'));
-		c = gerb_fgetc(fd); /* Read the '*' */
-		break;
-	    }
-	case '1':
-	case '2':
-	case '3':
-	case '4':
-	case '5':
-	case '6':
-	case '7':
-	case '8':
-	case '9':
-	case '.':
-	    /* 
-	     * First number in an aperture macro describes the primitive
-	     * as a numerical value
-	     */
-	    if (!found_primitive) {
-		primitive = (primitive * 10) + (c - '0');
-		break;
-	    }
-	    (void)gerb_ungetc(fd);
-	    ip->next = new_instruction(); /* XXX Check return value */
-	    ip = ip->next;
-	    ip->opcode = GERBV_OPCODE_PUSH;
-	    amacro->nuf_push++;
-	    ip->data.fval = gerb_fgetdouble(fd);
-	    if (neg) 
-		ip->data.fval = -ip->data.fval;
-	    neg = 0;
-	    comma = 0;
-	    break;
-	case '%':
-	    gerb_ungetc(fd);  /* Must return with % first in string
-				 since the main parser needs it */
-	    return amacro;
-	default :
-	    /* Whitespace */
-	    break;
-	}
-	if (c == EOF) {
-	    continueLoop = 0;
-	}
+    ip              = amacro->program;
+
+    while (continueLoop) {
+
+        c = gerb_fgetc(fd);
+        switch (c) {
+            case '$':
+                if (found_primitive) {
+                    ip->next   = new_instruction(); /* XXX Check return value */
+                    ip         = ip->next;
+                    ip->opcode = GERBV_OPCODE_PPUSH;
+                    amacro->nuf_push++;
+                    ip->data.ival = gerb_fgetint(fd, NULL);
+                    comma         = 0;
+                } else {
+                    equate = gerb_fgetint(fd, NULL);
+                }
+                break;
+            case '*':
+                while (!MATH_OP_EMPTY) {
+                    ip->next   = new_instruction(); /* XXX Check return value */
+                    ip         = ip->next;
+                    ip->opcode = MATH_OP_POP;
+                }
+                /*
+                 * Check is due to some gerber files has spurious empty lines.
+                 * (EagleCad of course).
+                 */
+                if (found_primitive) {
+                    ip->next = new_instruction(); /* XXX Check return value */
+                    ip       = ip->next;
+                    if (equate) {
+                        ip->opcode    = GERBV_OPCODE_PPOP;
+                        ip->data.ival = equate;
+                    } else {
+                        ip->opcode    = GERBV_OPCODE_PRIM;
+                        ip->data.ival = primitive;
+                    }
+                    equate          = 0;
+                    primitive       = 0;
+                    found_primitive = 0;
+                }
+                break;
+            case '=':
+                if (equate) {
+                    found_primitive = 1;
+                }
+                break;
+            case ',':
+                if (!found_primitive) {
+                    found_primitive = 1;
+                    break;
+                }
+                while (!MATH_OP_EMPTY) {
+                    ip->next   = new_instruction(); /* XXX Check return value */
+                    ip         = ip->next;
+                    ip->opcode = MATH_OP_POP;
+                }
+                comma = 1;
+                break;
+            case '+':
+                while ((!MATH_OP_EMPTY) && (math_op_prec(MATH_OP_TOP) >= math_op_prec(GERBV_OPCODE_ADD))) {
+                    ip->next   = new_instruction(); /* XXX Check return value */
+                    ip         = ip->next;
+                    ip->opcode = MATH_OP_POP;
+                }
+                MATH_OP_PUSH(GERBV_OPCODE_ADD);
+                comma = 1;
+                break;
+            case '-':
+                if (comma) {
+                    neg   = 1;
+                    comma = 0;
+                    break;
+                }
+                while ((!MATH_OP_EMPTY) && (math_op_prec(MATH_OP_TOP) >= math_op_prec(GERBV_OPCODE_SUB))) {
+                    ip->next   = new_instruction(); /* XXX Check return value */
+                    ip         = ip->next;
+                    ip->opcode = MATH_OP_POP;
+                }
+                MATH_OP_PUSH(GERBV_OPCODE_SUB);
+                break;
+            case '/':
+                while ((!MATH_OP_EMPTY) && (math_op_prec(MATH_OP_TOP) >= math_op_prec(GERBV_OPCODE_DIV))) {
+                    ip->next   = new_instruction(); /* XXX Check return value */
+                    ip         = ip->next;
+                    ip->opcode = MATH_OP_POP;
+                }
+                MATH_OP_PUSH(GERBV_OPCODE_DIV);
+                comma = 1;
+                break;
+            case 'X':
+            case 'x':
+                while ((!MATH_OP_EMPTY) && (math_op_prec(MATH_OP_TOP) >= math_op_prec(GERBV_OPCODE_MUL))) {
+                    ip->next   = new_instruction(); /* XXX Check return value */
+                    ip         = ip->next;
+                    ip->opcode = MATH_OP_POP;
+                }
+                MATH_OP_PUSH(GERBV_OPCODE_MUL);
+                comma = 1;
+                break;
+            case '0':
+                /*
+                 * Comments in aperture macros are a definition starting with
+                 * zero and ends with a '*'
+                 */
+                if (!found_primitive && (primitive == 0)) {
+                    /* Comment continues 'til next *, just throw it away */
+                    free(gerb_fgetstring(fd, '*'));
+                    c = gerb_fgetc(fd); /* Read the '*' */
+                    break;
+                }
+            case '1':
+            case '2':
+            case '3':
+            case '4':
+            case '5':
+            case '6':
+            case '7':
+            case '8':
+            case '9':
+            case '.':
+                /*
+                 * First number in an aperture macro describes the primitive
+                 * as a numerical value
+                 */
+                if (!found_primitive) {
+                    primitive = (primitive * 10) + (c - '0');
+                    break;
+                }
+                (void)gerb_ungetc(fd);
+                ip->next   = new_instruction(); /* XXX Check return value */
+                ip         = ip->next;
+                ip->opcode = GERBV_OPCODE_PUSH;
+                amacro->nuf_push++;
+                ip->data.fval = gerb_fgetdouble(fd);
+                if (neg)
+                    ip->data.fval = -ip->data.fval;
+                neg   = 0;
+                comma = 0;
+                break;
+            case '%':
+                gerb_ungetc(fd); /* Must return with % first in string
+                        since the main parser needs it */
+                return amacro;
+            default:
+                /* Whitespace */
+                break;
+        }
+        if (c == EOF) {
+            continueLoop = 0;
+        }
     }
-    free (amacro);
+    free(amacro);
     return NULL;
 }
 
-
-void 
-free_amacro(gerbv_amacro_t *amacro)
-{
-    gerbv_amacro_t *am1, *am2;
+void
+free_amacro(gerbv_amacro_t* amacro) {
+    gerbv_amacro_t *     am1, *am2;
     gerbv_instruction_t *instr1, *instr2;
-    
+
     am1 = amacro;
     while (am1 != NULL) {
-	free(am1->name);
-	am1->name = NULL;
+        free(am1->name);
+        am1->name = NULL;
 
-	instr1 = am1->program;
-	while (instr1 != NULL) {
-	    instr2 = instr1;
-	    instr1 = instr1->next;
-	    free(instr2);
-	    instr2 = NULL;
-	}
+        instr1 = am1->program;
+        while (instr1 != NULL) {
+            instr2 = instr1;
+            instr1 = instr1->next;
+            free(instr2);
+            instr2 = NULL;
+        }
 
-	am2 = am1;
-	am1 = am1->next;
-	free(am2);
-	am2 = NULL;
+        am2 = am1;
+        am1 = am1->next;
+        free(am2);
+        am2 = NULL;
     }
-	
+
     return;
 } /* free_amacro */
 
-
-void 
-print_program(gerbv_amacro_t *amacro)
-{
-    gerbv_instruction_t *ip;
+void
+print_program(gerbv_amacro_t* amacro) {
+    gerbv_instruction_t* ip;
 
     printf("Macroname [%s] :\n", amacro->name);
-    for (ip = amacro->program ; ip != NULL; ip = ip->next) {
-	switch(ip->opcode) {
-	case GERBV_OPCODE_NOP:
-	    printf(" NOP\n");
-	    break;
-	case GERBV_OPCODE_PUSH: 
-	    printf(" PUSH %f\n", ip->data.fval);
-	    break;
-	case GERBV_OPCODE_PPOP:
-	    printf(" PPOP %d\n", ip->data.ival);
-	    break;
-	case GERBV_OPCODE_PPUSH:
-	    printf(" PPUSH %d\n", ip->data.ival);
-	    break;
-	case GERBV_OPCODE_ADD:
-	    printf(" ADD\n");
-	    break;
-	case GERBV_OPCODE_SUB:
-	    printf(" SUB\n");
-	    break;
-	case GERBV_OPCODE_MUL:
-	    printf(" MUL\n");
-	    break;
-	case GERBV_OPCODE_DIV:
-	    printf(" DIV\n");
-	    break;
-	case GERBV_OPCODE_PRIM:
-	    printf(" PRIM %d\n", ip->data.ival);
-	    break;
-	default :
-	    printf("  ERROR!\n");
-	    break;
-	}
-	fflush(stdout);
+    for (ip = amacro->program; ip != NULL; ip = ip->next) {
+        switch (ip->opcode) {
+            case GERBV_OPCODE_NOP: printf(" NOP\n"); break;
+            case GERBV_OPCODE_PUSH: printf(" PUSH %f\n", ip->data.fval); break;
+            case GERBV_OPCODE_PPOP: printf(" PPOP %d\n", ip->data.ival); break;
+            case GERBV_OPCODE_PPUSH: printf(" PPUSH %d\n", ip->data.ival); break;
+            case GERBV_OPCODE_ADD: printf(" ADD\n"); break;
+            case GERBV_OPCODE_SUB: printf(" SUB\n"); break;
+            case GERBV_OPCODE_MUL: printf(" MUL\n"); break;
+            case GERBV_OPCODE_DIV: printf(" DIV\n"); break;
+            case GERBV_OPCODE_PRIM: printf(" PRIM %d\n", ip->data.ival); break;
+            default: printf("  ERROR!\n"); break;
+        }
+        fflush(stdout);
     }
 } /* print_program */
diff --git a/src/amacro.h b/src/amacro.h
index 3624c82..284c52d 100644
--- a/src/amacro.h
+++ b/src/amacro.h
@@ -36,18 +36,17 @@ extern "C" {
 /*
  * Parses the definition of an aperture macro
  */
-gerbv_amacro_t *parse_aperture_macro(gerb_file_t *fd);
+gerbv_amacro_t* parse_aperture_macro(gerb_file_t* fd);
 
 /*
  * Frees amacro struct completly
  */
-void free_amacro(gerbv_amacro_t *amacro);
+void free_amacro(gerbv_amacro_t* amacro);
 
 /*
  * Print out parsed aperture macro. For debugging purpose.
  */
-void print_program(gerbv_amacro_t *amacro);
-
+void print_program(gerbv_amacro_t* amacro);
 
 #ifdef __cplusplus
 }
diff --git a/src/attribute.c b/src/attribute.c
index 67a622d..77ba73a 100644
--- a/src/attribute.c
+++ b/src/attribute.c
@@ -51,492 +51,447 @@
 #include "attribute.h"
 #include "main.h"
 
-#define dprintf if(DEBUG) printf
-
-static int auto_uncheck_needed = 0;
-static GtkWidget * auto_uncheck_widget = NULL;
-static int * auto_uncheck_attr = NULL;
-static GtkWidget ** all_widgets = NULL;
-static int n_widgets;
-
-static void clear_auto()
-{
-  if( auto_uncheck_needed && auto_uncheck_widget != NULL && auto_uncheck_attr != NULL) {
-    /* disable this bit of code so we don't enter an endless loop */
-    auto_uncheck_needed = 0;
+#define dprintf \
+    if (DEBUG)  \
+    printf
+
+static int         auto_uncheck_needed = 0;
+static GtkWidget*  auto_uncheck_widget = NULL;
+static int*        auto_uncheck_attr   = NULL;
+static GtkWidget** all_widgets         = NULL;
+static int         n_widgets;
 
-    /* uncheck the "auto" toggle button */
-    gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (auto_uncheck_widget), 0);
+static void
+clear_auto() {
+    if (auto_uncheck_needed && auto_uncheck_widget != NULL && auto_uncheck_attr != NULL) {
+        /* disable this bit of code so we don't enter an endless loop */
+        auto_uncheck_needed = 0;
 
-    /* store that we have unchecked the "auto" toggle button */
-    *auto_uncheck_attr = 0;
+        /* uncheck the "auto" toggle button */
+        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(auto_uncheck_widget), 0);
 
-    /* re-enable this bit of code */
-    auto_uncheck_needed = 1;
-  }
+        /* store that we have unchecked the "auto" toggle button */
+        *auto_uncheck_attr = 0;
+
+        /* re-enable this bit of code */
+        auto_uncheck_needed = 1;
+    }
 }
 
 /* Callback for toggling a boolean attribute */
 static void
-set_flag_cb (GtkToggleButton * button, gboolean * flag)
-{
-  int i, f;
-
-  *flag = gtk_toggle_button_get_active (button);
-  
-  /* 
-   * if this is the "auto" button then set/clear the sensitivity of
-   * everything else.  Otherwise call the clear_auto() function 
-   */
-  if (auto_uncheck_widget == GTK_WIDGET (button)) {
-    f = *flag ? 0 : 1;
-    for (i = 1 ; i < n_widgets ; i++) {
-      gtk_widget_set_sensitive (all_widgets[i], f);
+set_flag_cb(GtkToggleButton* button, gboolean* flag) {
+    int i, f;
+
+    *flag = gtk_toggle_button_get_active(button);
+
+    /*
+     * if this is the "auto" button then set/clear the sensitivity of
+     * everything else.  Otherwise call the clear_auto() function
+     */
+    if (auto_uncheck_widget == GTK_WIDGET(button)) {
+        f = *flag ? 0 : 1;
+        for (i = 1; i < n_widgets; i++) {
+            gtk_widget_set_sensitive(all_widgets[i], f);
+        }
+    } else {
+        clear_auto();
     }
-  } else {
-    clear_auto ();
-  }
 }
 
 /* Callback for setting an integer value */
 static void
-intspinner_changed_cb (GtkWidget * spin_button, gpointer data)
-{
-  int *ival = data;
+intspinner_changed_cb(GtkWidget* spin_button, gpointer data) {
+    int* ival = data;
 
-  *ival = gtk_spin_button_get_value (GTK_SPIN_BUTTON (spin_button));
-  clear_auto ();
+    *ival = gtk_spin_button_get_value(GTK_SPIN_BUTTON(spin_button));
+    clear_auto();
 }
 
 /* Callback for setting a floating point value */
 static void
-dblspinner_changed_cb (GtkWidget * spin_button, gpointer data)
-{
-  double *dval = data;
+dblspinner_changed_cb(GtkWidget* spin_button, gpointer data) {
+    double* dval = data;
 
-  *dval = gtk_spin_button_get_value (GTK_SPIN_BUTTON (spin_button));
-  clear_auto ();
+    *dval = gtk_spin_button_get_value(GTK_SPIN_BUTTON(spin_button));
+    clear_auto();
 }
 
 /* Callback for setting an string value */
 static void
-entry_changed_cb (GtkEntry * entry, char **str)
-{
-  const gchar *s;
+entry_changed_cb(GtkEntry* entry, char** str) {
+    const gchar* s;
 
-  s = gtk_entry_get_text (entry);
+    s = gtk_entry_get_text(entry);
 
-  if (*str)
-    free (*str);
-  *str = strdup (s);
+    if (*str)
+        free(*str);
+    *str = strdup(s);
 
-  clear_auto ();
+    clear_auto();
 }
 
 /* Callback for setting an enum value */
 static void
-enum_changed_cb (GtkWidget * combo_box, int *val)
-{
-  gint active;
+enum_changed_cb(GtkWidget* combo_box, int* val) {
+    gint active;
 
-  active = gtk_combo_box_get_active (GTK_COMBO_BOX (combo_box));
-  *val = active;
+    active = gtk_combo_box_get_active(GTK_COMBO_BOX(combo_box));
+    *val   = active;
 
-  clear_auto ();
+    clear_auto();
 }
 
 /* Utility function for building a vbox with a text label */
 /* Written by Bill Wilson for PCB */
-static GtkWidget *
-ghid_category_vbox (GtkWidget * box, const gchar * category_header,
-		    gint header_pad,
-		    gint box_pad, gboolean pack_start, gboolean bottom_pad)
-{
-  GtkWidget *vbox, *vbox1, *hbox, *label;
-  gchar *s;
-
-  vbox = gtk_vbox_new (FALSE, 0);
-  if (pack_start)
-    gtk_box_pack_start (GTK_BOX (box), vbox, FALSE, FALSE, 0);
-  else
-    gtk_box_pack_end (GTK_BOX (box), vbox, FALSE, FALSE, 0);
-
-  if (category_header)
-    {
-      label = gtk_label_new (NULL);
-      s = g_strconcat ("<span weight=\"bold\">", category_header,
-		       "</span>", NULL);
-      gtk_label_set_markup (GTK_LABEL (label), s);
-      gtk_misc_set_alignment (GTK_MISC (label), 0.0, 0.5);
-      gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, header_pad);
-      g_free (s);
+static GtkWidget*
+ghid_category_vbox(
+    GtkWidget* box, const gchar* category_header, gint header_pad, gint box_pad, gboolean pack_start,
+    gboolean bottom_pad
+) {
+    GtkWidget *vbox, *vbox1, *hbox, *label;
+    gchar*     s;
+
+    vbox = gtk_vbox_new(FALSE, 0);
+    if (pack_start)
+        gtk_box_pack_start(GTK_BOX(box), vbox, FALSE, FALSE, 0);
+    else
+        gtk_box_pack_end(GTK_BOX(box), vbox, FALSE, FALSE, 0);
+
+    if (category_header) {
+        label = gtk_label_new(NULL);
+        s     = g_strconcat("<span weight=\"bold\">", category_header, "</span>", NULL);
+        gtk_label_set_markup(GTK_LABEL(label), s);
+        gtk_misc_set_alignment(GTK_MISC(label), 0.0, 0.5);
+        gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, header_pad);
+        g_free(s);
     }
 
-  hbox = gtk_hbox_new (FALSE, 0);
-  gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);
-  label = gtk_label_new ("     ");
-  gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 0);
-  vbox1 = gtk_vbox_new (FALSE, box_pad);
-  gtk_box_pack_start (GTK_BOX (hbox), vbox1, TRUE, TRUE, 0);
-
-  if (bottom_pad)
-    {
-      label = gtk_label_new ("");
-      gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 0);
+    hbox = gtk_hbox_new(FALSE, 0);
+    gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
+    label = gtk_label_new("     ");
+    gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);
+    vbox1 = gtk_vbox_new(FALSE, box_pad);
+    gtk_box_pack_start(GTK_BOX(hbox), vbox1, TRUE, TRUE, 0);
+
+    if (bottom_pad) {
+        label = gtk_label_new("");
+        gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
     }
-  return vbox1;
+    return vbox1;
 }
 
 /* Utility function for creating a spin button */
 /* Written by Bill Wilson for PCB */
 static void
-ghid_spin_button (GtkWidget * box, GtkWidget ** spin_button, gfloat value,
-		  gfloat low, gfloat high, gfloat step0, gfloat step1,
-		  gint digits, gint width,
-		  void (*cb_func) (), gpointer data, gboolean right_align,
-		  gchar * string)
-{
-  GtkWidget *hbox = NULL, *label, *spin_but;
-  GtkSpinButton *spin;
-  GtkAdjustment *adj;
-
-  if (string && box)
-    {
-      hbox = gtk_hbox_new (FALSE, 0);
-      gtk_box_pack_start (GTK_BOX (box), hbox, FALSE, FALSE, 2);
-      box = hbox;
+ghid_spin_button(
+    GtkWidget* box, GtkWidget** spin_button, gfloat value, gfloat low, gfloat high, gfloat step0, gfloat step1,
+    gint digits, gint width, void (*cb_func)(), gpointer data, gboolean right_align, gchar* string
+) {
+    GtkWidget *    hbox = NULL, *label, *spin_but;
+    GtkSpinButton* spin;
+    GtkAdjustment* adj;
+
+    if (string && box) {
+        hbox = gtk_hbox_new(FALSE, 0);
+        gtk_box_pack_start(GTK_BOX(box), hbox, FALSE, FALSE, 2);
+        box = hbox;
     }
-  adj = (GtkAdjustment *) gtk_adjustment_new (value,
-					      low, high, step0, step1, 0.0);
-  spin_but = gtk_spin_button_new (adj, 0.5, digits);
-  if (spin_button)
-    *spin_button = spin_but;
-  if (width > 0)
-    gtk_widget_set_size_request (spin_but, width, -1);
-  spin = GTK_SPIN_BUTTON (spin_but);
-  gtk_spin_button_set_numeric (spin, TRUE);
-  if (data == NULL)
-    data = (gpointer) spin;
-  if (cb_func)
-    g_signal_connect (G_OBJECT (spin_but), "value_changed",
-		      G_CALLBACK (cb_func), data);
-  if (box)
-    {
-      if (right_align && string)
-	{
-	  label = gtk_label_new (string);
-	  gtk_misc_set_alignment (GTK_MISC (label), 1.0, 0.5);
-	  gtk_box_pack_start (GTK_BOX (box), label, TRUE, TRUE, 2);
-	}
-      gtk_box_pack_start (GTK_BOX (box), spin_but, FALSE, FALSE, 2);
-      if (!right_align && string)
-	{
-	  label = gtk_label_new (string);
-	  gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);
-	  gtk_box_pack_start (GTK_BOX (box), label, TRUE, TRUE, 2);
-	}
+    adj      = (GtkAdjustment*)gtk_adjustment_new(value, low, high, step0, step1, 0.0);
+    spin_but = gtk_spin_button_new(adj, 0.5, digits);
+    if (spin_button)
+        *spin_button = spin_but;
+    if (width > 0)
+        gtk_widget_set_size_request(spin_but, width, -1);
+    spin = GTK_SPIN_BUTTON(spin_but);
+    gtk_spin_button_set_numeric(spin, TRUE);
+    if (data == NULL)
+        data = (gpointer)spin;
+    if (cb_func)
+        g_signal_connect(G_OBJECT(spin_but), "value_changed", G_CALLBACK(cb_func), data);
+    if (box) {
+        if (right_align && string) {
+            label = gtk_label_new(string);
+            gtk_misc_set_alignment(GTK_MISC(label), 1.0, 0.5);
+            gtk_box_pack_start(GTK_BOX(box), label, TRUE, TRUE, 2);
+        }
+        gtk_box_pack_start(GTK_BOX(box), spin_but, FALSE, FALSE, 2);
+        if (!right_align && string) {
+            label = gtk_label_new(string);
+            gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
+            gtk_box_pack_start(GTK_BOX(box), label, TRUE, TRUE, 2);
+        }
     }
 }
 
 /* Utility function for creating a check button */
 /* Written by Bill Wilson for PCB */
 static void
-ghid_check_button_connected (GtkWidget * box,
-			     GtkWidget ** button,
-			     gboolean active,
-			     gboolean pack_start,
-			     gboolean expand,
-			     gboolean fill,
-			     gint pad,
-			     void (*cb_func) (),
-			     gpointer data, gchar * string)
-{
-  GtkWidget *b;
-
-  if (!string)
-    return;
-  b = gtk_check_button_new_with_label (string);
-  gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (b), active);
-  if (box && pack_start)
-    gtk_box_pack_start (GTK_BOX (box), b, expand, fill, pad);
-  else if (box && !pack_start)
-    gtk_box_pack_end (GTK_BOX (box), b, expand, fill, pad);
-
-  if (cb_func)
-    gtk_signal_connect (GTK_OBJECT (b), "clicked",
-			GTK_SIGNAL_FUNC (cb_func), data);
-  if (button)
-    *button = b;
+ghid_check_button_connected(
+    GtkWidget* box, GtkWidget** button, gboolean active, gboolean pack_start, gboolean expand, gboolean fill, gint pad,
+    void (*cb_func)(), gpointer data, gchar* string
+) {
+    GtkWidget* b;
+
+    if (!string)
+        return;
+    b = gtk_check_button_new_with_label(string);
+    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(b), active);
+    if (box && pack_start)
+        gtk_box_pack_start(GTK_BOX(box), b, expand, fill, pad);
+    else if (box && !pack_start)
+        gtk_box_pack_end(GTK_BOX(box), b, expand, fill, pad);
+
+    if (cb_func)
+        gtk_signal_connect(GTK_OBJECT(b), "clicked", GTK_SIGNAL_FUNC(cb_func), data);
+    if (button)
+        *button = b;
 }
 
-/* 
+/*
  * The following function is taken almost directly from
  * ghid_attribte_dialog() from pcb.  It is a generic attribute editor
  * gui where the dialog is built on the fly based on a passed in
  * attribute list.
- * 
+ *
  * Written by Dan McMahill
  */
 int
-attribute_interface_dialog (gerbv_HID_Attribute * attrs,
-		       int n_attrs, gerbv_HID_Attr_Val * results,
-		       const char * title,
-		       const char * descr)
-{
-  GtkWidget *dialog, *main_vbox, *vbox, *vbox1, *hbox, *entry;
-  GtkWidget *combo;
-  GtkWidget *widget;
-  int i, j;
-  GtkTooltips *tips;
-  int rc = 0;
-  int set_auto_uncheck = 0;
-  int sen = TRUE;
-
-  /* 
-   * Store how many widgets we'll have in our dialog and keep track of
-   * them.  Be sure to free up our list if one existed already.
-   */
-  n_widgets = n_attrs;
-  if (all_widgets != NULL)
-    free (all_widgets);
-
-  all_widgets = (GtkWidget **) malloc (n_widgets * sizeof(GtkWidget *));
-  if (all_widgets == NULL) {
-    fprintf (stderr, "%s():  malloc failed for an array of size %d\n", __FUNCTION__, n_widgets);
-    exit (1);
-  }
-
-  dprintf ("%s(%p, %d, %p, \"%s\", \"%s\")\n", __FUNCTION__, attrs, n_attrs, results, title, descr);
-
-  auto_uncheck_needed = 0;
-  auto_uncheck_widget = NULL;
-  auto_uncheck_attr = NULL;
-
-  tips = gtk_tooltips_new ();
-
-  dialog = gtk_dialog_new_with_buttons (title,
-					GTK_WINDOW (screen.win.topLevelWindow),
-					GTK_DIALOG_MODAL
-					| GTK_DIALOG_DESTROY_WITH_PARENT,
-					GTK_STOCK_CANCEL, GTK_RESPONSE_NONE,
-					GTK_STOCK_OK, GTK_RESPONSE_OK, NULL);
-  gtk_window_set_wmclass (GTK_WINDOW (dialog), "gerbv_attribute_editor", _("gerbv"));
-
-  main_vbox = gtk_vbox_new (FALSE, 6);
-  gtk_container_set_border_width (GTK_CONTAINER (main_vbox), 6);
-  gtk_container_add (GTK_CONTAINER (GTK_DIALOG (dialog)->vbox), main_vbox);
-
-  vbox = ghid_category_vbox (main_vbox, descr != NULL ? descr : "",
-			     4, 2, TRUE, TRUE);
-
-  /* 
-   * Iterate over all the attributes and build up a dialog box
-   * that lets us control all of the options.  By doing things this
-   * way, any changes to the attributes or if there is a new list of
-   * attributes, everything will automatically be reflected in this
-   * dialog box. 
-   */
-  for (j = 0; j < n_attrs; j++)
-      {
-	  dprintf ("%s(): adding attribute #%d\n", __func__, j);
-	  switch (attrs[j].type)
-	      {
-	      case HID_Label:
-		  widget = gtk_label_new (_(attrs[j].name));
-		  gtk_box_pack_start (GTK_BOX (vbox), widget, FALSE, FALSE, 0);
-		  gtk_tooltips_set_tip (tips, widget, _(attrs[j].help_text), NULL);
-		  break;
-		  
-	      case HID_Integer:
-		  hbox = gtk_hbox_new (FALSE, 4);
-		  gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);
-		  
-		  /* 
-		   * FIXME 
-		   * need to pick the "digits" argument based on min/max
-		   * values
-		   */
-		  ghid_spin_button (hbox, &widget, attrs[j].default_val.int_value,
-				    attrs[j].min_val, attrs[j].max_val, 1.0, 1.0, 0, 0,
-				    intspinner_changed_cb,
-				    &(attrs[j].default_val.int_value), FALSE, NULL);
-		  
-		  gtk_tooltips_set_tip (tips, widget, _(attrs[j].help_text), NULL);
-		  all_widgets[j] = widget;
-		  
-		  widget = gtk_label_new (_(attrs[j].name));
-		  gtk_box_pack_start (GTK_BOX (hbox), widget, FALSE, FALSE, 0);
-		  break;
-		  
-	      case HID_Real:
-		  hbox = gtk_hbox_new (FALSE, 4);
-		  gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);
-		  
-		  /* 
-		   * FIXME 
-		   * need to pick the "digits" and step size argument more
-		   * intelligently
-		   */
-		  ghid_spin_button (hbox, &widget, attrs[j].default_val.real_value,
-				    attrs[j].min_val, attrs[j].max_val, 0.01, 0.01, 3,
-				    0, 
-				    dblspinner_changed_cb,
-				    &(attrs[j].default_val.real_value), FALSE, NULL);
-		  
-		  gtk_tooltips_set_tip (tips, widget, _(attrs[j].help_text), NULL);
-		  all_widgets[j] = widget;
-
-		  widget = gtk_label_new (_(attrs[j].name));
-		  gtk_box_pack_start (GTK_BOX (hbox), widget, FALSE, FALSE, 0);
-		  break;
-		  
-	      case HID_String:
-		  hbox = gtk_hbox_new (FALSE, 4);
-		  gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);
-		  
-		  entry = gtk_entry_new ();
-		  gtk_box_pack_start (GTK_BOX (hbox), entry, FALSE, FALSE, 0);
-		  gtk_entry_set_text (GTK_ENTRY (entry),
-				      attrs[j].default_val.str_value);
-		  gtk_tooltips_set_tip (tips, entry, _(attrs[j].help_text), NULL);
-		  g_signal_connect (G_OBJECT (entry), "changed",
-				    G_CALLBACK (entry_changed_cb),
-				    &(attrs[j].default_val.str_value));
-		  all_widgets[j] = entry;
-
-		  widget = gtk_label_new (_(attrs[j].name));
-		  gtk_box_pack_start (GTK_BOX (hbox), widget, FALSE, FALSE, 0);
-		  break;
-		  
-	      case HID_Boolean:
-		  /* put this in a check button */
-		  ghid_check_button_connected (vbox, &widget,
-					       attrs[j].default_val.int_value,
-					       TRUE, FALSE, FALSE, 0, set_flag_cb,
-					       &(attrs[j].default_val.int_value),
-					       _(attrs[j].name));
-		  gtk_tooltips_set_tip (tips, widget, _(attrs[j].help_text), NULL);
-
-		  /* 
-		   * This is an ugly ugly ugly hack....  If this is
-		   * the first in our list of attributes *and* it has a
-		   * magic name of "autodetect" then we'll remember it and
-		   * all of the other callbacks will cause this button to
-		   * come unchecked. Among the other nastiness
-		   * involved here, this dialog is now *required* to
-		   * be modal since we are using a static variable.
-		   * To avoid that, we need a new data type that can hold
-		   * more state information.  Ideally we need a better
-		   * way to capture dependencies between attributes to
-		   * allow arbitrary relationships instead of just this
-		   * one single "magic" one.
-		   */
-		  if (j == 0 && strcmp(attrs[j].name, "autodetect") == 0) {
-		    set_auto_uncheck = 1;
-		    auto_uncheck_widget = widget;
-		    auto_uncheck_attr = &(attrs[j].default_val.int_value);
-
-		    /* if the "auto" button in checked then don't let
-		     * anything else be sensitive.
-		    */
-		       
-		    if (attrs[j].default_val.int_value)
-		      sen = FALSE;
-		  }
-		  all_widgets[j] = widget;
-
-		  break;
-		  
-	      case HID_Enum:
-		  hbox = gtk_hbox_new (FALSE, 4);
-		  gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);
-		  
-		  /* 
-		   * We have to put the combo_box inside of an event_box in
-		   * order for tooltips to work.
-		   */
-		  widget = gtk_event_box_new ();
-		  gtk_tooltips_set_tip (tips, widget, _(attrs[j].help_text), NULL);
-		  gtk_box_pack_start (GTK_BOX (hbox), widget, FALSE, FALSE, 0);
-		  
-		  combo = gtk_combo_box_new_text ();
-		  gtk_container_add (GTK_CONTAINER (widget), combo);
-		  g_signal_connect (G_OBJECT (combo), "changed",
-				    G_CALLBACK (enum_changed_cb),
-				    &(attrs[j].default_val.int_value));
-		  
-
-		  /* 
-		   * Iterate through each value and add them to the
-		   * combo box
-		   */
-		  i = 0;
-		  while (attrs[j].enumerations[i])
-		      {
-			  gtk_combo_box_append_text (GTK_COMBO_BOX (combo),
-						     _(attrs[j].enumerations[i]));
-			  i++;
-		      }
-		  gtk_combo_box_set_active (GTK_COMBO_BOX (combo),
-					    attrs[j].default_val.int_value);
-		  all_widgets[j] = combo;
-	  
-		  widget = gtk_label_new (_(attrs[j].name));
-		  gtk_box_pack_start (GTK_BOX (hbox), widget, FALSE, FALSE, 0);
-		  break;
-
-	      case HID_Mixed:
-		  dprintf ("HID_Mixed\n");
-		  break;
-
-	      case HID_Path:
-		  vbox1 = ghid_category_vbox (vbox, _(attrs[j].name), 4, 2, TRUE, TRUE);
-		  entry = gtk_entry_new ();
-		  gtk_box_pack_start (GTK_BOX (vbox1), entry, FALSE, FALSE, 0);
-		  gtk_entry_set_text (GTK_ENTRY (entry),
-				      attrs[j].default_val.str_value);
-		  g_signal_connect (G_OBJECT (entry), "changed",
-				    G_CALLBACK (entry_changed_cb),
-				    &(attrs[j].default_val.str_value));
-
-		  gtk_tooltips_set_tip (tips, entry, _(attrs[j].help_text), NULL);
-		  all_widgets[j] = entry;
-		  break;
-
-	      default:
-		  fprintf (stderr, _("%s: unknown type of HID attribute\n"), __FUNCTION__);
-		  break;
-	      }
-      }
-
-
-  gtk_widget_show_all (dialog);
-  auto_uncheck_needed = set_auto_uncheck;
-
-  /* 
-   * part of the "auto" hack.  Make everything sensitive or
-   * insensitive based on the state of the "auto" toggle button (if it
-   * exists)
-   */
-  for (j = 1; j < n_widgets ; j++) {
-    gtk_widget_set_sensitive (all_widgets[j], sen);
-  }
-  if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_OK)
-      {
-	  /* copy over the results */
-	  for (i = 0; i < n_attrs; i++)
-	      {
-		  results[i] = attrs[i].default_val;
-		  if (results[i].str_value)
-		      results[i].str_value = strdup (results[i].str_value);
-	      }
-	  rc = 0;
-      }
-  else
-      rc = 1;
-
-  gtk_widget_destroy (dialog);
-
-  return rc;
-}
+attribute_interface_dialog(
+    gerbv_HID_Attribute* attrs, int n_attrs, gerbv_HID_Attr_Val* results, const char* title, const char* descr
+) {
+    GtkWidget *  dialog, *main_vbox, *vbox, *vbox1, *hbox, *entry;
+    GtkWidget*   combo;
+    GtkWidget*   widget;
+    int          i, j;
+    GtkTooltips* tips;
+    int          rc               = 0;
+    int          set_auto_uncheck = 0;
+    int          sen              = TRUE;
+
+    /*
+     * Store how many widgets we'll have in our dialog and keep track of
+     * them.  Be sure to free up our list if one existed already.
+     */
+    n_widgets = n_attrs;
+    if (all_widgets != NULL)
+        free(all_widgets);
+
+    all_widgets = (GtkWidget**)malloc(n_widgets * sizeof(GtkWidget*));
+    if (all_widgets == NULL) {
+        fprintf(stderr, "%s():  malloc failed for an array of size %d\n", __FUNCTION__, n_widgets);
+        exit(1);
+    }
+
+    dprintf("%s(%p, %d, %p, \"%s\", \"%s\")\n", __FUNCTION__, attrs, n_attrs, results, title, descr);
+
+    auto_uncheck_needed = 0;
+    auto_uncheck_widget = NULL;
+    auto_uncheck_attr   = NULL;
+
+    tips = gtk_tooltips_new();
+
+    dialog = gtk_dialog_new_with_buttons(
+        title, GTK_WINDOW(screen.win.topLevelWindow), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
+        GTK_STOCK_CANCEL, GTK_RESPONSE_NONE, GTK_STOCK_OK, GTK_RESPONSE_OK, NULL
+    );
+    gtk_window_set_wmclass(GTK_WINDOW(dialog), "gerbv_attribute_editor", _("gerbv"));
+
+    main_vbox = gtk_vbox_new(FALSE, 6);
+    gtk_container_set_border_width(GTK_CONTAINER(main_vbox), 6);
+    gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), main_vbox);
+
+    vbox = ghid_category_vbox(main_vbox, descr != NULL ? descr : "", 4, 2, TRUE, TRUE);
+
+    /*
+     * Iterate over all the attributes and build up a dialog box
+     * that lets us control all of the options.  By doing things this
+     * way, any changes to the attributes or if there is a new list of
+     * attributes, everything will automatically be reflected in this
+     * dialog box.
+     */
+    for (j = 0; j < n_attrs; j++) {
+        dprintf("%s(): adding attribute #%d\n", __func__, j);
+        switch (attrs[j].type) {
+            case HID_Label:
+                widget = gtk_label_new(_(attrs[j].name));
+                gtk_box_pack_start(GTK_BOX(vbox), widget, FALSE, FALSE, 0);
+                gtk_tooltips_set_tip(tips, widget, _(attrs[j].help_text), NULL);
+                break;
+
+            case HID_Integer:
+                hbox = gtk_hbox_new(FALSE, 4);
+                gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
+
+                /*
+                 * FIXME
+                 * need to pick the "digits" argument based on min/max
+                 * values
+                 */
+                ghid_spin_button(
+                    hbox, &widget, attrs[j].default_val.int_value, attrs[j].min_val, attrs[j].max_val, 1.0, 1.0, 0, 0,
+                    intspinner_changed_cb, &(attrs[j].default_val.int_value), FALSE, NULL
+                );
+
+                gtk_tooltips_set_tip(tips, widget, _(attrs[j].help_text), NULL);
+                all_widgets[j] = widget;
+
+                widget = gtk_label_new(_(attrs[j].name));
+                gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, FALSE, 0);
+                break;
+
+            case HID_Real:
+                hbox = gtk_hbox_new(FALSE, 4);
+                gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
+
+                /*
+                 * FIXME
+                 * need to pick the "digits" and step size argument more
+                 * intelligently
+                 */
+                ghid_spin_button(
+                    hbox, &widget, attrs[j].default_val.real_value, attrs[j].min_val, attrs[j].max_val, 0.01, 0.01, 3,
+                    0, dblspinner_changed_cb, &(attrs[j].default_val.real_value), FALSE, NULL
+                );
+
+                gtk_tooltips_set_tip(tips, widget, _(attrs[j].help_text), NULL);
+                all_widgets[j] = widget;
+
+                widget = gtk_label_new(_(attrs[j].name));
+                gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, FALSE, 0);
+                break;
+
+            case HID_String:
+                hbox = gtk_hbox_new(FALSE, 4);
+                gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
+
+                entry = gtk_entry_new();
+                gtk_box_pack_start(GTK_BOX(hbox), entry, FALSE, FALSE, 0);
+                gtk_entry_set_text(GTK_ENTRY(entry), attrs[j].default_val.str_value);
+                gtk_tooltips_set_tip(tips, entry, _(attrs[j].help_text), NULL);
+                g_signal_connect(
+                    G_OBJECT(entry), "changed", G_CALLBACK(entry_changed_cb), &(attrs[j].default_val.str_value)
+                );
+                all_widgets[j] = entry;
+
+                widget = gtk_label_new(_(attrs[j].name));
+                gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, FALSE, 0);
+                break;
+
+            case HID_Boolean:
+                /* put this in a check button */
+                ghid_check_button_connected(
+                    vbox, &widget, attrs[j].default_val.int_value, TRUE, FALSE, FALSE, 0, set_flag_cb,
+                    &(attrs[j].default_val.int_value), _(attrs[j].name)
+                );
+                gtk_tooltips_set_tip(tips, widget, _(attrs[j].help_text), NULL);
+
+                /*
+                 * This is an ugly ugly ugly hack....  If this is
+                 * the first in our list of attributes *and* it has a
+                 * magic name of "autodetect" then we'll remember it and
+                 * all of the other callbacks will cause this button to
+                 * come unchecked. Among the other nastiness
+                 * involved here, this dialog is now *required* to
+                 * be modal since we are using a static variable.
+                 * To avoid that, we need a new data type that can hold
+                 * more state information.  Ideally we need a better
+                 * way to capture dependencies between attributes to
+                 * allow arbitrary relationships instead of just this
+                 * one single "magic" one.
+                 */
+                if (j == 0 && strcmp(attrs[j].name, "autodetect") == 0) {
+                    set_auto_uncheck    = 1;
+                    auto_uncheck_widget = widget;
+                    auto_uncheck_attr   = &(attrs[j].default_val.int_value);
+
+                    /* if the "auto" button in checked then don't let
+                     * anything else be sensitive.
+                     */
+
+                    if (attrs[j].default_val.int_value)
+                        sen = FALSE;
+                }
+                all_widgets[j] = widget;
+
+                break;
+
+            case HID_Enum:
+                hbox = gtk_hbox_new(FALSE, 4);
+                gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
+
+                /*
+                 * We have to put the combo_box inside of an event_box in
+                 * order for tooltips to work.
+                 */
+                widget = gtk_event_box_new();
+                gtk_tooltips_set_tip(tips, widget, _(attrs[j].help_text), NULL);
+                gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, FALSE, 0);
+
+                combo = gtk_combo_box_new_text();
+                gtk_container_add(GTK_CONTAINER(widget), combo);
+                g_signal_connect(
+                    G_OBJECT(combo), "changed", G_CALLBACK(enum_changed_cb), &(attrs[j].default_val.int_value)
+                );
+
+                /*
+                 * Iterate through each value and add them to the
+                 * combo box
+                 */
+                i = 0;
+                while (attrs[j].enumerations[i]) {
+                    gtk_combo_box_append_text(GTK_COMBO_BOX(combo), _(attrs[j].enumerations[i]));
+                    i++;
+                }
+                gtk_combo_box_set_active(GTK_COMBO_BOX(combo), attrs[j].default_val.int_value);
+                all_widgets[j] = combo;
+
+                widget = gtk_label_new(_(attrs[j].name));
+                gtk_box_pack_start(GTK_BOX(hbox), widget, FALSE, FALSE, 0);
+                break;
+
+            case HID_Mixed: dprintf("HID_Mixed\n"); break;
+
+            case HID_Path:
+                vbox1 = ghid_category_vbox(vbox, _(attrs[j].name), 4, 2, TRUE, TRUE);
+                entry = gtk_entry_new();
+                gtk_box_pack_start(GTK_BOX(vbox1), entry, FALSE, FALSE, 0);
+                gtk_entry_set_text(GTK_ENTRY(entry), attrs[j].default_val.str_value);
+                g_signal_connect(
+                    G_OBJECT(entry), "changed", G_CALLBACK(entry_changed_cb), &(attrs[j].default_val.str_value)
+                );
+
+                gtk_tooltips_set_tip(tips, entry, _(attrs[j].help_text), NULL);
+                all_widgets[j] = entry;
+                break;
+
+            default: fprintf(stderr, _("%s: unknown type of HID attribute\n"), __FUNCTION__); break;
+        }
+    }
+
+    gtk_widget_show_all(dialog);
+    auto_uncheck_needed = set_auto_uncheck;
 
+    /*
+     * part of the "auto" hack.  Make everything sensitive or
+     * insensitive based on the state of the "auto" toggle button (if it
+     * exists)
+     */
+    for (j = 1; j < n_widgets; j++) {
+        gtk_widget_set_sensitive(all_widgets[j], sen);
+    }
+    if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) {
+        /* copy over the results */
+        for (i = 0; i < n_attrs; i++) {
+            results[i] = attrs[i].default_val;
+            if (results[i].str_value)
+                results[i].str_value = strdup(results[i].str_value);
+        }
+        rc = 0;
+    } else
+        rc = 1;
+
+    gtk_widget_destroy(dialog);
+
+    return rc;
+}
diff --git a/src/attribute.h b/src/attribute.h
index 5e066de..0d088c6 100644
--- a/src/attribute.h
+++ b/src/attribute.h
@@ -36,12 +36,9 @@
 extern "C" {
 #endif
 
-int
-attribute_interface_dialog (gerbv_HID_Attribute *, int, gerbv_HID_Attr_Val *, 
-			    const char *,const char *);
+int attribute_interface_dialog(gerbv_HID_Attribute*, int, gerbv_HID_Attr_Val*, const char*, const char*);
 
-void
-attribute_merge (gerbv_HID_Attribute *, int, gerbv_HID_Attribute *, int);
+void attribute_merge(gerbv_HID_Attribute*, int, gerbv_HID_Attribute*, int);
 
 #ifdef __cplusplus
 }
diff --git a/src/callbacks.c b/src/callbacks.c
index 6b4c90e..5475ac8 100644
--- a/src/callbacks.c
+++ b/src/callbacks.c
@@ -30,7 +30,7 @@
 #include "drill.h"
 
 #if !defined(WIN32) && !defined(QUARTZ)
-# include <gdk/gdkx.h>
+#include <gdk/gdkx.h>
 #endif
 
 #ifdef HAVE_STDLIB_H
@@ -65,4628 +65,4165 @@
 
 #include "draw.h"
 #ifdef WIN32
-# include <cairo-win32.h>
+#include <cairo-win32.h>
 #elif QUARTZ
-# include <cairo-quartz.h>
+#include <cairo-quartz.h>
 #else
-# include <cairo-xlib.h>
+#include <cairo-xlib.h>
 #endif
 
-
-#define dprintf if(DEBUG) printf
+#define dprintf \
+    if (DEBUG)  \
+    printf
 
 /* This default extension should really not be changed, but if it absolutely
  * must change, the ../win32/gerbv.nsi.in *must* be changed to reflect that.
  * Just grep for the extension (gvp) and change it in two places in that file.
  */
 #define GERBV_PROJECT_FILE_EXT ".gvp"
-const char *gerbv_project_file_name = N_("Gerbv Project");
-const char *gerbv_project_file_pat = "*" GERBV_PROJECT_FILE_EXT;
+const char* gerbv_project_file_name = N_("Gerbv Project");
+const char* gerbv_project_file_pat  = "*" GERBV_PROJECT_FILE_EXT;
 
-static gint callbacks_get_selected_row_index (void);
-static void callbacks_units_changed (gerbv_gui_unit_t unit);
-static void callbacks_update_statusbar_coordinates (gint x, gint y);
-static void callbacks_update_ruler_scales (void);
-static void callbacks_render_type_changed (void);
-static void show_no_layers_warning (void);
+static gint callbacks_get_selected_row_index(void);
+static void callbacks_units_changed(gerbv_gui_unit_t unit);
+static void callbacks_update_statusbar_coordinates(gint x, gint y);
+static void callbacks_update_ruler_scales(void);
+static void callbacks_render_type_changed(void);
+static void show_no_layers_warning(void);
 
-static double screen_units(double);
-static const char *screen_units_str(void);
+static double      screen_units(double);
+static const char* screen_units_str(void);
 
 static double line_length(double, double, double, double);
 static double arc_length(double, double);
 
-static void aperture_state_report (gerbv_net_t *,
-		gerbv_image_t *, gerbv_project_t *);
-static void aperture_report(gerbv_aperture_t *[], int,
-		double, double, gerbv_image_t *, gerbv_project_t *);
-static void drill_report(gerbv_aperture_t *[], int);
-static void parea_report(gerbv_net_t *,
-		gerbv_image_t *, gerbv_project_t *);
-static void net_layer_file_report(gerbv_net_t *,
-		gerbv_image_t *, gerbv_project_t *);
-static void analyze_window_size_restore(GtkWidget *);
-static void analyze_window_size_store(GtkWidget *, gpointer);
-
-static void update_selected_object_message (gboolean userTriedToSelect);
-
-
-gchar *utf8_strncpy(gchar *dst, const gchar *src, gsize byte_len)
-{
-	/* -1 for '\0' in buffer */
-	glong char_len = g_utf8_strlen(src, byte_len - 1);
-	return g_utf8_strncpy(dst, src, char_len);
+static void aperture_state_report(gerbv_net_t*, gerbv_image_t*, gerbv_project_t*);
+static void aperture_report(gerbv_aperture_t*[], int, double, double, gerbv_image_t*, gerbv_project_t*);
+static void drill_report(gerbv_aperture_t*[], int);
+static void parea_report(gerbv_net_t*, gerbv_image_t*, gerbv_project_t*);
+static void net_layer_file_report(gerbv_net_t*, gerbv_image_t*, gerbv_project_t*);
+static void analyze_window_size_restore(GtkWidget*);
+static void analyze_window_size_store(GtkWidget*, gpointer);
+
+static void update_selected_object_message(gboolean userTriedToSelect);
+
+gchar*
+utf8_strncpy(gchar* dst, const gchar* src, gsize byte_len) {
+    /* -1 for '\0' in buffer */
+    glong char_len = g_utf8_strlen(src, byte_len - 1);
+    return g_utf8_strncpy(dst, src, char_len);
 }
 
-void utf8_snprintf(gchar *dst, gsize byte_len, const gchar *fmt, ...)
-{
-	va_list ap;
-
-	va_start(ap, fmt);
-	gchar *str = g_strdup_vprintf(fmt, ap); 
-	va_end(ap);
-	utf8_strncpy(dst, str, byte_len);
-	g_free(str);
+void
+utf8_snprintf(gchar* dst, gsize byte_len, const gchar* fmt, ...) {
+    va_list ap;
+
+    va_start(ap, fmt);
+    gchar* str = g_strdup_vprintf(fmt, ap);
+    va_end(ap);
+    utf8_strncpy(dst, str, byte_len);
+    g_free(str);
 }
 
 /* --------------------------------------------------------- */
 
-static void show_no_layers_warning (void) {
-	gchar *str = g_new(gchar, MAX_DISTLEN);
-	utf8_strncpy(str, _("No layers are currently loaded. A layer must be loaded first."), MAX_DISTLEN - 7);
-	utf8_snprintf(screen.statusbar.diststr, MAX_DISTLEN, "<b>%s</b>", str);
-	g_free(str);
-		
-	callbacks_update_statusbar();
+static void
+show_no_layers_warning(void) {
+    gchar* str = g_new(gchar, MAX_DISTLEN);
+    utf8_strncpy(str, _("No layers are currently loaded. A layer must be loaded first."), MAX_DISTLEN - 7);
+    utf8_snprintf(screen.statusbar.diststr, MAX_DISTLEN, "<b>%s</b>", str);
+    g_free(str);
+
+    callbacks_update_statusbar();
 }
 
 /* --------------------------------------------------------- */
 /**
-  * The file -> new menu item was selected.  Create new
-  * project.
-  *
-  */
+ * The file -> new menu item was selected.  Create new
+ * project.
+ *
+ */
 void
-callbacks_new_project_activate (GtkMenuItem *menuitem, gpointer user_data)
-{
-	if (mainProject->last_loaded >= 0) {
-		if (!interface_get_alert_dialog_response (
-			_("Do you want to close any open layers "
-			"and start a new project?"),
-			_("Starting a new project will cause all currently "
-			"open layers to be closed. Any unsaved changes "
-			"will be lost."),
-			FALSE, NULL, GTK_STOCK_CLOSE, GTK_STOCK_CANCEL))
-			return;
-	}
-	/* Unload all layers and then clear layer window */
-	gerbv_unload_all_layers (mainProject);
-	callbacks_update_layer_tree ();
-	selection_clear (&screen.selectionInfo);
-	update_selected_object_message (FALSE);
-	
-	/* Destroy project info */
-	if (mainProject->project) {
-	    g_free(mainProject->project);
-	    mainProject->project = NULL;
-	}
-	render_refresh_rendered_image_on_screen();
-}
+callbacks_new_project_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    if (mainProject->last_loaded >= 0) {
+        if (!interface_get_alert_dialog_response(
+                _("Do you want to close any open layers "
+                  "and start a new project?"),
+                _("Starting a new project will cause all currently "
+                  "open layers to be closed. Any unsaved changes "
+                  "will be lost."),
+                FALSE, NULL, GTK_STOCK_CLOSE, GTK_STOCK_CANCEL
+            ))
+            return;
+    }
+    /* Unload all layers and then clear layer window */
+    gerbv_unload_all_layers(mainProject);
+    callbacks_update_layer_tree();
+    selection_clear(&screen.selectionInfo);
+    update_selected_object_message(FALSE);
 
+    /* Destroy project info */
+    if (mainProject->project) {
+        g_free(mainProject->project);
+        mainProject->project = NULL;
+    }
+    render_refresh_rendered_image_on_screen();
+}
 
 /* --------------------------------------------------------- */
 /**
-  * The file -> open menu item was selected.  Open a
-  * project file.
-  *
-  */
-void open_project(char *project_filename)
-{
-
-/* TODO: check if layers is modified and show it to user. */
-
-	if (mainProject->last_loaded >= 0
-	&&  !interface_get_alert_dialog_response (
-		_("Do you want to close any open layers and load "
-		"an existing project?"),
-		_("Loading a project will cause all currently open "
-		"layers to be closed. Any unsaved changes "
-		"will be lost."),
-		FALSE, NULL, GTK_STOCK_CLOSE, GTK_STOCK_CANCEL)) {
-
-			return;
-	}
-
-	/* Update the last folder */
-	g_free (mainProject->path);
-	mainProject->path = g_strdup(project_filename);
-
-	gerbv_unload_all_layers (mainProject);
-	main_open_project_from_filename (mainProject, project_filename);
-}
+ * The file -> open menu item was selected.  Open a
+ * project file.
+ *
+ */
+void
+open_project(char* project_filename) {
 
+    /* TODO: check if layers is modified and show it to user. */
+
+    if (mainProject->last_loaded >= 0
+        && !interface_get_alert_dialog_response(
+            _("Do you want to close any open layers and load "
+              "an existing project?"),
+            _("Loading a project will cause all currently open "
+              "layers to be closed. Any unsaved changes "
+              "will be lost."),
+            FALSE, NULL, GTK_STOCK_CLOSE, GTK_STOCK_CANCEL
+        )) {
+
+        return;
+    }
+
+    /* Update the last folder */
+    g_free(mainProject->path);
+    mainProject->path = g_strdup(project_filename);
+
+    gerbv_unload_all_layers(mainProject);
+    main_open_project_from_filename(mainProject, project_filename);
+}
 
 /* --------------------------------------------------------- */
 /**
-  * File -> open action requested
-  * or file drop event happened.
-  * Open a layer (or layers) or one Gerbv project from the files.
-  * This function will show a question if the layer to be opened
-  * is already open.
-  */
-void open_files(GSList *filenames)
-{
-	GSList *fns = NULL;		/* File names to ask */
-	GSList *fns_is_mod = NULL;	/* File name layer is modified */
-	GSList *fns_cnt = NULL;		/* File names count */
-	GSList *fns_lay_num = NULL;	/* Layer number for fns */
-	GSList *cnt = NULL;		/* File names count unsorted by layers,
-					   0 -- file not yet loaded as layer */
-	gint answer;
-
-	if (filenames == NULL)
-		return;
-
-	/* Check if there is a Gerbv project in the list.
-	 * If there is least open only that and ignore the rest. */
-	for (GSList *fn = filenames; fn; fn = fn->next) {
-		gboolean is_project = FALSE;
-		if (0 == project_is_gerbv_project(fn->data, &is_project)
-		&&  is_project) {
-			open_project(fn->data);
-
-			gerbv_render_zoom_to_fit_display(mainProject,
-					&screenRenderInfo);
-			render_refresh_rendered_image_on_screen();
-			callbacks_update_layer_tree();
-
-			return;
-		}
-	}
-
-	/* Count opened filenames and place result in list */
-	for (GSList *fn = filenames; fn; fn = fn->next) {
-		gint c = 0;
-
-		for (gint fidx = 0; fidx <= mainProject->last_loaded; ++fidx) {
-			gchar *fpn = mainProject->file[fidx]->fullPathname;
-
-			if (strlen(fpn) == strlen(fn->data)
-			&&  0 == g_ascii_strncasecmp(fpn, fn->data,
-						strlen(fn->data))) {
-				c++;
-			}
-		}
-
-		cnt = g_slist_append(cnt, GINT_TO_POINTER(c));
-	}
-
-	/* Make fns, fns_is_mod and fns_cnt lists sorted by layers */
-	for (gint fidx = 0; fidx <= mainProject->last_loaded; ++fidx) {
-		gchar *fpn = mainProject->file[fidx]->fullPathname;
-
-		for (GSList *fn = filenames; fn; fn = fn->next) {
-			if (strlen(fpn) == strlen(fn->data)
-			&&  0 == g_ascii_strncasecmp(fpn, fn->data,
-					strlen(fn->data))) {
-				fns = g_slist_append(fns, fn->data);
-				fns_is_mod = g_slist_append(fns_is_mod,
-						GINT_TO_POINTER(mainProject->
-							file[fidx]->
-							layer_dirty));
-				fns_cnt = g_slist_append(fns_cnt,
-						g_slist_nth_data(cnt,
-							g_slist_position(
-								filenames,
-								fn)));
-				fns_lay_num = g_slist_append(fns_lay_num,
-						GINT_TO_POINTER(fidx));
-
-				break;
-			}
-		}
-	}
-
-	answer = GTK_RESPONSE_NONE;
-	if (g_slist_length(fns) > 0)
-		answer = interface_reopen_question(fns, fns_is_mod,
-							fns_cnt, fns_lay_num);
-
-	switch (answer) {
-
-	case GTK_RESPONSE_CANCEL:
-	case GTK_RESPONSE_NONE:
-	case GTK_RESPONSE_DELETE_EVENT:
-		/* Dialog is closed or Esc is pressed, skip all */
-		break;
-
-	case GTK_RESPONSE_YES: /* Reload layer was selected */
-		for (GSList *fn = fns; fn; fn = fn->next) {
-			if (fn->data != NULL)
-				gerbv_revert_file(mainProject,
-					GPOINTER_TO_INT(
-						g_slist_nth_data (fns_lay_num,
-							g_slist_position (fns,
-									fn))));
-		}
-		break;
-
-	case GTK_RESPONSE_OK: /* Open as a new layer was selected */
-		/* To open as new only _one_ instance of file, check filenames
-		 * by selected files in fns */
-		for (GSList *fn = filenames; fn; fn = fn->next) {
-			if (NULL != g_slist_find (fns, fn->data))
-				gerbv_open_layer_from_filename(mainProject,
-								fn->data);
-		}
-		break;
-	}
-
-	/* Add not loaded files (cnt == 0) in the end */
-	for (GSList *fn = filenames; fn; fn = fn->next) {
-		if (0 == GPOINTER_TO_INT(g_slist_nth_data(cnt,
-					g_slist_position(filenames, fn))))
-			gerbv_open_layer_from_filename (mainProject, fn->data);
-	}
-
-	g_slist_free(fns);
-	g_slist_free(fns_is_mod);
-	g_slist_free(fns_cnt);
-	g_slist_free(fns_lay_num);
-	g_slist_free(cnt);
-
-	gerbv_render_zoom_to_fit_display (mainProject, &screenRenderInfo);
-	render_refresh_rendered_image_on_screen();
-	callbacks_update_layer_tree();
+ * File -> open action requested
+ * or file drop event happened.
+ * Open a layer (or layers) or one Gerbv project from the files.
+ * This function will show a question if the layer to be opened
+ * is already open.
+ */
+void
+open_files(GSList* filenames) {
+    GSList* fns         = NULL; /* File names to ask */
+    GSList* fns_is_mod  = NULL; /* File name layer is modified */
+    GSList* fns_cnt     = NULL; /* File names count */
+    GSList* fns_lay_num = NULL; /* Layer number for fns */
+    GSList* cnt         = NULL; /* File names count unsorted by layers,
+                           0 -- file not yet loaded as layer */
+    gint answer;
+
+    if (filenames == NULL)
+        return;
+
+    /* Check if there is a Gerbv project in the list.
+     * If there is least open only that and ignore the rest. */
+    for (GSList* fn = filenames; fn; fn = fn->next) {
+        gboolean is_project = FALSE;
+        if (0 == project_is_gerbv_project(fn->data, &is_project) && is_project) {
+            open_project(fn->data);
+
+            gerbv_render_zoom_to_fit_display(mainProject, &screenRenderInfo);
+            render_refresh_rendered_image_on_screen();
+            callbacks_update_layer_tree();
+
+            return;
+        }
+    }
+
+    /* Count opened filenames and place result in list */
+    for (GSList* fn = filenames; fn; fn = fn->next) {
+        gint c = 0;
+
+        for (gint fidx = 0; fidx <= mainProject->last_loaded; ++fidx) {
+            gchar* fpn = mainProject->file[fidx]->fullPathname;
+
+            if (strlen(fpn) == strlen(fn->data) && 0 == g_ascii_strncasecmp(fpn, fn->data, strlen(fn->data))) {
+                c++;
+            }
+        }
+
+        cnt = g_slist_append(cnt, GINT_TO_POINTER(c));
+    }
+
+    /* Make fns, fns_is_mod and fns_cnt lists sorted by layers */
+    for (gint fidx = 0; fidx <= mainProject->last_loaded; ++fidx) {
+        gchar* fpn = mainProject->file[fidx]->fullPathname;
+
+        for (GSList* fn = filenames; fn; fn = fn->next) {
+            if (strlen(fpn) == strlen(fn->data) && 0 == g_ascii_strncasecmp(fpn, fn->data, strlen(fn->data))) {
+                fns         = g_slist_append(fns, fn->data);
+                fns_is_mod  = g_slist_append(fns_is_mod, GINT_TO_POINTER(mainProject->file[fidx]->layer_dirty));
+                fns_cnt     = g_slist_append(fns_cnt, g_slist_nth_data(cnt, g_slist_position(filenames, fn)));
+                fns_lay_num = g_slist_append(fns_lay_num, GINT_TO_POINTER(fidx));
+
+                break;
+            }
+        }
+    }
+
+    answer = GTK_RESPONSE_NONE;
+    if (g_slist_length(fns) > 0)
+        answer = interface_reopen_question(fns, fns_is_mod, fns_cnt, fns_lay_num);
+
+    switch (answer) {
+
+        case GTK_RESPONSE_CANCEL:
+        case GTK_RESPONSE_NONE:
+        case GTK_RESPONSE_DELETE_EVENT:
+            /* Dialog is closed or Esc is pressed, skip all */
+            break;
+
+        case GTK_RESPONSE_YES: /* Reload layer was selected */
+            for (GSList* fn = fns; fn; fn = fn->next) {
+                if (fn->data != NULL)
+                    gerbv_revert_file(
+                        mainProject, GPOINTER_TO_INT(g_slist_nth_data(fns_lay_num, g_slist_position(fns, fn)))
+                    );
+            }
+            break;
+
+        case GTK_RESPONSE_OK: /* Open as a new layer was selected */
+            /* To open as new only _one_ instance of file, check filenames
+             * by selected files in fns */
+            for (GSList* fn = filenames; fn; fn = fn->next) {
+                if (NULL != g_slist_find(fns, fn->data))
+                    gerbv_open_layer_from_filename(mainProject, fn->data);
+            }
+            break;
+    }
+
+    /* Add not loaded files (cnt == 0) in the end */
+    for (GSList* fn = filenames; fn; fn = fn->next) {
+        if (0 == GPOINTER_TO_INT(g_slist_nth_data(cnt, g_slist_position(filenames, fn))))
+            gerbv_open_layer_from_filename(mainProject, fn->data);
+    }
+
+    g_slist_free(fns);
+    g_slist_free(fns_is_mod);
+    g_slist_free(fns_cnt);
+    g_slist_free(fns_lay_num);
+    g_slist_free(cnt);
+
+    gerbv_render_zoom_to_fit_display(mainProject, &screenRenderInfo);
+    render_refresh_rendered_image_on_screen();
+    callbacks_update_layer_tree();
 }
 
 /* --------------------------------------------------------- */
 /**
-  * The file -> open action was selected.  Open a
-  * layer (or layers) or a project file.
-  *
-  */
+ * The file -> open action was selected.  Open a
+ * layer (or layers) or a project file.
+ *
+ */
 void
-callbacks_open_activate(GtkMenuItem *menuitem, gpointer user_data)
-{
-	GSList *fns = NULL;
-	screen.win.gerber = 
-		gtk_file_chooser_dialog_new (
-				_("Open Gerbv project, Gerber, drill, "
-				"or pick&place files"),
-			NULL, GTK_FILE_CHOOSER_ACTION_OPEN,
-			GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
-			GTK_STOCK_OPEN,   GTK_RESPONSE_ACCEPT,
-			NULL);
-
-	gtk_file_chooser_set_select_multiple(
-			(GtkFileChooser *)screen.win.gerber, TRUE);
-	gtk_file_chooser_set_current_folder(
-			(GtkFileChooser *)screen.win.gerber, mainProject->path);
-	gtk_widget_show (screen.win.gerber);
-	if (gtk_dialog_run ((GtkDialog*)screen.win.gerber) ==
-			GTK_RESPONSE_ACCEPT) {
-		fns = gtk_file_chooser_get_filenames(
-				GTK_FILE_CHOOSER (screen.win.gerber));
-		/* Update the last folder */
-		g_free (mainProject->path);
-		mainProject->path = gtk_file_chooser_get_current_folder(
-				(GtkFileChooser *)screen.win.gerber);
-	}
-	gtk_widget_destroy (screen.win.gerber);
-
-	open_files (fns);
-	g_slist_free_full (fns, g_free);
+callbacks_open_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    GSList* fns       = NULL;
+    screen.win.gerber = gtk_file_chooser_dialog_new(
+        _("Open Gerbv project, Gerber, drill, "
+          "or pick&place files"),
+        NULL, GTK_FILE_CHOOSER_ACTION_OPEN, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
+        NULL
+    );
+
+    gtk_file_chooser_set_select_multiple((GtkFileChooser*)screen.win.gerber, TRUE);
+    gtk_file_chooser_set_current_folder((GtkFileChooser*)screen.win.gerber, mainProject->path);
+    gtk_widget_show(screen.win.gerber);
+    if (gtk_dialog_run((GtkDialog*)screen.win.gerber) == GTK_RESPONSE_ACCEPT) {
+        fns = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(screen.win.gerber));
+        /* Update the last folder */
+        g_free(mainProject->path);
+        mainProject->path = gtk_file_chooser_get_current_folder((GtkFileChooser*)screen.win.gerber);
+    }
+    gtk_widget_destroy(screen.win.gerber);
+
+    open_files(fns);
+    g_slist_free_full(fns, g_free);
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_revert_activate (GtkMenuItem *menuitem, gpointer user_data)
-{
-	gerbv_revert_all_files (mainProject);
-	selection_clear (&screen.selectionInfo);
-	update_selected_object_message (FALSE);
-	render_refresh_rendered_image_on_screen ();
-	callbacks_update_layer_tree ();
+callbacks_revert_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    gerbv_revert_all_files(mainProject);
+    selection_clear(&screen.selectionInfo);
+    update_selected_object_message(FALSE);
+    render_refresh_rendered_image_on_screen();
+    callbacks_update_layer_tree();
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_save_project_activate                       (GtkMenuItem     *menuitem,
-                                        gpointer         user_data)
-{
-  if (mainProject->project)
-    main_save_project_from_filename (mainProject, mainProject->project);
-  else
-    callbacks_generic_save_activate (menuitem, (gpointer) CALLBACKS_SAVE_PROJECT_AS);
-  callbacks_update_layer_tree();
-  return;
+callbacks_save_project_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    if (mainProject->project)
+        main_save_project_from_filename(mainProject, mainProject->project);
+    else
+        callbacks_generic_save_activate(menuitem, (gpointer)CALLBACKS_SAVE_PROJECT_AS);
+    callbacks_update_layer_tree();
+    return;
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_save_layer_activate                       (GtkMenuItem     *menuitem,
-                                        gpointer         user_data)
-{
-  /* first figure out which layer in the layer side menu is selected */
-  gint index=callbacks_get_selected_row_index();
-  
-  /* Now save that layer */
-  if (index >= 0) {
-    if (!gerbv_save_layer_from_index (mainProject, index, mainProject->file[index]->fullPathname)) {
-      interface_show_alert_dialog(_("Gerbv cannot export this file type"), 
-				  NULL,
-				  FALSE,
-				  NULL);
-      mainProject->file[index]->layer_dirty = FALSE;
-      callbacks_update_layer_tree();
-      return;
+callbacks_save_layer_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    /* first figure out which layer in the layer side menu is selected */
+    gint index = callbacks_get_selected_row_index();
+
+    /* Now save that layer */
+    if (index >= 0) {
+        if (!gerbv_save_layer_from_index(mainProject, index, mainProject->file[index]->fullPathname)) {
+            interface_show_alert_dialog(_("Gerbv cannot export this file type"), NULL, FALSE, NULL);
+            mainProject->file[index]->layer_dirty = FALSE;
+            callbacks_update_layer_tree();
+            return;
+        }
     }
-  }
-  callbacks_update_layer_tree();
-  return;
+    callbacks_update_layer_tree();
+    return;
 }
+
 struct l_image_info {
-	gerbv_image_t *image;
-	gerbv_user_transformation_t *transform;
+    gerbv_image_t*               image;
+    gerbv_user_transformation_t* transform;
 };
 
 /* --------------------------------------------------------- */
 /**Go through each file and look at visibility, then type.
 Make sure we have at least 2 files.
 */
-gerbv_image_t *merge_images (int type)
-{
-	gint i, filecount, img;
-	gerbv_image_t *out;
-	gerbv_layertype_t layertype;
-	struct l_image_info {
-		gerbv_image_t *image;
-		gerbv_user_transformation_t *transform;
-	} *images;
-	
-	images=(struct l_image_info *)g_new0(struct l_image_info,1);
-	out = NULL;
-	switch(type) {
-	case CALLBACKS_SAVE_FILE_DRILLM:
-		layertype = GERBV_LAYERTYPE_DRILL;
-		break;
-	case CALLBACKS_SAVE_FILE_RS274XM:
-		layertype = GERBV_LAYERTYPE_RS274X;
-		break;
-	default:
-		GERB_COMPILE_ERROR(_("Unknown Layer type for merge"));
-		goto err;
-	}
-	dprintf("Looking for matching files\n");
-	for (i = img = filecount = 0; i < mainProject->max_files; ++i) {
-		if (mainProject->file[i] &&  mainProject->file[i]->isVisible &&
-		(mainProject->file[i]->image->layertype == layertype)) {
-			++filecount;
-			dprintf("Adding '%s'\n", mainProject->file[i]->name);
-			images[img].image=mainProject->file[i]->image;
-			images[img++].transform=&mainProject->file[i]->transform;
-			images = (struct l_image_info *)g_renew(struct l_image_info, images, img+1);
-		}
-	}
-	if (filecount < 2) {
-		GERB_COMPILE_ERROR(_("Not Enough Files of same type to merge"));
-		goto err;
-	}
-	dprintf("Now merging files\n");
-	for (i = 0; i < img; ++i) {
-		gerbv_user_transformation_t *thisTransform;
-		gerbv_user_transformation_t identityTransform = {0,0,1,1,0,FALSE,FALSE,FALSE};
-		thisTransform=images[i].transform;
-		if (NULL == thisTransform)
-			thisTransform = &identityTransform;
-		if (0 == i)
-			out = gerbv_image_duplicate_image(images[i].image, thisTransform);
-		else
-			gerbv_image_copy_image(images[i].image, thisTransform, out);
-	}
+gerbv_image_t*
+merge_images(int type) {
+    gint              i, filecount, img;
+    gerbv_image_t*    out;
+    gerbv_layertype_t layertype;
+
+    struct l_image_info {
+        gerbv_image_t*               image;
+        gerbv_user_transformation_t* transform;
+    } * images;
+
+    images = (struct l_image_info*)g_new0(struct l_image_info, 1);
+    out    = NULL;
+    switch (type) {
+        case CALLBACKS_SAVE_FILE_DRILLM: layertype = GERBV_LAYERTYPE_DRILL; break;
+        case CALLBACKS_SAVE_FILE_RS274XM: layertype = GERBV_LAYERTYPE_RS274X; break;
+        default: GERB_COMPILE_ERROR(_("Unknown Layer type for merge")); goto err;
+    }
+    dprintf("Looking for matching files\n");
+    for (i = img = filecount = 0; i < mainProject->max_files; ++i) {
+        if (mainProject->file[i] && mainProject->file[i]->isVisible
+            && (mainProject->file[i]->image->layertype == layertype)) {
+            ++filecount;
+            dprintf("Adding '%s'\n", mainProject->file[i]->name);
+            images[img].image       = mainProject->file[i]->image;
+            images[img++].transform = &mainProject->file[i]->transform;
+            images                  = (struct l_image_info*)g_renew(struct l_image_info, images, img + 1);
+        }
+    }
+    if (filecount < 2) {
+        GERB_COMPILE_ERROR(_("Not Enough Files of same type to merge"));
+        goto err;
+    }
+    dprintf("Now merging files\n");
+    for (i = 0; i < img; ++i) {
+        gerbv_user_transformation_t* thisTransform;
+        gerbv_user_transformation_t  identityTransform = { 0, 0, 1, 1, 0, FALSE, FALSE, FALSE };
+        thisTransform                                  = images[i].transform;
+        if (NULL == thisTransform)
+            thisTransform = &identityTransform;
+        if (0 == i)
+            out = gerbv_image_duplicate_image(images[i].image, thisTransform);
+        else
+            gerbv_image_copy_image(images[i].image, thisTransform, out);
+    }
 err:
-	g_free(images);
-	return out;
+    g_free(images);
+    return out;
 }
 
 /* --------------------------------------------------------- */
 int
-visible_file_name(gchar **file_name, gchar **dir_name,
-		gerbv_layertype_t layer_type, /* -1 for all types */
-		const gchar *file_extension,
-		const gchar *untitled_file_extension)
-{
-	unsigned int count = 0;
-	gerbv_fileinfo_t *first_vis_file = NULL;
-
-	for (int i = 0; i < mainProject->max_files; ++i) {
-		if (mainProject->file[i]
-		&&  mainProject->file[i]->isVisible
-		&&  (layer_type == (gerbv_layertype_t)-1
-		  || layer_type == mainProject->file[i]->image->layertype)) {
-			if (first_vis_file == NULL) {
-				first_vis_file = mainProject->file[i];
-				/* Always directory of first visible file */
-				if (dir_name)
-					*dir_name = g_path_get_dirname (
-						first_vis_file->fullPathname);
-			}
-
-			if (++count == 2 && file_name) {
-				*file_name = g_strdup_printf("%s%s",
-						pgettext("file name",
-							"untitled"),
-						untitled_file_extension);
-			}
-		}
-	}
-
-	if (count == 1 && file_name)
-		*file_name = g_strdup_printf("%s%s",
-			first_vis_file->name, file_extension);
-
-	return count;
+visible_file_name(
+    gchar** file_name, gchar** dir_name, gerbv_layertype_t layer_type, /* -1 for all types */
+    const gchar* file_extension, const gchar* untitled_file_extension
+) {
+    unsigned int      count          = 0;
+    gerbv_fileinfo_t* first_vis_file = NULL;
+
+    for (int i = 0; i < mainProject->max_files; ++i) {
+        if (mainProject->file[i] && mainProject->file[i]->isVisible
+            && (layer_type == (gerbv_layertype_t)-1 || layer_type == mainProject->file[i]->image->layertype)) {
+            if (first_vis_file == NULL) {
+                first_vis_file = mainProject->file[i];
+                /* Always directory of first visible file */
+                if (dir_name)
+                    *dir_name = g_path_get_dirname(first_vis_file->fullPathname);
+            }
+
+            if (++count == 2 && file_name) {
+                *file_name = g_strdup_printf("%s%s", pgettext("file name", "untitled"), untitled_file_extension);
+            }
+        }
+    }
+
+    if (count == 1 && file_name)
+        *file_name = g_strdup_printf("%s%s", first_vis_file->name, file_extension);
+
+    return count;
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_generic_save_activate (GtkMenuItem     *menuitem,
-				 gpointer         user_data)
-{
-	gchar *new_file_name = NULL;
-	gchar *file_name = NULL;
-	gchar *dir_name = NULL;
-	gboolean error_visible_layers = FALSE;
-	gchar *windowTitle = NULL;
-	gerbv_fileinfo_t *act_file;
-	gint file_index;
-	gint processType = GPOINTER_TO_INT (user_data);
-	GtkFileFilter *filter;
-	GtkSpinButton *spin_but;
-	GtkTooltips *tooltips;
-	GtkWidget *label;
-	GtkWidget *hbox;
-	static gint dpi = 0;
-	
-	file_index = callbacks_get_selected_row_index ();
-	if (file_index < 0) {
-		interface_show_alert_dialog (_("No layer is currently active"),
-			_("Please select a layer and try again."),
-			FALSE,
-			NULL);
-		return;
-	}
-
-	act_file = mainProject->file[file_index];
-
-	screen.win.gerber = gtk_file_chooser_dialog_new ("", NULL,
-			GTK_FILE_CHOOSER_ACTION_SAVE, NULL, NULL, NULL);
-	GtkFileChooser *file_chooser_p =
-			GTK_FILE_CHOOSER(screen.win.gerber);
-	gtk_file_chooser_set_do_overwrite_confirmation (file_chooser_p, TRUE);
-
-	hbox = gtk_hbox_new (0, 0);
-	spin_but = GTK_SPIN_BUTTON(gtk_spin_button_new_with_range (0, 0, 1));
-	label = gtk_label_new ("");
-	tooltips = gtk_tooltips_new ();
-	gtk_box_pack_end (GTK_BOX(hbox), GTK_WIDGET(spin_but), 0, 0, 1);
-	gtk_box_pack_end (GTK_BOX(hbox), label, 0, 0, 5);
-	gtk_box_pack_end (GTK_BOX(GTK_DIALOG(screen.win.gerber)->vbox),
-			hbox, 0, 0, 2);
-
-	switch (processType) {
-	case CALLBACKS_SAVE_PROJECT_AS:
-		windowTitle = g_strdup (_("Save project as..."));
-		if (mainProject->project) {
-			file_name = g_path_get_basename (mainProject->project);
-
-			dir_name = g_path_get_dirname (mainProject->project);
-		} else {
-			file_name = g_strdup_printf("%s%s",
-					pgettext("file name", "untitled"),
-					GERBV_PROJECT_FILE_EXT);
-			dir_name= g_path_get_dirname (act_file->fullPathname);
-		}
-
-		filter = gtk_file_filter_new ();
-		gtk_file_filter_set_name (filter, _(gerbv_project_file_name));
-		gtk_file_filter_add_pattern (filter, gerbv_project_file_pat);
-		gtk_file_chooser_add_filter (file_chooser_p, filter);
-
-		filter = gtk_file_filter_new ();
-		gtk_file_filter_set_name (filter, _("All"));
-		gtk_file_filter_add_pattern (filter, "*");
-		gtk_file_chooser_add_filter (file_chooser_p, filter);
-
-		break;
-	case CALLBACKS_SAVE_FILE_PS:
-		windowTitle = g_strdup_printf (
-				_("Export visible layers to %s file as..."),
-				_("PS"));
-		if (0 == visible_file_name(&file_name, &dir_name, -1,
-							".ps", ".ps")) {
-			error_visible_layers = TRUE;
-			break;
-		}
-
-
-		break;
-	case CALLBACKS_SAVE_FILE_PDF:
-		windowTitle = g_strdup_printf (
-				_("Export visible layers to %s file as..."),
-				_("PDF"));
-		if (0 == visible_file_name(&file_name, &dir_name, -1,
-							".pdf", ".pdf")) {
-			error_visible_layers = TRUE;
-			break;
-		}
-
-
-		break;
-	case CALLBACKS_SAVE_FILE_SVG:
-		windowTitle = g_strdup_printf (
-				_("Export visible layers to %s file as..."),
-				_("SVG"));
-		if (0 == visible_file_name(&file_name, &dir_name, -1,
-							".svg", ".svg")) {
-			error_visible_layers = TRUE;
-			break;
-		}
-
-
-		break;
-	case CALLBACKS_SAVE_FILE_DXF:
+callbacks_generic_save_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    gchar*            new_file_name        = NULL;
+    gchar*            file_name            = NULL;
+    gchar*            dir_name             = NULL;
+    gboolean          error_visible_layers = FALSE;
+    gchar*            windowTitle          = NULL;
+    gerbv_fileinfo_t* act_file;
+    gint              file_index;
+    gint              processType = GPOINTER_TO_INT(user_data);
+    GtkFileFilter*    filter;
+    GtkSpinButton*    spin_but;
+    GtkTooltips*      tooltips;
+    GtkWidget*        label;
+    GtkWidget*        hbox;
+    static gint       dpi = 0;
+
+    file_index = callbacks_get_selected_row_index();
+    if (file_index < 0) {
+        interface_show_alert_dialog(
+            _("No layer is currently active"), _("Please select a layer and try again."), FALSE, NULL
+        );
+        return;
+    }
+
+    act_file = mainProject->file[file_index];
+
+    screen.win.gerber = gtk_file_chooser_dialog_new("", NULL, GTK_FILE_CHOOSER_ACTION_SAVE, NULL, NULL, NULL);
+    GtkFileChooser* file_chooser_p = GTK_FILE_CHOOSER(screen.win.gerber);
+    gtk_file_chooser_set_do_overwrite_confirmation(file_chooser_p, TRUE);
+
+    hbox     = gtk_hbox_new(0, 0);
+    spin_but = GTK_SPIN_BUTTON(gtk_spin_button_new_with_range(0, 0, 1));
+    label    = gtk_label_new("");
+    tooltips = gtk_tooltips_new();
+    gtk_box_pack_end(GTK_BOX(hbox), GTK_WIDGET(spin_but), 0, 0, 1);
+    gtk_box_pack_end(GTK_BOX(hbox), label, 0, 0, 5);
+    gtk_box_pack_end(GTK_BOX(GTK_DIALOG(screen.win.gerber)->vbox), hbox, 0, 0, 2);
+
+    switch (processType) {
+        case CALLBACKS_SAVE_PROJECT_AS:
+            windowTitle = g_strdup(_("Save project as..."));
+            if (mainProject->project) {
+                file_name = g_path_get_basename(mainProject->project);
+
+                dir_name = g_path_get_dirname(mainProject->project);
+            } else {
+                file_name = g_strdup_printf("%s%s", pgettext("file name", "untitled"), GERBV_PROJECT_FILE_EXT);
+                dir_name  = g_path_get_dirname(act_file->fullPathname);
+            }
+
+            filter = gtk_file_filter_new();
+            gtk_file_filter_set_name(filter, _(gerbv_project_file_name));
+            gtk_file_filter_add_pattern(filter, gerbv_project_file_pat);
+            gtk_file_chooser_add_filter(file_chooser_p, filter);
+
+            filter = gtk_file_filter_new();
+            gtk_file_filter_set_name(filter, _("All"));
+            gtk_file_filter_add_pattern(filter, "*");
+            gtk_file_chooser_add_filter(file_chooser_p, filter);
+
+            break;
+        case CALLBACKS_SAVE_FILE_PS:
+            windowTitle = g_strdup_printf(_("Export visible layers to %s file as..."), _("PS"));
+            if (0 == visible_file_name(&file_name, &dir_name, -1, ".ps", ".ps")) {
+                error_visible_layers = TRUE;
+                break;
+            }
+
+            break;
+        case CALLBACKS_SAVE_FILE_PDF:
+            windowTitle = g_strdup_printf(_("Export visible layers to %s file as..."), _("PDF"));
+            if (0 == visible_file_name(&file_name, &dir_name, -1, ".pdf", ".pdf")) {
+                error_visible_layers = TRUE;
+                break;
+            }
+
+            break;
+        case CALLBACKS_SAVE_FILE_SVG:
+            windowTitle = g_strdup_printf(_("Export visible layers to %s file as..."), _("SVG"));
+            if (0 == visible_file_name(&file_name, &dir_name, -1, ".svg", ".svg")) {
+                error_visible_layers = TRUE;
+                break;
+            }
+
+            break;
+        case CALLBACKS_SAVE_FILE_DXF:
 #if HAVE_LIBDXFLIB
-		windowTitle = g_strdup_printf (
-			_("Export \"%s\" layer #%d to DXF file as..."),
-			act_file->name, file_index + 1);
-		file_name = g_strconcat (act_file->name, ".dxf", NULL);
-		dir_name =  g_path_get_dirname (act_file->fullPathname);
+            windowTitle =
+                g_strdup_printf(_("Export \"%s\" layer #%d to DXF file as..."), act_file->name, file_index + 1);
+            file_name = g_strconcat(act_file->name, ".dxf", NULL);
+            dir_name  = g_path_get_dirname(act_file->fullPathname);
 #endif
-		break;
-	case CALLBACKS_SAVE_FILE_PNG:
-		windowTitle = g_strdup_printf (
-				_("Export visible layers to %s file as..."),
-				_("PNG"));
-		if (0 == visible_file_name(&file_name, &dir_name, -1,
-							".png", ".png")) {
-			error_visible_layers = TRUE;
-			break;
-		}
-
-		gtk_label_set_text (GTK_LABEL(label), _("DPI:"));
-		gtk_spin_button_set_range (spin_but, 0, 6000);
-		gtk_spin_button_set_increments (spin_but, 10, 100);
-		gtk_tooltips_set_tip (tooltips, GTK_WIDGET(label),
-				_("DPI value, autoscaling if 0"), NULL);
-		gtk_tooltips_set_tip (tooltips, GTK_WIDGET(spin_but),
-				_("DPI value, autoscaling if 0"), NULL);
-		gtk_spin_button_set_value (spin_but, dpi);
-		gtk_widget_show_all (hbox);
-
-		break;
-	case CALLBACKS_SAVE_FILE_RS274X:
-		windowTitle = g_strdup_printf(
-			_("Export \"%s\" layer #%d to "
-				"RS-274X file as..."),
-			act_file->name, file_index+1);
-
-		if (GERBV_LAYERTYPE_RS274X != act_file->image->layertype)
-			file_name = g_strconcat (act_file->name, ".gbr", NULL);
-		else
-			file_name = g_strdup (act_file->name);
-
-		dir_name =  g_path_get_dirname (act_file->fullPathname);
-		break;
-	case CALLBACKS_SAVE_FILE_RS274XM:
-		windowTitle = g_strdup (_("Export merged visible layers to "
-					"RS-274X file as..."));
-		if (2 > visible_file_name(&file_name, &dir_name,
-					GERBV_LAYERTYPE_RS274X, "", ".gbr")) {
-			error_visible_layers = TRUE;
-			break;
-		}
-	case CALLBACKS_SAVE_FILE_DRILL:
-		windowTitle = g_strdup_printf(
-			_("Export \"%s\" layer #%d to "
-				"Excellon drill file as..."),
-			act_file->name, file_index+1);
-
-		if (GERBV_LAYERTYPE_DRILL != act_file->image->layertype)
-			file_name = g_strconcat (act_file->name, ".drl", NULL);
-		else
-			file_name = g_strdup (act_file->name);
-
-		dir_name =  g_path_get_dirname (act_file->fullPathname);
-		break;
-	case CALLBACKS_SAVE_FILE_DRILLM:
-		windowTitle = g_strdup (_("Export merged visible layers to "
-					"Excellon drill file as..."));
-		if (2 > visible_file_name(&file_name, &dir_name,
-				GERBV_LAYERTYPE_DRILL, "", ".drl")) {
-			error_visible_layers = TRUE;
-		}
-		break;
-	case CALLBACKS_SAVE_FILE_IDRILL:
-		windowTitle = g_strdup_printf(
-			_("Export \"%s\" layer #%d to ISEL NCP drill file as..."),
-			act_file->name, file_index+1);
-		file_name = g_strconcat (act_file->name, ".ncp", NULL);
-		dir_name =  g_path_get_dirname (act_file->fullPathname);
-
-		break;
-	case CALLBACKS_SAVE_FILE_GEDA_PCB:
-		windowTitle = g_strdup_printf (
-			_("Export \"%s\" layer #%d to gEDA PCB file as..."),
-			act_file->name, file_index + 1);
-		file_name = g_strconcat (act_file->name, ".pcb", NULL);
-		dir_name =  g_path_get_dirname (act_file->fullPathname);
-		break;
-	case CALLBACKS_SAVE_LAYER_AS:
-		windowTitle = g_strdup_printf (_("Save \"%s\" layer #%d as..."),
-				act_file->name, file_index+1);
-		file_name = g_strdup (act_file->name);
-		dir_name =  g_path_get_dirname (act_file->fullPathname);
-		break;
-	}
-
-	if (file_name != NULL) {
-		gtk_file_chooser_set_current_name (file_chooser_p, file_name);
-		g_free (file_name);
-	}
-	if (dir_name != NULL) {
-		gtk_file_chooser_set_current_folder (file_chooser_p, dir_name);
-		g_free (dir_name);
-	}
-
-	gtk_dialog_add_buttons (GTK_DIALOG(screen.win.gerber),
-			GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
-			GTK_STOCK_SAVE,   GTK_RESPONSE_ACCEPT,
-			NULL);
-
-	gtk_window_set_title (GTK_WINDOW(screen.win.gerber), windowTitle);
-	g_free (windowTitle);
-
-	if (error_visible_layers) {
-		switch (processType) {
-		case CALLBACKS_SAVE_FILE_RS274XM:
-			interface_get_alert_dialog_response (
-				_("Not enough Gerber layers are visible"),
-				_("Two or more Gerber layers must be visible "
-				"for export with merge."),
-				FALSE, NULL, NULL, GTK_STOCK_CANCEL);
-			break;
-		case CALLBACKS_SAVE_FILE_DRILLM:
-			interface_get_alert_dialog_response (
-				_("Not enough Excellon layers are visible"),
-				_("Two or more Excellon layers must be visible "
-				"for export with merge."),
-				FALSE, NULL, NULL, GTK_STOCK_CANCEL);
-			break;
-		default:
-			interface_get_alert_dialog_response (
-				_("No layers are visible"), _("One or more "
-				"layers must be visible for export."),
-				FALSE, NULL, NULL, GTK_STOCK_CANCEL);
-		}
-
-		gtk_widget_destroy (screen.win.gerber);
-		callbacks_update_layer_tree ();
-
-		return;
-	}
-
-	gtk_widget_show (screen.win.gerber);
-	if (gtk_dialog_run (GTK_DIALOG(screen.win.gerber)) == GTK_RESPONSE_ACCEPT) {
-		new_file_name = gtk_file_chooser_get_filename (file_chooser_p);
-		dpi = gtk_spin_button_get_value_as_int (spin_but);
-	}
-	gtk_widget_destroy (screen.win.gerber);
-
-	if (!new_file_name) {
-		callbacks_update_layer_tree ();
-
-		return;
-	}
-
-	switch (processType) {
-	case CALLBACKS_SAVE_PROJECT_AS:
-		main_save_as_project_from_filename (mainProject, new_file_name);
-		rename_main_window(new_file_name, NULL);
-		break;
-	case CALLBACKS_SAVE_FILE_PS:
-		gerbv_export_postscript_file_from_project_autoscaled (
-				mainProject, new_file_name);
-		break;
-	case CALLBACKS_SAVE_FILE_PDF:
-		gerbv_export_pdf_file_from_project_autoscaled (
-				mainProject, new_file_name);
-		break;
-	case CALLBACKS_SAVE_FILE_SVG:
-		gerbv_export_svg_file_from_project_autoscaled (
-				mainProject, new_file_name);
-		break;
-	case CALLBACKS_SAVE_FILE_DXF:
+            break;
+        case CALLBACKS_SAVE_FILE_PNG:
+            windowTitle = g_strdup_printf(_("Export visible layers to %s file as..."), _("PNG"));
+            if (0 == visible_file_name(&file_name, &dir_name, -1, ".png", ".png")) {
+                error_visible_layers = TRUE;
+                break;
+            }
+
+            gtk_label_set_text(GTK_LABEL(label), _("DPI:"));
+            gtk_spin_button_set_range(spin_but, 0, 6000);
+            gtk_spin_button_set_increments(spin_but, 10, 100);
+            gtk_tooltips_set_tip(tooltips, GTK_WIDGET(label), _("DPI value, autoscaling if 0"), NULL);
+            gtk_tooltips_set_tip(tooltips, GTK_WIDGET(spin_but), _("DPI value, autoscaling if 0"), NULL);
+            gtk_spin_button_set_value(spin_but, dpi);
+            gtk_widget_show_all(hbox);
+
+            break;
+        case CALLBACKS_SAVE_FILE_RS274X:
+            windowTitle = g_strdup_printf(
+                _("Export \"%s\" layer #%d to "
+                  "RS-274X file as..."),
+                act_file->name, file_index + 1
+            );
+
+            if (GERBV_LAYERTYPE_RS274X != act_file->image->layertype)
+                file_name = g_strconcat(act_file->name, ".gbr", NULL);
+            else
+                file_name = g_strdup(act_file->name);
+
+            dir_name = g_path_get_dirname(act_file->fullPathname);
+            break;
+        case CALLBACKS_SAVE_FILE_RS274XM:
+            windowTitle =
+                g_strdup(_("Export merged visible layers to "
+                           "RS-274X file as..."));
+            if (2 > visible_file_name(&file_name, &dir_name, GERBV_LAYERTYPE_RS274X, "", ".gbr")) {
+                error_visible_layers = TRUE;
+                break;
+            }
+        case CALLBACKS_SAVE_FILE_DRILL:
+            windowTitle = g_strdup_printf(
+                _("Export \"%s\" layer #%d to "
+                  "Excellon drill file as..."),
+                act_file->name, file_index + 1
+            );
+
+            if (GERBV_LAYERTYPE_DRILL != act_file->image->layertype)
+                file_name = g_strconcat(act_file->name, ".drl", NULL);
+            else
+                file_name = g_strdup(act_file->name);
+
+            dir_name = g_path_get_dirname(act_file->fullPathname);
+            break;
+        case CALLBACKS_SAVE_FILE_DRILLM:
+            windowTitle =
+                g_strdup(_("Export merged visible layers to "
+                           "Excellon drill file as..."));
+            if (2 > visible_file_name(&file_name, &dir_name, GERBV_LAYERTYPE_DRILL, "", ".drl")) {
+                error_visible_layers = TRUE;
+            }
+            break;
+        case CALLBACKS_SAVE_FILE_IDRILL:
+            windowTitle = g_strdup_printf(
+                _("Export \"%s\" layer #%d to ISEL NCP drill file as..."), act_file->name, file_index + 1
+            );
+            file_name = g_strconcat(act_file->name, ".ncp", NULL);
+            dir_name  = g_path_get_dirname(act_file->fullPathname);
+
+            break;
+        case CALLBACKS_SAVE_FILE_GEDA_PCB:
+            windowTitle =
+                g_strdup_printf(_("Export \"%s\" layer #%d to gEDA PCB file as..."), act_file->name, file_index + 1);
+            file_name = g_strconcat(act_file->name, ".pcb", NULL);
+            dir_name  = g_path_get_dirname(act_file->fullPathname);
+            break;
+        case CALLBACKS_SAVE_LAYER_AS:
+            windowTitle = g_strdup_printf(_("Save \"%s\" layer #%d as..."), act_file->name, file_index + 1);
+            file_name   = g_strdup(act_file->name);
+            dir_name    = g_path_get_dirname(act_file->fullPathname);
+            break;
+    }
+
+    if (file_name != NULL) {
+        gtk_file_chooser_set_current_name(file_chooser_p, file_name);
+        g_free(file_name);
+    }
+    if (dir_name != NULL) {
+        gtk_file_chooser_set_current_folder(file_chooser_p, dir_name);
+        g_free(dir_name);
+    }
+
+    gtk_dialog_add_buttons(
+        GTK_DIALOG(screen.win.gerber), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT, NULL
+    );
+
+    gtk_window_set_title(GTK_WINDOW(screen.win.gerber), windowTitle);
+    g_free(windowTitle);
+
+    if (error_visible_layers) {
+        switch (processType) {
+            case CALLBACKS_SAVE_FILE_RS274XM:
+                interface_get_alert_dialog_response(
+                    _("Not enough Gerber layers are visible"),
+                    _("Two or more Gerber layers must be visible "
+                      "for export with merge."),
+                    FALSE, NULL, NULL, GTK_STOCK_CANCEL
+                );
+                break;
+            case CALLBACKS_SAVE_FILE_DRILLM:
+                interface_get_alert_dialog_response(
+                    _("Not enough Excellon layers are visible"),
+                    _("Two or more Excellon layers must be visible "
+                      "for export with merge."),
+                    FALSE, NULL, NULL, GTK_STOCK_CANCEL
+                );
+                break;
+            default:
+                interface_get_alert_dialog_response(
+                    _("No layers are visible"),
+                    _("One or more "
+                      "layers must be visible for export."),
+                    FALSE, NULL, NULL, GTK_STOCK_CANCEL
+                );
+        }
+
+        gtk_widget_destroy(screen.win.gerber);
+        callbacks_update_layer_tree();
+
+        return;
+    }
+
+    gtk_widget_show(screen.win.gerber);
+    if (gtk_dialog_run(GTK_DIALOG(screen.win.gerber)) == GTK_RESPONSE_ACCEPT) {
+        new_file_name = gtk_file_chooser_get_filename(file_chooser_p);
+        dpi           = gtk_spin_button_get_value_as_int(spin_but);
+    }
+    gtk_widget_destroy(screen.win.gerber);
+
+    if (!new_file_name) {
+        callbacks_update_layer_tree();
+
+        return;
+    }
+
+    switch (processType) {
+        case CALLBACKS_SAVE_PROJECT_AS:
+            main_save_as_project_from_filename(mainProject, new_file_name);
+            rename_main_window(new_file_name, NULL);
+            break;
+        case CALLBACKS_SAVE_FILE_PS:
+            gerbv_export_postscript_file_from_project_autoscaled(mainProject, new_file_name);
+            break;
+        case CALLBACKS_SAVE_FILE_PDF: gerbv_export_pdf_file_from_project_autoscaled(mainProject, new_file_name); break;
+        case CALLBACKS_SAVE_FILE_SVG: gerbv_export_svg_file_from_project_autoscaled(mainProject, new_file_name); break;
+        case CALLBACKS_SAVE_FILE_DXF:
 #if HAVE_LIBDXFLIB
-		if (gerbv_export_dxf_file_from_image(new_file_name,
-				act_file->image, &act_file->transform)) {
-			GERB_MESSAGE (
-				_("\"%s\" layer #%d saved as DXF in \"%s\""),
-				act_file->name, file_index + 1,
-				new_file_name);
-		}
+            if (gerbv_export_dxf_file_from_image(new_file_name, act_file->image, &act_file->transform)) {
+                GERB_MESSAGE(
+                    _("\"%s\" layer #%d saved as DXF in \"%s\""), act_file->name, file_index + 1, new_file_name
+                );
+            }
 #endif
-		break;
-	case CALLBACKS_SAVE_FILE_PNG:
-		if (dpi == 0) {
-			gerbv_export_png_file_from_project_autoscaled (
-					mainProject,
-					screenRenderInfo.displayWidth,
-					screenRenderInfo.displayHeight,
-					new_file_name);
-		} else {	/* Non zero DPI */
-			gerbv_render_size_t bb;
-			gerbv_render_get_boundingbox (mainProject, &bb);
-			gfloat w = bb.right - bb.left;
-			gfloat h = bb.bottom - bb.top;
-			gerbv_render_info_t renderInfo = {
-				dpi, dpi,
-				bb.left - (w*GERBV_DEFAULT_BORDER_COEFF)/2.0,
-				bb.top - (h*GERBV_DEFAULT_BORDER_COEFF)/2.0,
-				GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY,
-				w*dpi*(1 + GERBV_DEFAULT_BORDER_COEFF),
-				h*dpi*(1 + GERBV_DEFAULT_BORDER_COEFF),
-			};
-			gerbv_export_png_file_from_project (mainProject,
-					&renderInfo, new_file_name);
-		}
-
-		break;
-	case  CALLBACKS_SAVE_LAYER_AS:
-		gerbv_save_layer_from_index (mainProject,
-				file_index, new_file_name);
-
-		/* Rename the file path in the index, so future saves will
-		 * reference the new file path */
-		g_free (act_file->fullPathname);
-		act_file->fullPathname = g_strdup (new_file_name);
-		g_free (act_file->name);
-		act_file->name = g_path_get_basename (new_file_name);
-
-		break;
-	case CALLBACKS_SAVE_FILE_RS274X:
-		if (gerbv_export_rs274x_file_from_image (new_file_name,
-					act_file->image,
-					&act_file->transform)) {
-			GERB_MESSAGE (
-				_("\"%s\" layer #%d saved as Gerber in \"%s\""),
-				act_file->name, file_index + 1,
-				new_file_name);
-		}
-		break;
-	case CALLBACKS_SAVE_FILE_DRILL:
-		if (gerbv_export_drill_file_from_image (new_file_name,
-					act_file->image,
-					&act_file->transform)) {
-			GERB_MESSAGE (
-				_("\"%s\" layer #%d saved as drill in \"%s\""),
-				act_file->name, file_index + 1,
-				new_file_name);
-		}
-		break;
-	case CALLBACKS_SAVE_FILE_IDRILL:
-		if (gerbv_export_isel_drill_file_from_image (new_file_name,
-				act_file->image, &act_file->transform)) {
-			GERB_MESSAGE (
-				_("\"%s\" layer #%d saved as ISEL NCP drill "
-				"in \"%s\""), act_file->name, file_index + 1,
-				new_file_name);
-		}
-		break;
-	case CALLBACKS_SAVE_FILE_GEDA_PCB:
-		if (gerbv_export_geda_pcb_file_from_image(new_file_name,
-				act_file->image, &act_file->transform)) {
-			GERB_MESSAGE (
-				_("\"%s\" layer #%d saved as gEDA PCB "
-				"in \"%s\""), act_file->name, file_index + 1,
-				new_file_name);
-		}
-		break;
-	case CALLBACKS_SAVE_FILE_RS274XM: {
-		gerbv_image_t *image;
-		gerbv_user_transformation_t t = {0,0,1,1,0,FALSE,FALSE,FALSE};
-		if (NULL != (image = merge_images (processType))) {
-			if (gerbv_export_rs274x_file_from_image (
-						new_file_name, image, &t)) {
-				GERB_MESSAGE (_("Merged visible Gerber layers "
-						"and saved in \"%s\""),
-						new_file_name);
-			}
-			gerbv_destroy_image (image);
-		}
-		break;
-	}
-	case CALLBACKS_SAVE_FILE_DRILLM: {
-		gerbv_image_t *image;
-		gerbv_user_transformation_t t = {0,0,1,1,0,FALSE,FALSE,FALSE};
-		if (NULL != (image = merge_images (processType))) {
-			gerbv_export_drill_file_from_image (
-					new_file_name, image, &t);
-			gerbv_destroy_image (image);
-			GERB_MESSAGE (_("Merged visible drill layers "
-					"and saved in \"%s\""),
-					new_file_name);
-		}
-		break;
-	}
-	}
-
-	g_free (new_file_name);
-	callbacks_update_layer_tree ();
-
-	return;
+            break;
+        case CALLBACKS_SAVE_FILE_PNG:
+            if (dpi == 0) {
+                gerbv_export_png_file_from_project_autoscaled(
+                    mainProject, screenRenderInfo.displayWidth, screenRenderInfo.displayHeight, new_file_name
+                );
+            } else { /* Non zero DPI */
+                gerbv_render_size_t bb;
+                gerbv_render_get_boundingbox(mainProject, &bb);
+                gfloat              w          = bb.right - bb.left;
+                gfloat              h          = bb.bottom - bb.top;
+                gerbv_render_info_t renderInfo = {
+                    dpi,
+                    dpi,
+                    bb.left - (w * GERBV_DEFAULT_BORDER_COEFF) / 2.0,
+                    bb.top - (h * GERBV_DEFAULT_BORDER_COEFF) / 2.0,
+                    GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY,
+                    w * dpi * (1 + GERBV_DEFAULT_BORDER_COEFF),
+                    h * dpi * (1 + GERBV_DEFAULT_BORDER_COEFF),
+                };
+                gerbv_export_png_file_from_project(mainProject, &renderInfo, new_file_name);
+            }
+
+            break;
+        case CALLBACKS_SAVE_LAYER_AS:
+            gerbv_save_layer_from_index(mainProject, file_index, new_file_name);
+
+            /* Rename the file path in the index, so future saves will
+             * reference the new file path */
+            g_free(act_file->fullPathname);
+            act_file->fullPathname = g_strdup(new_file_name);
+            g_free(act_file->name);
+            act_file->name = g_path_get_basename(new_file_name);
+
+            break;
+        case CALLBACKS_SAVE_FILE_RS274X:
+            if (gerbv_export_rs274x_file_from_image(new_file_name, act_file->image, &act_file->transform)) {
+                GERB_MESSAGE(
+                    _("\"%s\" layer #%d saved as Gerber in \"%s\""), act_file->name, file_index + 1, new_file_name
+                );
+            }
+            break;
+        case CALLBACKS_SAVE_FILE_DRILL:
+            if (gerbv_export_drill_file_from_image(new_file_name, act_file->image, &act_file->transform)) {
+                GERB_MESSAGE(
+                    _("\"%s\" layer #%d saved as drill in \"%s\""), act_file->name, file_index + 1, new_file_name
+                );
+            }
+            break;
+        case CALLBACKS_SAVE_FILE_IDRILL:
+            if (gerbv_export_isel_drill_file_from_image(new_file_name, act_file->image, &act_file->transform)) {
+                GERB_MESSAGE(
+                    _("\"%s\" layer #%d saved as ISEL NCP drill "
+                      "in \"%s\""),
+                    act_file->name, file_index + 1, new_file_name
+                );
+            }
+            break;
+        case CALLBACKS_SAVE_FILE_GEDA_PCB:
+            if (gerbv_export_geda_pcb_file_from_image(new_file_name, act_file->image, &act_file->transform)) {
+                GERB_MESSAGE(
+                    _("\"%s\" layer #%d saved as gEDA PCB "
+                      "in \"%s\""),
+                    act_file->name, file_index + 1, new_file_name
+                );
+            }
+            break;
+        case CALLBACKS_SAVE_FILE_RS274XM:
+            {
+                gerbv_image_t*              image;
+                gerbv_user_transformation_t t = { 0, 0, 1, 1, 0, FALSE, FALSE, FALSE };
+                if (NULL != (image = merge_images(processType))) {
+                    if (gerbv_export_rs274x_file_from_image(new_file_name, image, &t)) {
+                        GERB_MESSAGE(
+                            _("Merged visible Gerber layers "
+                              "and saved in \"%s\""),
+                            new_file_name
+                        );
+                    }
+                    gerbv_destroy_image(image);
+                }
+                break;
+            }
+        case CALLBACKS_SAVE_FILE_DRILLM:
+            {
+                gerbv_image_t*              image;
+                gerbv_user_transformation_t t = { 0, 0, 1, 1, 0, FALSE, FALSE, FALSE };
+                if (NULL != (image = merge_images(processType))) {
+                    gerbv_export_drill_file_from_image(new_file_name, image, &t);
+                    gerbv_destroy_image(image);
+                    GERB_MESSAGE(
+                        _("Merged visible drill layers "
+                          "and saved in \"%s\""),
+                        new_file_name
+                    );
+                }
+                break;
+            }
+    }
+
+    g_free(new_file_name);
+    callbacks_update_layer_tree();
+
+    return;
 }
 
 /* --------------------------------------------------------- */
-#if GTK_CHECK_VERSION(2,10,0)
+#if GTK_CHECK_VERSION(2, 10, 0)
 
 static void
-callbacks_begin_print (GtkPrintOperation *operation, GtkPrintContext   *context,
-		gpointer user_data) {
-	gtk_print_operation_set_n_pages     (operation, 1);
+callbacks_begin_print(GtkPrintOperation* operation, GtkPrintContext* context, gpointer user_data) {
+    gtk_print_operation_set_n_pages(operation, 1);
 }
 
-
 /* --------------------------------------------------------- */
 static void
-callbacks_print_render_page (GtkPrintOperation *operation,
-           GtkPrintContext   *context,
-           gint               page_nr,
-           gpointer           user_data)
-{
-	GtkPrintSettings *pSettings = gtk_print_operation_get_print_settings (operation);
-	gerbv_render_info_t renderInfo = {1.0, 1.0, 0, 0,
-		GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY,
-		(gint) gtk_print_context_get_width (context),
-		(gint) gtk_print_context_get_height (context)};
-	cairo_t *cr;
-	
-	/* have to assume x and y resolutions are the same for now, since we
-	   don't support differing scales in the gerb_render_info_t struct yet */
-	gdouble xres = gtk_print_context_get_dpi_x (context);
-	gdouble yres = gtk_print_context_get_dpi_y (context);
-	gdouble scalePercentage = gtk_print_settings_get_scale (pSettings);
-	renderInfo.scaleFactorX = scalePercentage / 100 * xres;
-	renderInfo.scaleFactorY = scalePercentage / 100 * yres;
-
-	gerbv_render_translate_to_fit_display (mainProject, &renderInfo);
-	cr = gtk_print_context_get_cairo_context (context);
-	gerbv_render_all_layers_to_cairo_target_for_vector_output (mainProject, cr, &renderInfo);
+callbacks_print_render_page(GtkPrintOperation* operation, GtkPrintContext* context, gint page_nr, gpointer user_data) {
+    GtkPrintSettings*   pSettings  = gtk_print_operation_get_print_settings(operation);
+    gerbv_render_info_t renderInfo = { 1.0,
+                                       1.0,
+                                       0,
+                                       0,
+                                       GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY,
+                                       (gint)gtk_print_context_get_width(context),
+                                       (gint)gtk_print_context_get_height(context) };
+    cairo_t*            cr;
+
+    /* have to assume x and y resolutions are the same for now, since we
+       don't support differing scales in the gerb_render_info_t struct yet */
+    gdouble xres            = gtk_print_context_get_dpi_x(context);
+    gdouble yres            = gtk_print_context_get_dpi_y(context);
+    gdouble scalePercentage = gtk_print_settings_get_scale(pSettings);
+    renderInfo.scaleFactorX = scalePercentage / 100 * xres;
+    renderInfo.scaleFactorY = scalePercentage / 100 * yres;
+
+    gerbv_render_translate_to_fit_display(mainProject, &renderInfo);
+    cr = gtk_print_context_get_cairo_context(context);
+    gerbv_render_all_layers_to_cairo_target_for_vector_output(mainProject, cr, &renderInfo);
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_print_activate (GtkMenuItem *menuitem, gpointer user_data)
-{
-	GtkPrintOperation *print;
-	/*GtkPrintOperationResult res;*/
+callbacks_print_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    GtkPrintOperation* print;
+    /*GtkPrintOperationResult res;*/
+
+    print = gtk_print_operation_new();
 
-	print = gtk_print_operation_new ();
+    g_signal_connect(print, "begin_print", G_CALLBACK(callbacks_begin_print), NULL);
+    g_signal_connect(print, "draw_page", G_CALLBACK(callbacks_print_render_page), NULL);
 
-	g_signal_connect (print, "begin_print", G_CALLBACK (callbacks_begin_print), NULL);
-	g_signal_connect (print, "draw_page", G_CALLBACK (callbacks_print_render_page), NULL);
+    // GtkPrintSettings *pSettings = gtk_print_operation_get_print_settings (print);
 
-	//GtkPrintSettings *pSettings = gtk_print_operation_get_print_settings (print);
-	
-	(void) gtk_print_operation_run (print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
-	                              (GtkWindow *) screen.win.topLevelWindow , NULL);
+    (void)gtk_print_operation_run(
+        print, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG, (GtkWindow*)screen.win.topLevelWindow, NULL
+    );
 
-	g_object_unref (print);
+    g_object_unref(print);
 }
 #endif /* GTK_CHECK_VERSION(2,10,0) */
 
 /* --------------------------------------------------------- */
 void
-callbacks_fullscreen_toggled (GtkMenuItem *menuitem, gpointer user_data)
-{
-	//struct GtkWindow *win = (struct GtkWindow *)(screen.win.topLevelWindow);
-	GdkWindowState state = gdk_window_get_state (gtk_widget_get_window(screen.win.topLevelWindow));
-	if(state & GDK_WINDOW_STATE_FULLSCREEN)
-		gtk_window_unfullscreen (GTK_WINDOW(screen.win.topLevelWindow));
-	else
-		gtk_window_fullscreen (GTK_WINDOW(screen.win.topLevelWindow));
+callbacks_fullscreen_toggled(GtkMenuItem* menuitem, gpointer user_data) {
+    // struct GtkWindow *win = (struct GtkWindow *)(screen.win.topLevelWindow);
+    GdkWindowState state = gdk_window_get_state(gtk_widget_get_window(screen.win.topLevelWindow));
+    if (state & GDK_WINDOW_STATE_FULLSCREEN)
+        gtk_window_unfullscreen(GTK_WINDOW(screen.win.topLevelWindow));
+    else
+        gtk_window_fullscreen(GTK_WINDOW(screen.win.topLevelWindow));
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_show_toolbar_toggled (GtkMenuItem *menuitem, gpointer user_data)
-{
-	gtk_widget_set_visible (user_data, GTK_CHECK_MENU_ITEM(menuitem)->active);
+callbacks_show_toolbar_toggled(GtkMenuItem* menuitem, gpointer user_data) {
+    gtk_widget_set_visible(user_data, GTK_CHECK_MENU_ITEM(menuitem)->active);
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_show_sidepane_toggled (GtkMenuItem *menuitem, gpointer user_data)
-{
-	gtk_widget_set_visible (user_data, GTK_CHECK_MENU_ITEM(menuitem)->active);
+callbacks_show_sidepane_toggled(GtkMenuItem* menuitem, gpointer user_data) {
+    gtk_widget_set_visible(user_data, GTK_CHECK_MENU_ITEM(menuitem)->active);
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_show_selection_on_invisible (GtkMenuItem *menuitem, gpointer user_data)
-{
-	mainProject->show_invisible_selection = GTK_CHECK_MENU_ITEM(menuitem)->active;
-	render_refresh_rendered_image_on_screen();
+callbacks_show_selection_on_invisible(GtkMenuItem* menuitem, gpointer user_data) {
+    mainProject->show_invisible_selection = GTK_CHECK_MENU_ITEM(menuitem)->active;
+    render_refresh_rendered_image_on_screen();
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_show_cross_on_drill_holes (GtkMenuItem *menuitem, gpointer user_data)
-{
-	screenRenderInfo.show_cross_on_drill_holes = GTK_CHECK_MENU_ITEM(menuitem)->active;
-	render_refresh_rendered_image_on_screen();
+callbacks_show_cross_on_drill_holes(GtkMenuItem* menuitem, gpointer user_data) {
+    screenRenderInfo.show_cross_on_drill_holes = GTK_CHECK_MENU_ITEM(menuitem)->active;
+    render_refresh_rendered_image_on_screen();
 }
 
 /* --------------------------------------------------------- */
 /** View/"Toggle visibility layer X" or Current layer/"Toggle visibility" menu item was activated.
-  * Set the isVisible flag on file X and update the treeview and rendering.
-*/
+ * Set the isVisible flag on file X and update the treeview and rendering.
+ */
 void
-callbacks_toggle_layer_visibility_activate (GtkMenuItem *menuitem, gpointer user_data)
-{
-	int i = GPOINTER_TO_INT(user_data);
-
-	switch (i) {
-	case LAYER_SELECTED:
-		i = callbacks_get_selected_row_index ();
-		/* No break */
-	default:
-		if (0 <= i && i <= mainProject->last_loaded) {
-			mainProject->file[i]->isVisible = !mainProject->file[i]->isVisible;
-		} else {
-			/* Not in range */
-			return;
-		}
-		break;
-	case LAYER_ALL_ON:
-		for (i = 0; i <= mainProject->last_loaded; i++) {
-			mainProject->file[i]->isVisible = TRUE;
-		}
-		break;
-	case LAYER_ALL_OFF:
-		for (i = 0; i <= mainProject->last_loaded; i++) {
-			mainProject->file[i]->isVisible = FALSE;
-		}
-		break;
-	}
-
-	callbacks_update_layer_tree ();
-
-	if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
-		render_refresh_rendered_image_on_screen ();
-	} else {
-		render_recreate_composite_surface (screen.drawing_area);
-		callbacks_force_expose_event_for_screen ();
-	}
+callbacks_toggle_layer_visibility_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    int i = GPOINTER_TO_INT(user_data);
+
+    switch (i) {
+        case LAYER_SELECTED:
+            i = callbacks_get_selected_row_index();
+            /* No break */
+        default:
+            if (0 <= i && i <= mainProject->last_loaded) {
+                mainProject->file[i]->isVisible = !mainProject->file[i]->isVisible;
+            } else {
+                /* Not in range */
+                return;
+            }
+            break;
+        case LAYER_ALL_ON:
+            for (i = 0; i <= mainProject->last_loaded; i++) {
+                mainProject->file[i]->isVisible = TRUE;
+            }
+            break;
+        case LAYER_ALL_OFF:
+            for (i = 0; i <= mainProject->last_loaded; i++) {
+                mainProject->file[i]->isVisible = FALSE;
+            }
+            break;
+    }
+
+    callbacks_update_layer_tree();
+
+    if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
+        render_refresh_rendered_image_on_screen();
+    } else {
+        render_recreate_composite_surface(screen.drawing_area);
+        callbacks_force_expose_event_for_screen();
+    }
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_zoom_in_activate                    (GtkMenuItem     *menuitem,
-                                        gpointer         user_data)
-{
-	render_zoom_display (ZOOM_IN, 0, 0, 0);
+callbacks_zoom_in_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    render_zoom_display(ZOOM_IN, 0, 0, 0);
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_zoom_out_activate                   (GtkMenuItem     *menuitem,
-                                        gpointer         user_data)
-{
-	render_zoom_display (ZOOM_OUT, 0, 0, 0);
+callbacks_zoom_out_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    render_zoom_display(ZOOM_OUT, 0, 0, 0);
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_fit_to_window_activate              (GtkMenuItem     *menuitem,
-                                        gpointer         user_data)
-{
-	gerbv_render_zoom_to_fit_display (mainProject, &screenRenderInfo);
-	render_refresh_rendered_image_on_screen();
+callbacks_fit_to_window_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    gerbv_render_zoom_to_fit_display(mainProject, &screenRenderInfo);
+    render_refresh_rendered_image_on_screen();
 }
 
 /* --------------------------------------------------------- */
 
-static const char *error_type_string(gerbv_message_type_t type) {
-	switch (type) {
-	case GERBV_MESSAGE_FATAL:
-		return _("FATAL");
-	case GERBV_MESSAGE_ERROR:
-		return _("ERROR");
-	case GERBV_MESSAGE_WARNING:
-		return _("Warning");
-	case GERBV_MESSAGE_NOTE:
-		return _("Note");
-	default:
-		return "Unknown";
-	}
+static const char*
+error_type_string(gerbv_message_type_t type) {
+    switch (type) {
+        case GERBV_MESSAGE_FATAL: return _("FATAL");
+        case GERBV_MESSAGE_ERROR: return _("ERROR");
+        case GERBV_MESSAGE_WARNING: return _("Warning");
+        case GERBV_MESSAGE_NOTE: return _("Note");
+        default: return "Unknown";
+    }
 }
 
 /* --------------------------------------------------------- */
 /**
-  * The analyze -> analyze Gerbers  menu item was selected.
-  * Compile statistics on all open Gerber layers and then display
-  * them.
-  *
-  */
+ * The analyze -> analyze Gerbers  menu item was selected.
+ * Compile statistics on all open Gerber layers and then display
+ * them.
+ *
+ */
 void
-callbacks_analyze_active_gerbers_activate(GtkMenuItem *menuitem,
-					gpointer user_data)
-{
-	gerbv_aperture_list_t *aperture_list;
-	gchar *str;
-	int i;
-
-	/* Get a report of stats & errors accumulated from all layers */
-	gerbv_stats_t *stat = generate_gerber_analysis();
-
-	/* General info report */
-	GString *general_report_str = g_string_new(NULL);
-	if (stat->layer_count == 0) {
-		g_string_printf(general_report_str,
-				_("No Gerber layers visible!"));
-	} else {
-		if (stat->error_list->error_text == NULL) {
-			g_string_printf(general_report_str,
-				ngettext("No errors found in %d visible "
-					"Gerber layer.",
-					"No errors found in %d visible "
-					"Gerber layers.",
-					stat->layer_count),
-				stat->layer_count);
-		} else {
-			g_string_printf(general_report_str,
-				ngettext("Found errors in %d visible "
-					"Gerber layer.",
-					"Found errors in %d visible "
-					"Gerber layers.",
-					stat->layer_count),
-				stat->layer_count);
-		}
-	}
-
-	GtkWidget *general_label = gtk_label_new(general_report_str->str);
-	g_string_free(general_report_str, TRUE);
-	gtk_misc_set_alignment(GTK_MISC(general_label), 0, 0);
-	gtk_misc_set_padding(GTK_MISC(general_label), 7, 7);
-	gtk_label_set_selectable(GTK_LABEL(general_label), TRUE);
-
-	struct table *general_table;
-	
-	general_table = table_new_with_columns(3,
-			_("Layer"), G_TYPE_UINT, _("Type"), G_TYPE_STRING,
-			_("Description"), G_TYPE_STRING);
-	table_set_column_align(general_table, 0, 1.0);
-
-	for (i = 0; i <= mainProject->last_loaded; i++) {
-		gerbv_fileinfo_t **files = mainProject->file;
-
-		if (!files[i]
-		||  !files[i]->isVisible
-		||   files[i]->image->layertype != GERBV_LAYERTYPE_RS274X)
-			continue;
-
-		table_add_row(general_table, i + 1,
-				_("RS-274X file"), files[i]->fullPathname);
-
-		str = g_strdup_printf(_("%g x %g %s"),
-				screen_units(fabs(files[i]->image->info->max_x -
-						files[i]->image->info->min_x)),
-				screen_units(fabs(files[i]->image->info->max_y -
-						files[i]->image->info->min_y)),
-				screen_units_str());
-		table_add_row(general_table, i + 1, _("Bounding size"), str);
-		g_free(str);
-
-		/* Check error report on layer */
-		if (stat->layer_count > 0
-		&&  stat->error_list->error_text != NULL) {
-			for (gerbv_error_list_t *err_list = stat->error_list;
-					err_list != NULL;
-					err_list = err_list->next) {
-
-				if (i != err_list->layer - 1)
-					continue;
-
-				table_add_row(general_table, err_list->layer,
-					error_type_string(err_list->type),
-					err_list->error_text);
-			}
-		}
-	}
-
-	/* G codes on active layers */
-	GtkWidget *G_report_window = gtk_scrolled_window_new(NULL, NULL);
-	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(G_report_window),
-			GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
-
-	struct table *G_table =
-		table_new_with_columns(3, _("Code"), G_TYPE_STRING,
-			pgettext("table", "Count"), G_TYPE_UINT,
-			_("Note"), G_TYPE_STRING);
-	table_set_column_align(G_table, 0, 1.0);
-	table_set_column_align(G_table, 1, 1.0);
-	gtk_tree_view_set_headers_clickable(
-			GTK_TREE_VIEW(G_table->widget), TRUE);
-
-	table_add_row(G_table, "G00", stat->G0,  _(gerber_g_code_name(0)));
-	table_add_row(G_table, "G01", stat->G1,  _(gerber_g_code_name(1)));
-	table_add_row(G_table, "G02", stat->G2,  _(gerber_g_code_name(2)));
-	table_add_row(G_table, "G03", stat->G3,  _(gerber_g_code_name(3)));
-	table_add_row(G_table, "G04", stat->G4,  _(gerber_g_code_name(4)));
-	table_add_row(G_table, "G10", stat->G10, _(gerber_g_code_name(10)));
-	table_add_row(G_table, "G11", stat->G11, _(gerber_g_code_name(11)));
-	table_add_row(G_table, "G12", stat->G12, _(gerber_g_code_name(12)));
-	table_add_row(G_table, "G36", stat->G36, _(gerber_g_code_name(36)));
-	table_add_row(G_table, "G37", stat->G37, _(gerber_g_code_name(37)));
-	table_add_row(G_table, "G54", stat->G54, _(gerber_g_code_name(54)));
-	table_add_row(G_table, "G55", stat->G55, _(gerber_g_code_name(55)));
-	table_add_row(G_table, "G70", stat->G70, _(gerber_g_code_name(70)));
-	table_add_row(G_table, "G71", stat->G71, _(gerber_g_code_name(71)));
-	table_add_row(G_table, "G74", stat->G74, _(gerber_g_code_name(74)));
-	table_add_row(G_table, "G75", stat->G75, _(gerber_g_code_name(75)));
-	table_add_row(G_table, "G90", stat->G90, _(gerber_g_code_name(90)));
-	table_add_row(G_table, "G91", stat->G91, _(gerber_g_code_name(91)));
-	table_add_row(G_table, "", stat->G_unknown, _("unknown G-codes"));
-
-	table_set_sortable(G_table);
-	gtk_container_add(GTK_CONTAINER(G_report_window), G_table->widget);
-
-	/* D codes on active layers */
-	GtkWidget *D_report_window = gtk_scrolled_window_new(NULL, NULL);
-	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(D_report_window),
-			GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
-
-	struct table *D_table =
-		table_new_with_columns(3, _("Code"), G_TYPE_STRING,
-			pgettext("table", "Count"), G_TYPE_UINT,
-			_("Note"), G_TYPE_STRING);
-	table_set_column_align(D_table, 0, 1.0);
-	table_set_column_align(D_table, 1, 1.0);
-	gtk_tree_view_set_headers_clickable(
-			GTK_TREE_VIEW(D_table->widget), TRUE);
-	table_add_row(D_table, "D01", stat->D1, _(gerber_d_code_name(1)));
-	table_add_row(D_table, "D02", stat->D2, _(gerber_d_code_name(2)));
-	table_add_row(D_table, "D03", stat->D3, _(gerber_d_code_name(3)));
-	table_add_row(D_table, "", stat->D_unknown, _("unknown D-codes"));
-	table_add_row(D_table, "", stat->D_error, _("D-code errors"));
-
-	table_set_sortable(D_table);
-	gtk_container_add(GTK_CONTAINER(D_report_window), D_table->widget);
-
-	/* M codes on active layers */
-	GtkWidget *M_report_window = gtk_scrolled_window_new(NULL, NULL);
-	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(M_report_window),
-			GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
-
-	struct table *M_table =
-		table_new_with_columns(3, _("Code"), G_TYPE_STRING,
-			pgettext("table", "Count"), G_TYPE_UINT,
-			_("Note"), G_TYPE_STRING);
-	table_set_column_align(M_table, 0, 1.0);
-	table_set_column_align(M_table, 1, 1.0);
-	gtk_tree_view_set_headers_clickable(
-			GTK_TREE_VIEW(M_table->widget), TRUE);
-	table_add_row(M_table, "M00", stat->M0, _(gerber_m_code_name(0)));
-	table_add_row(M_table, "M01", stat->M1, _(gerber_m_code_name(1)));
-	table_add_row(M_table, "M02", stat->M2, _(gerber_m_code_name(2)));
-	table_add_row(M_table, "", stat->M_unknown, _("unknown M-codes"));
-
-	table_set_sortable(M_table);
-	gtk_container_add(GTK_CONTAINER(M_report_window), M_table->widget);
-
-	/* Misc codes */
-	GtkWidget *misc_report_window = gtk_scrolled_window_new(NULL, NULL);
-	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(misc_report_window),
-			GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
-
-	struct table *misc_table =
-		table_new_with_columns(2, _("Code"), G_TYPE_STRING,
-				pgettext("table", "Count"), G_TYPE_UINT);
-	table_set_column_align(misc_table, 1, 1.0);
-	gtk_tree_view_set_headers_clickable(
-			GTK_TREE_VIEW(misc_table->widget), TRUE);
-	table_add_row(misc_table, "X", stat->X);
-	table_add_row(misc_table, "Y", stat->Y);
-	table_add_row(misc_table, "I", stat->I);
-	table_add_row(misc_table, "J", stat->J);
-	table_add_row(misc_table, "*", stat->star);
-	table_add_row(misc_table, _("Unknown"), stat->unknown);
-
-	table_set_sortable(misc_table);
-	gtk_container_add(GTK_CONTAINER(misc_report_window),
-			misc_table->widget);
-
-	/* Apertures definition in input files */
-	GtkWidget *aperture_def_report_window =
-		gtk_scrolled_window_new(NULL, NULL);
-	gtk_scrolled_window_set_policy(
-			GTK_SCROLLED_WINDOW(aperture_def_report_window),
-			GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
-
-	if (stat->aperture_list->number == -1) {
-		GtkWidget *aperture_def_label = gtk_label_new(
-			_("No aperture definitions found in active Gerber file(s)!"));
-		gtk_misc_set_alignment(GTK_MISC(aperture_def_label), 0, 0);
-		gtk_misc_set_padding(GTK_MISC(aperture_def_label), 7, 7);
-		gtk_label_set_selectable(GTK_LABEL(aperture_def_label), TRUE);
-		gtk_scrolled_window_add_with_viewport(
-				GTK_SCROLLED_WINDOW(aperture_def_report_window),
-				aperture_def_label);
-	} else {
-		struct table *aperture_def_table = table_new_with_columns(6,
-				_("Layer"), G_TYPE_UINT,
-				_("D code"), G_TYPE_STRING,
-				_("Aperture"), G_TYPE_STRING,
-				_("Param[0]"), G_TYPE_DOUBLE,
-				_("Param[1]"), G_TYPE_DOUBLE,
-				_("Param[2]"), G_TYPE_DOUBLE);
-		table_set_column_align(aperture_def_table, 0, 1.0);
-		table_set_column_align(aperture_def_table, 1, 1.0);
-		gtk_tree_view_set_headers_clickable(
-				GTK_TREE_VIEW(aperture_def_table->widget), TRUE);
-		gtk_tree_view_set_search_column(
-				GTK_TREE_VIEW(aperture_def_table->widget), 1);
-
-		GString *gstr = g_string_new(NULL);
-		for (aperture_list = stat->aperture_list;
-				aperture_list != NULL;
-				aperture_list = aperture_list->next) {
-			g_string_printf(gstr, "D%d", aperture_list->number);
-			table_add_row(aperture_def_table,
-				aperture_list->layer,
-				gstr->str,
-				_(gerbv_aperture_type_name(
-					aperture_list->type)),
-				aperture_list->parameter[0],
-				aperture_list->parameter[1],
-				aperture_list->parameter[2]);
-		}
-		g_string_free(gstr, TRUE);
-		table_set_sortable(aperture_def_table);
-		gtk_container_add(GTK_CONTAINER(aperture_def_report_window),
-				aperture_def_table->widget);
-	}
-
-	/* Gerber aperture usage on active layers */
-	GtkWidget *aperture_usage_report_window =
-		gtk_scrolled_window_new(NULL, NULL);
-	gtk_scrolled_window_set_policy(
-			GTK_SCROLLED_WINDOW(aperture_usage_report_window),
-			GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
-
-	unsigned int aperture_count = 0;
-
-	if (stat->D_code_list->number == -1) {
-		GtkWidget *aperture_usage_label = gtk_label_new(
-			_("No apertures used in Gerber file(s)!"));
-		gtk_misc_set_alignment(GTK_MISC(aperture_usage_label), 0, 0);
-		gtk_misc_set_padding(GTK_MISC(aperture_usage_label), 7, 7);
-		gtk_label_set_selectable(GTK_LABEL(aperture_usage_label), TRUE);
-		gtk_scrolled_window_add_with_viewport(
-			GTK_SCROLLED_WINDOW(aperture_usage_report_window),
-			aperture_usage_label);
-	} else {
-		struct table *aperture_usage_table = table_new_with_columns(2,
-				_("Code"), G_TYPE_STRING,
-				pgettext("table", "Count"), G_TYPE_UINT);
-		table_set_column_align(aperture_usage_table, 0, 1.0);
-		table_set_column_align(aperture_usage_table, 1, 1.0);
-		gtk_tree_view_set_headers_clickable(
-			GTK_TREE_VIEW(aperture_usage_table->widget), TRUE);
-
-		GString *gstr = g_string_new(NULL);
-		for (aperture_list = stat->D_code_list;
-				aperture_list != NULL;
-				aperture_list = aperture_list->next) {
-			g_string_printf(gstr, "D%d", aperture_list->number);
-			table_add_row(aperture_usage_table,
-					gstr->str,
-					aperture_list->count);
-			aperture_count += aperture_list->count;
-		}
-		g_string_free(gstr, TRUE);
-		table_add_row(aperture_usage_table, _("Total"), aperture_count);
-		table_set_sortable(aperture_usage_table);
-		gtk_container_add( GTK_CONTAINER(aperture_usage_report_window),
-				aperture_usage_table->widget);
-	}
-
-	/* Create top level dialog window for report */
-	GtkWidget *analyze_active_gerbers;
-	analyze_active_gerbers = gtk_dialog_new_with_buttons(
-			_("Gerber codes report on visible layers"),
-			NULL, GTK_DIALOG_DESTROY_WITH_PARENT,
-			GTK_STOCK_OK, GTK_RESPONSE_ACCEPT, NULL);
-	gtk_container_set_border_width(GTK_CONTAINER (analyze_active_gerbers), 5);
-
-	gtk_dialog_set_default_response (GTK_DIALOG(analyze_active_gerbers),
-			GTK_RESPONSE_ACCEPT);
-	g_signal_connect_after (G_OBJECT(analyze_active_gerbers),
-			"response",
-			G_CALLBACK (gtk_widget_destroy),
-			GTK_WIDGET(analyze_active_gerbers));
-
-	/* Put general report text into scrolled window */
-	GtkWidget *general_report_window =
-		gtk_scrolled_window_new(NULL, NULL);
-	gtk_scrolled_window_set_policy(
-			GTK_SCROLLED_WINDOW(general_report_window),
-			GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
-
-	GtkWidget *vbox = gtk_vbox_new(0, 0);
-	gtk_box_pack_start(GTK_BOX(vbox), general_label, 0, 0, 0);
-	gtk_box_pack_start(GTK_BOX(vbox), general_table->widget, 0, 0, 0);
-	gtk_scrolled_window_add_with_viewport(
-			GTK_SCROLLED_WINDOW(general_report_window), vbox);
-
-	/* Create tabbed notebook widget and add report widgets. */
-	GtkWidget *notebook = gtk_notebook_new();
-
-	gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
-			GTK_WIDGET(general_report_window),
-			gtk_label_new(_("General")));
-
-	gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
-			GTK_WIDGET(G_report_window),
-			gtk_label_new(_("G codes")));
-
-	gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
-			GTK_WIDGET(D_report_window),
-			gtk_label_new(_("D codes")));
-
-	gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
-			GTK_WIDGET(M_report_window),
-			gtk_label_new(_("M codes")));
-
-	gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
-			GTK_WIDGET(misc_report_window),
-			gtk_label_new(_("Misc. codes")));
-
-	gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
-			GTK_WIDGET(aperture_def_report_window),
-			gtk_label_new(_("Aperture definitions")));
-
-	gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
-			GTK_WIDGET(aperture_usage_report_window),
-			gtk_label_new(_("Aperture usage")));
-
-	/* Now put notebook into dialog window and show the whole thing */
-	gtk_container_add(
-			GTK_CONTAINER(GTK_DIALOG(analyze_active_gerbers)->vbox),
-			GTK_WIDGET(notebook));
-
-	if (screen.settings) {
-		analyze_window_size_restore(analyze_active_gerbers);
-		g_signal_connect (G_OBJECT(analyze_active_gerbers), "response",
-				G_CALLBACK (analyze_window_size_store),
-				GTK_WIDGET(analyze_active_gerbers));
-	} else {
-		gtk_window_set_default_size(GTK_WINDOW(analyze_active_gerbers),
-						640, 320);
-	}
-
-	gtk_widget_show_all(analyze_active_gerbers);
-
-	gerbv_stats_destroy(stat);	
+callbacks_analyze_active_gerbers_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    gerbv_aperture_list_t* aperture_list;
+    gchar*                 str;
+    int                    i;
+
+    /* Get a report of stats & errors accumulated from all layers */
+    gerbv_stats_t* stat = generate_gerber_analysis();
+
+    /* General info report */
+    GString* general_report_str = g_string_new(NULL);
+    if (stat->layer_count == 0) {
+        g_string_printf(general_report_str, _("No Gerber layers visible!"));
+    } else {
+        if (stat->error_list->error_text == NULL) {
+            g_string_printf(
+                general_report_str,
+                ngettext(
+                    "No errors found in %d visible "
+                    "Gerber layer.",
+                    "No errors found in %d visible "
+                    "Gerber layers.",
+                    stat->layer_count
+                ),
+                stat->layer_count
+            );
+        } else {
+            g_string_printf(
+                general_report_str,
+                ngettext(
+                    "Found errors in %d visible "
+                    "Gerber layer.",
+                    "Found errors in %d visible "
+                    "Gerber layers.",
+                    stat->layer_count
+                ),
+                stat->layer_count
+            );
+        }
+    }
+
+    GtkWidget* general_label = gtk_label_new(general_report_str->str);
+    g_string_free(general_report_str, TRUE);
+    gtk_misc_set_alignment(GTK_MISC(general_label), 0, 0);
+    gtk_misc_set_padding(GTK_MISC(general_label), 7, 7);
+    gtk_label_set_selectable(GTK_LABEL(general_label), TRUE);
+
+    struct table* general_table;
+
+    general_table =
+        table_new_with_columns(3, _("Layer"), G_TYPE_UINT, _("Type"), G_TYPE_STRING, _("Description"), G_TYPE_STRING);
+    table_set_column_align(general_table, 0, 1.0);
+
+    for (i = 0; i <= mainProject->last_loaded; i++) {
+        gerbv_fileinfo_t** files = mainProject->file;
+
+        if (!files[i] || !files[i]->isVisible || files[i]->image->layertype != GERBV_LAYERTYPE_RS274X)
+            continue;
+
+        table_add_row(general_table, i + 1, _("RS-274X file"), files[i]->fullPathname);
+
+        str = g_strdup_printf(
+            _("%g x %g %s"), screen_units(fabs(files[i]->image->info->max_x - files[i]->image->info->min_x)),
+            screen_units(fabs(files[i]->image->info->max_y - files[i]->image->info->min_y)), screen_units_str()
+        );
+        table_add_row(general_table, i + 1, _("Bounding size"), str);
+        g_free(str);
+
+        /* Check error report on layer */
+        if (stat->layer_count > 0 && stat->error_list->error_text != NULL) {
+            for (gerbv_error_list_t* err_list = stat->error_list; err_list != NULL; err_list = err_list->next) {
+
+                if (i != err_list->layer - 1)
+                    continue;
+
+                table_add_row(general_table, err_list->layer, error_type_string(err_list->type), err_list->error_text);
+            }
+        }
+    }
+
+    /* G codes on active layers */
+    GtkWidget* G_report_window = gtk_scrolled_window_new(NULL, NULL);
+    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(G_report_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
+
+    struct table* G_table = table_new_with_columns(
+        3, _("Code"), G_TYPE_STRING, pgettext("table", "Count"), G_TYPE_UINT, _("Note"), G_TYPE_STRING
+    );
+    table_set_column_align(G_table, 0, 1.0);
+    table_set_column_align(G_table, 1, 1.0);
+    gtk_tree_view_set_headers_clickable(GTK_TREE_VIEW(G_table->widget), TRUE);
+
+    table_add_row(G_table, "G00", stat->G0, _(gerber_g_code_name(0)));
+    table_add_row(G_table, "G01", stat->G1, _(gerber_g_code_name(1)));
+    table_add_row(G_table, "G02", stat->G2, _(gerber_g_code_name(2)));
+    table_add_row(G_table, "G03", stat->G3, _(gerber_g_code_name(3)));
+    table_add_row(G_table, "G04", stat->G4, _(gerber_g_code_name(4)));
+    table_add_row(G_table, "G10", stat->G10, _(gerber_g_code_name(10)));
+    table_add_row(G_table, "G11", stat->G11, _(gerber_g_code_name(11)));
+    table_add_row(G_table, "G12", stat->G12, _(gerber_g_code_name(12)));
+    table_add_row(G_table, "G36", stat->G36, _(gerber_g_code_name(36)));
+    table_add_row(G_table, "G37", stat->G37, _(gerber_g_code_name(37)));
+    table_add_row(G_table, "G54", stat->G54, _(gerber_g_code_name(54)));
+    table_add_row(G_table, "G55", stat->G55, _(gerber_g_code_name(55)));
+    table_add_row(G_table, "G70", stat->G70, _(gerber_g_code_name(70)));
+    table_add_row(G_table, "G71", stat->G71, _(gerber_g_code_name(71)));
+    table_add_row(G_table, "G74", stat->G74, _(gerber_g_code_name(74)));
+    table_add_row(G_table, "G75", stat->G75, _(gerber_g_code_name(75)));
+    table_add_row(G_table, "G90", stat->G90, _(gerber_g_code_name(90)));
+    table_add_row(G_table, "G91", stat->G91, _(gerber_g_code_name(91)));
+    table_add_row(G_table, "", stat->G_unknown, _("unknown G-codes"));
+
+    table_set_sortable(G_table);
+    gtk_container_add(GTK_CONTAINER(G_report_window), G_table->widget);
+
+    /* D codes on active layers */
+    GtkWidget* D_report_window = gtk_scrolled_window_new(NULL, NULL);
+    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(D_report_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
+
+    struct table* D_table = table_new_with_columns(
+        3, _("Code"), G_TYPE_STRING, pgettext("table", "Count"), G_TYPE_UINT, _("Note"), G_TYPE_STRING
+    );
+    table_set_column_align(D_table, 0, 1.0);
+    table_set_column_align(D_table, 1, 1.0);
+    gtk_tree_view_set_headers_clickable(GTK_TREE_VIEW(D_table->widget), TRUE);
+    table_add_row(D_table, "D01", stat->D1, _(gerber_d_code_name(1)));
+    table_add_row(D_table, "D02", stat->D2, _(gerber_d_code_name(2)));
+    table_add_row(D_table, "D03", stat->D3, _(gerber_d_code_name(3)));
+    table_add_row(D_table, "", stat->D_unknown, _("unknown D-codes"));
+    table_add_row(D_table, "", stat->D_error, _("D-code errors"));
+
+    table_set_sortable(D_table);
+    gtk_container_add(GTK_CONTAINER(D_report_window), D_table->widget);
+
+    /* M codes on active layers */
+    GtkWidget* M_report_window = gtk_scrolled_window_new(NULL, NULL);
+    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(M_report_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
+
+    struct table* M_table = table_new_with_columns(
+        3, _("Code"), G_TYPE_STRING, pgettext("table", "Count"), G_TYPE_UINT, _("Note"), G_TYPE_STRING
+    );
+    table_set_column_align(M_table, 0, 1.0);
+    table_set_column_align(M_table, 1, 1.0);
+    gtk_tree_view_set_headers_clickable(GTK_TREE_VIEW(M_table->widget), TRUE);
+    table_add_row(M_table, "M00", stat->M0, _(gerber_m_code_name(0)));
+    table_add_row(M_table, "M01", stat->M1, _(gerber_m_code_name(1)));
+    table_add_row(M_table, "M02", stat->M2, _(gerber_m_code_name(2)));
+    table_add_row(M_table, "", stat->M_unknown, _("unknown M-codes"));
+
+    table_set_sortable(M_table);
+    gtk_container_add(GTK_CONTAINER(M_report_window), M_table->widget);
+
+    /* Misc codes */
+    GtkWidget* misc_report_window = gtk_scrolled_window_new(NULL, NULL);
+    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(misc_report_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
+
+    struct table* misc_table =
+        table_new_with_columns(2, _("Code"), G_TYPE_STRING, pgettext("table", "Count"), G_TYPE_UINT);
+    table_set_column_align(misc_table, 1, 1.0);
+    gtk_tree_view_set_headers_clickable(GTK_TREE_VIEW(misc_table->widget), TRUE);
+    table_add_row(misc_table, "X", stat->X);
+    table_add_row(misc_table, "Y", stat->Y);
+    table_add_row(misc_table, "I", stat->I);
+    table_add_row(misc_table, "J", stat->J);
+    table_add_row(misc_table, "*", stat->star);
+    table_add_row(misc_table, _("Unknown"), stat->unknown);
+
+    table_set_sortable(misc_table);
+    gtk_container_add(GTK_CONTAINER(misc_report_window), misc_table->widget);
+
+    /* Apertures definition in input files */
+    GtkWidget* aperture_def_report_window = gtk_scrolled_window_new(NULL, NULL);
+    gtk_scrolled_window_set_policy(
+        GTK_SCROLLED_WINDOW(aperture_def_report_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC
+    );
+
+    if (stat->aperture_list->number == -1) {
+        GtkWidget* aperture_def_label = gtk_label_new(_("No aperture definitions found in active Gerber file(s)!"));
+        gtk_misc_set_alignment(GTK_MISC(aperture_def_label), 0, 0);
+        gtk_misc_set_padding(GTK_MISC(aperture_def_label), 7, 7);
+        gtk_label_set_selectable(GTK_LABEL(aperture_def_label), TRUE);
+        gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(aperture_def_report_window), aperture_def_label);
+    } else {
+        struct table* aperture_def_table = table_new_with_columns(
+            6, _("Layer"), G_TYPE_UINT, _("D code"), G_TYPE_STRING, _("Aperture"), G_TYPE_STRING, _("Param[0]"),
+            G_TYPE_DOUBLE, _("Param[1]"), G_TYPE_DOUBLE, _("Param[2]"), G_TYPE_DOUBLE
+        );
+        table_set_column_align(aperture_def_table, 0, 1.0);
+        table_set_column_align(aperture_def_table, 1, 1.0);
+        gtk_tree_view_set_headers_clickable(GTK_TREE_VIEW(aperture_def_table->widget), TRUE);
+        gtk_tree_view_set_search_column(GTK_TREE_VIEW(aperture_def_table->widget), 1);
+
+        GString* gstr = g_string_new(NULL);
+        for (aperture_list = stat->aperture_list; aperture_list != NULL; aperture_list = aperture_list->next) {
+            g_string_printf(gstr, "D%d", aperture_list->number);
+            table_add_row(
+                aperture_def_table, aperture_list->layer, gstr->str, _(gerbv_aperture_type_name(aperture_list->type)),
+                aperture_list->parameter[0], aperture_list->parameter[1], aperture_list->parameter[2]
+            );
+        }
+        g_string_free(gstr, TRUE);
+        table_set_sortable(aperture_def_table);
+        gtk_container_add(GTK_CONTAINER(aperture_def_report_window), aperture_def_table->widget);
+    }
+
+    /* Gerber aperture usage on active layers */
+    GtkWidget* aperture_usage_report_window = gtk_scrolled_window_new(NULL, NULL);
+    gtk_scrolled_window_set_policy(
+        GTK_SCROLLED_WINDOW(aperture_usage_report_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC
+    );
+
+    unsigned int aperture_count = 0;
+
+    if (stat->D_code_list->number == -1) {
+        GtkWidget* aperture_usage_label = gtk_label_new(_("No apertures used in Gerber file(s)!"));
+        gtk_misc_set_alignment(GTK_MISC(aperture_usage_label), 0, 0);
+        gtk_misc_set_padding(GTK_MISC(aperture_usage_label), 7, 7);
+        gtk_label_set_selectable(GTK_LABEL(aperture_usage_label), TRUE);
+        gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(aperture_usage_report_window), aperture_usage_label);
+    } else {
+        struct table* aperture_usage_table =
+            table_new_with_columns(2, _("Code"), G_TYPE_STRING, pgettext("table", "Count"), G_TYPE_UINT);
+        table_set_column_align(aperture_usage_table, 0, 1.0);
+        table_set_column_align(aperture_usage_table, 1, 1.0);
+        gtk_tree_view_set_headers_clickable(GTK_TREE_VIEW(aperture_usage_table->widget), TRUE);
+
+        GString* gstr = g_string_new(NULL);
+        for (aperture_list = stat->D_code_list; aperture_list != NULL; aperture_list = aperture_list->next) {
+            g_string_printf(gstr, "D%d", aperture_list->number);
+            table_add_row(aperture_usage_table, gstr->str, aperture_list->count);
+            aperture_count += aperture_list->count;
+        }
+        g_string_free(gstr, TRUE);
+        table_add_row(aperture_usage_table, _("Total"), aperture_count);
+        table_set_sortable(aperture_usage_table);
+        gtk_container_add(GTK_CONTAINER(aperture_usage_report_window), aperture_usage_table->widget);
+    }
+
+    /* Create top level dialog window for report */
+    GtkWidget* analyze_active_gerbers;
+    analyze_active_gerbers = gtk_dialog_new_with_buttons(
+        _("Gerber codes report on visible layers"), NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_STOCK_OK,
+        GTK_RESPONSE_ACCEPT, NULL
+    );
+    gtk_container_set_border_width(GTK_CONTAINER(analyze_active_gerbers), 5);
+
+    gtk_dialog_set_default_response(GTK_DIALOG(analyze_active_gerbers), GTK_RESPONSE_ACCEPT);
+    g_signal_connect_after(
+        G_OBJECT(analyze_active_gerbers), "response", G_CALLBACK(gtk_widget_destroy), GTK_WIDGET(analyze_active_gerbers)
+    );
+
+    /* Put general report text into scrolled window */
+    GtkWidget* general_report_window = gtk_scrolled_window_new(NULL, NULL);
+    gtk_scrolled_window_set_policy(
+        GTK_SCROLLED_WINDOW(general_report_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC
+    );
+
+    GtkWidget* vbox = gtk_vbox_new(0, 0);
+    gtk_box_pack_start(GTK_BOX(vbox), general_label, 0, 0, 0);
+    gtk_box_pack_start(GTK_BOX(vbox), general_table->widget, 0, 0, 0);
+    gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(general_report_window), vbox);
+
+    /* Create tabbed notebook widget and add report widgets. */
+    GtkWidget* notebook = gtk_notebook_new();
+
+    gtk_notebook_append_page(GTK_NOTEBOOK(notebook), GTK_WIDGET(general_report_window), gtk_label_new(_("General")));
+
+    gtk_notebook_append_page(GTK_NOTEBOOK(notebook), GTK_WIDGET(G_report_window), gtk_label_new(_("G codes")));
+
+    gtk_notebook_append_page(GTK_NOTEBOOK(notebook), GTK_WIDGET(D_report_window), gtk_label_new(_("D codes")));
+
+    gtk_notebook_append_page(GTK_NOTEBOOK(notebook), GTK_WIDGET(M_report_window), gtk_label_new(_("M codes")));
+
+    gtk_notebook_append_page(GTK_NOTEBOOK(notebook), GTK_WIDGET(misc_report_window), gtk_label_new(_("Misc. codes")));
+
+    gtk_notebook_append_page(
+        GTK_NOTEBOOK(notebook), GTK_WIDGET(aperture_def_report_window), gtk_label_new(_("Aperture definitions"))
+    );
+
+    gtk_notebook_append_page(
+        GTK_NOTEBOOK(notebook), GTK_WIDGET(aperture_usage_report_window), gtk_label_new(_("Aperture usage"))
+    );
+
+    /* Now put notebook into dialog window and show the whole thing */
+    gtk_container_add(GTK_CONTAINER(GTK_DIALOG(analyze_active_gerbers)->vbox), GTK_WIDGET(notebook));
+
+    if (screen.settings) {
+        analyze_window_size_restore(analyze_active_gerbers);
+        g_signal_connect(
+            G_OBJECT(analyze_active_gerbers), "response", G_CALLBACK(analyze_window_size_store),
+            GTK_WIDGET(analyze_active_gerbers)
+        );
+    } else {
+        gtk_window_set_default_size(GTK_WINDOW(analyze_active_gerbers), 640, 320);
+    }
+
+    gtk_widget_show_all(analyze_active_gerbers);
+
+    gerbv_stats_destroy(stat);
 }
 
 /* --------------------------------------------------------- */
 /**
-  * The analyze -> analyze drill file  menu item was selected.
-  * Complie statistics on all open drill layers and then display
-  * them.
-  *
-  */
+ * The analyze -> analyze drill file  menu item was selected.
+ * Complie statistics on all open drill layers and then display
+ * them.
+ *
+ */
 void
-callbacks_analyze_active_drill_activate(GtkMenuItem *menuitem,
-					gpointer user_data)
-{
-	gchar *str;
-	int i;
-
-	gerbv_drill_stats_t *stat = generate_drill_analysis();
-
-	/* General info report */
-	GString *general_report_str = g_string_new(NULL);
-	if (stat->layer_count == 0) {
-		g_string_printf(general_report_str,
-				_("No drill layers visible!"));
-	} else {
-		if (stat->error_list->error_text == NULL) {
-			g_string_printf(general_report_str,
-				ngettext("No errors found in %d visible "
-					"drill layer.",
-					"No errors found in %d visible "
-					"drill layers.",
-					stat->layer_count),
-				stat->layer_count);
-		} else {
-			g_string_printf(general_report_str,
-				ngettext("Found errors found in %d visible "
-					"drill layer.",
-					"Found errors found in %d visible "
-					"drill layers.",
-					stat->layer_count),
-				stat->layer_count);
-		}
-	}
-
-	GtkWidget *general_label = gtk_label_new(general_report_str->str);
-	g_string_free(general_report_str, TRUE);
-	gtk_misc_set_alignment(GTK_MISC(general_label), 0, 0);
-	gtk_misc_set_padding(GTK_MISC(general_label), 7, 7);
-	gtk_label_set_selectable(GTK_LABEL(general_label), TRUE);
-
-	struct table *general_table;
-	
-	general_table = table_new_with_columns(3,
-			_("Layer"), G_TYPE_UINT, _("Type"), G_TYPE_STRING,
-			_("Description"), G_TYPE_STRING);
-	table_set_column_align(general_table, 0, 1.0);
-
-	for (i = 0; i <= mainProject->last_loaded; i++) {
-		gerbv_fileinfo_t **files = mainProject->file;
-
-		if (!files[i]
-		||  !files[i]->isVisible
-		||   files[i]->image->layertype != GERBV_LAYERTYPE_DRILL)
-			continue;
-
-		table_add_row(general_table, i + 1,
-				_("Excellon file"), files[i]->fullPathname);
-
-		str = g_strdup_printf(_("%g x %g %s"),
-				screen_units(fabs(files[i]->image->info->max_x -
-						files[i]->image->info->min_x)),
-				screen_units(fabs(files[i]->image->info->max_y -
-						files[i]->image->info->min_y)),
-				screen_units_str());
-		table_add_row(general_table, i + 1, _("Bounding size"), str);
-		g_free(str);
-
-		/* Check error report on layer */
-		if (stat->layer_count > 0
-		&&  stat->error_list->error_text != NULL) {
-			for (gerbv_error_list_t *err_list = stat->error_list;
-					err_list != NULL;
-					err_list = err_list->next) {
-
-				if (i != err_list->layer - 1)
-					continue;
-
-				table_add_row(general_table, err_list->layer,
-					error_type_string(err_list->type),
-					err_list->error_text);
-			}
-		}
-	}
-
-	/* G codes on active layers */
-	GtkWidget *G_report_window = gtk_scrolled_window_new(NULL, NULL);
-	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(G_report_window),
-			GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
-
-	struct table *G_table =
-		table_new_with_columns(3, _("Code"), G_TYPE_STRING,
-			pgettext("table", "Count"), G_TYPE_UINT,
-			_("Note"), G_TYPE_STRING);
-	table_set_column_align(G_table, 0, 1.0);
-	table_set_column_align(G_table, 1, 1.0);
-	gtk_tree_view_set_headers_clickable(
-			GTK_TREE_VIEW(G_table->widget), TRUE);
-
-	table_add_row(G_table, "G00", stat->G00, _(drill_g_code_name(0)));
-	table_add_row(G_table, "G01", stat->G01, _(drill_g_code_name(1)));
-	table_add_row(G_table, "G02", stat->G02, _(drill_g_code_name(2)));
-	table_add_row(G_table, "G03", stat->G03, _(drill_g_code_name(3)));
-	table_add_row(G_table, "G04", stat->G04, _(drill_g_code_name(4)));
-	table_add_row(G_table, "G05", stat->G05, _(drill_g_code_name(5)));
-	table_add_row(G_table, "G85", stat->G85, _(drill_g_code_name(85)));
-	table_add_row(G_table, "G90", stat->G90, _(drill_g_code_name(90)));
-	table_add_row(G_table, "G91", stat->G91, _(drill_g_code_name(91)));
-	table_add_row(G_table, "G93", stat->G93, _(drill_g_code_name(93)));
-	table_add_row(G_table, "", stat->G_unknown, _("unknown G-codes"));
-
-	table_set_sortable(G_table);
-	gtk_container_add(GTK_CONTAINER(G_report_window), G_table->widget);
-
-	/* M codes on active layers */
-	GtkWidget *M_report_window = gtk_scrolled_window_new(NULL, NULL);
-	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(M_report_window),
-			GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
-
-	struct table *M_table =
-		table_new_with_columns(3, _("Code"), G_TYPE_STRING,
-			pgettext("table", "Count"), G_TYPE_UINT,
-			_("Note"), G_TYPE_STRING);
-	table_set_column_align(M_table, 0, 1.0);
-	table_set_column_align(M_table, 1, 1.0);
-	gtk_tree_view_set_headers_clickable(
-			GTK_TREE_VIEW(M_table->widget), TRUE);
-	table_add_row(M_table, "M00", stat->M00, _(drill_m_code_name(0)));
-	table_add_row(M_table, "M01", stat->M01, _(drill_m_code_name(1)));
-	table_add_row(M_table, "M18", stat->M18, _(drill_m_code_name(18)));
-	table_add_row(M_table, "M25", stat->M25, _(drill_m_code_name(25)));
-	table_add_row(M_table, "M30", stat->M30, _(drill_m_code_name(30)));
-	table_add_row(M_table, "M45", stat->M45, _(drill_m_code_name(45)));
-	table_add_row(M_table, "M47", stat->M47, _(drill_m_code_name(47)));
-	table_add_row(M_table, "M48", stat->M48, _(drill_m_code_name(48)));
-	table_add_row(M_table, "M71", stat->M71, _(drill_m_code_name(71)));
-	table_add_row(M_table, "M72", stat->M72, _(drill_m_code_name(72)));
-	table_add_row(M_table, "M95", stat->M95, _(drill_m_code_name(95)));
-	table_add_row(M_table, "M97", stat->M97, _(drill_m_code_name(97)));
-	table_add_row(M_table, "M98", stat->M98, _(drill_m_code_name(98)));
-	table_add_row(M_table, "", stat->M_unknown, _("unknown M-codes"));
-
-	table_set_sortable(M_table);
-	gtk_container_add(GTK_CONTAINER(M_report_window), M_table->widget);
-
-	/* Misc codes */
-	GtkWidget *misc_report_window = gtk_scrolled_window_new(NULL, NULL);
-	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(misc_report_window),
-			GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
-
-	struct table *misc_table =
-		table_new_with_columns(2,
-				/* Count is string for value hide. */
-				pgettext("table", "Count"), G_TYPE_STRING,
-				_("Code"), G_TYPE_STRING);
-	table_set_column_align(misc_table, 0, 1.0);
-	str = g_strdup_printf("%d", stat->comment);
-	table_add_row(misc_table, str,_("Comments"));
-	g_free(str);
-	str = g_strdup_printf("%d", stat->unknown);
-	table_add_row(misc_table, str, _("Unknown codes"));
-	g_free(str);
-	str = g_strdup_printf("%d", stat->R);
-	table_add_row(misc_table, str, _("Repeat hole (R)"));
-	g_free(str);
-	if (stat->detect != NULL ) {
-		table_add_row(misc_table, "", stat->detect);
-	}
-
-	table_set_sortable(misc_table);
-	gtk_container_add(GTK_CONTAINER(misc_report_window),
-			misc_table->widget);
-
-	/* Drill usage on active layers */
-	GtkWidget *drill_usage_report_window =
-			gtk_scrolled_window_new(NULL, NULL);
-	gtk_scrolled_window_set_policy(
-			GTK_SCROLLED_WINDOW(drill_usage_report_window),
-			GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
-
-	struct table *drill_usage_table = table_new_with_columns(4,
-			_("Drill no."), G_TYPE_UINT,
-			_("Dia."), G_TYPE_DOUBLE,
-			_("Units"), G_TYPE_STRING,
-			pgettext("table", "Count"), G_TYPE_UINT);
-
-	table_set_column_align(drill_usage_table, 0, 1.0);
-	table_set_column_align(drill_usage_table, 3, 1.0);
-	gtk_tree_view_set_headers_clickable(
-		GTK_TREE_VIEW(drill_usage_table->widget), TRUE);
-
-	gerbv_drill_list_t *drill_list;
-	for (drill_list = stat->drill_list;
-			drill_list != NULL; drill_list = drill_list->next) {
-		if (drill_list->drill_num == -1)
-			break;	/* No drill list */
-
-		table_add_row(drill_usage_table,
-				drill_list->drill_num,
-				drill_list->drill_size,
-				drill_list->drill_unit,
-				drill_list->drill_count);
-	}
-
-	table_set_sortable(drill_usage_table);
-	gtk_container_add(GTK_CONTAINER(drill_usage_report_window),
-			drill_usage_table->widget);
-
-	/* Create top level dialog window for report */
-	GtkWidget *analyze_active_drill;
-	analyze_active_drill = gtk_dialog_new_with_buttons(
-			_("Drill codes report on visible layers"),
-			NULL, GTK_DIALOG_DESTROY_WITH_PARENT,
-			GTK_STOCK_OK, GTK_RESPONSE_ACCEPT, NULL);
-	gtk_container_set_border_width (GTK_CONTAINER (analyze_active_drill), 5);
-
-	gtk_dialog_set_default_response (GTK_DIALOG(analyze_active_drill),
-			GTK_RESPONSE_ACCEPT);
-	g_signal_connect_after (G_OBJECT(analyze_active_drill),
-			"response",
-			G_CALLBACK (gtk_widget_destroy),
-			GTK_WIDGET(analyze_active_drill));
-
-	/* Put general report text into scrolled window */
-	GtkWidget *general_report_window =
-		gtk_scrolled_window_new(NULL, NULL);
-	gtk_scrolled_window_set_policy(
-			GTK_SCROLLED_WINDOW(general_report_window),
-			GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
-
-	GtkWidget *vbox = gtk_vbox_new(0, 0);
-	gtk_box_pack_start(GTK_BOX(vbox), general_label, 0, 0, 0);
-	gtk_box_pack_start(GTK_BOX(vbox), general_table->widget, 0, 0, 0);
-	gtk_scrolled_window_add_with_viewport(
-			GTK_SCROLLED_WINDOW(general_report_window), vbox);
-
-	/* Create tabbed notebook widget and add report widgets. */
-	GtkWidget *notebook = gtk_notebook_new();
-
-	gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
-			GTK_WIDGET(general_report_window),
-			gtk_label_new(_("General")));
-
-	gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
-			GTK_WIDGET(G_report_window),
-			gtk_label_new(_("G codes")));
-
-	gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
-			GTK_WIDGET(M_report_window),
-			gtk_label_new(_("M codes")));
-
-	gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
-			GTK_WIDGET(misc_report_window),
-			gtk_label_new(_("Misc. codes")));
-
-	gtk_notebook_append_page(GTK_NOTEBOOK(notebook),
-			GTK_WIDGET(drill_usage_report_window),
-			gtk_label_new(_("Drill usage")));
-
-	/* Now put notebook into dialog window and show the whole thing */
-	gtk_container_add(GTK_CONTAINER(GTK_DIALOG(analyze_active_drill)->vbox),
-			GTK_WIDGET(notebook));
-
-	if (screen.settings) {
-		analyze_window_size_restore(analyze_active_drill);
-		g_signal_connect (G_OBJECT(analyze_active_drill), "response",
-				G_CALLBACK (analyze_window_size_store),
-				GTK_WIDGET(analyze_active_drill));
-	} else {
-		gtk_window_set_default_size(GTK_WINDOW(analyze_active_drill),
-						640, 320);
-	}
-
-	gtk_widget_show_all(analyze_active_drill);
-
-	gerbv_drill_stats_destroy(stat);
-}
+callbacks_analyze_active_drill_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    gchar* str;
+    int    i;
+
+    gerbv_drill_stats_t* stat = generate_drill_analysis();
+
+    /* General info report */
+    GString* general_report_str = g_string_new(NULL);
+    if (stat->layer_count == 0) {
+        g_string_printf(general_report_str, _("No drill layers visible!"));
+    } else {
+        if (stat->error_list->error_text == NULL) {
+            g_string_printf(
+                general_report_str,
+                ngettext(
+                    "No errors found in %d visible "
+                    "drill layer.",
+                    "No errors found in %d visible "
+                    "drill layers.",
+                    stat->layer_count
+                ),
+                stat->layer_count
+            );
+        } else {
+            g_string_printf(
+                general_report_str,
+                ngettext(
+                    "Found errors found in %d visible "
+                    "drill layer.",
+                    "Found errors found in %d visible "
+                    "drill layers.",
+                    stat->layer_count
+                ),
+                stat->layer_count
+            );
+        }
+    }
 
-/* --------------------------------------------------------- */
-void
-callbacks_control_gerber_options_activate     (GtkMenuItem     *menuitem,
-                                        gpointer         user_data)
-{
+    GtkWidget* general_label = gtk_label_new(general_report_str->str);
+    g_string_free(general_report_str, TRUE);
+    gtk_misc_set_alignment(GTK_MISC(general_label), 0, 0);
+    gtk_misc_set_padding(GTK_MISC(general_label), 7, 7);
+    gtk_label_set_selectable(GTK_LABEL(general_label), TRUE);
+
+    struct table* general_table;
+
+    general_table =
+        table_new_with_columns(3, _("Layer"), G_TYPE_UINT, _("Type"), G_TYPE_STRING, _("Description"), G_TYPE_STRING);
+    table_set_column_align(general_table, 0, 1.0);
+
+    for (i = 0; i <= mainProject->last_loaded; i++) {
+        gerbv_fileinfo_t** files = mainProject->file;
+
+        if (!files[i] || !files[i]->isVisible || files[i]->image->layertype != GERBV_LAYERTYPE_DRILL)
+            continue;
+
+        table_add_row(general_table, i + 1, _("Excellon file"), files[i]->fullPathname);
+
+        str = g_strdup_printf(
+            _("%g x %g %s"), screen_units(fabs(files[i]->image->info->max_x - files[i]->image->info->min_x)),
+            screen_units(fabs(files[i]->image->info->max_y - files[i]->image->info->min_y)), screen_units_str()
+        );
+        table_add_row(general_table, i + 1, _("Bounding size"), str);
+        g_free(str);
+
+        /* Check error report on layer */
+        if (stat->layer_count > 0 && stat->error_list->error_text != NULL) {
+            for (gerbv_error_list_t* err_list = stat->error_list; err_list != NULL; err_list = err_list->next) {
+
+                if (i != err_list->layer - 1)
+                    continue;
+
+                table_add_row(general_table, err_list->layer, error_type_string(err_list->type), err_list->error_text);
+            }
+        }
+    }
+
+    /* G codes on active layers */
+    GtkWidget* G_report_window = gtk_scrolled_window_new(NULL, NULL);
+    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(G_report_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
+
+    struct table* G_table = table_new_with_columns(
+        3, _("Code"), G_TYPE_STRING, pgettext("table", "Count"), G_TYPE_UINT, _("Note"), G_TYPE_STRING
+    );
+    table_set_column_align(G_table, 0, 1.0);
+    table_set_column_align(G_table, 1, 1.0);
+    gtk_tree_view_set_headers_clickable(GTK_TREE_VIEW(G_table->widget), TRUE);
+
+    table_add_row(G_table, "G00", stat->G00, _(drill_g_code_name(0)));
+    table_add_row(G_table, "G01", stat->G01, _(drill_g_code_name(1)));
+    table_add_row(G_table, "G02", stat->G02, _(drill_g_code_name(2)));
+    table_add_row(G_table, "G03", stat->G03, _(drill_g_code_name(3)));
+    table_add_row(G_table, "G04", stat->G04, _(drill_g_code_name(4)));
+    table_add_row(G_table, "G05", stat->G05, _(drill_g_code_name(5)));
+    table_add_row(G_table, "G85", stat->G85, _(drill_g_code_name(85)));
+    table_add_row(G_table, "G90", stat->G90, _(drill_g_code_name(90)));
+    table_add_row(G_table, "G91", stat->G91, _(drill_g_code_name(91)));
+    table_add_row(G_table, "G93", stat->G93, _(drill_g_code_name(93)));
+    table_add_row(G_table, "", stat->G_unknown, _("unknown G-codes"));
+
+    table_set_sortable(G_table);
+    gtk_container_add(GTK_CONTAINER(G_report_window), G_table->widget);
+
+    /* M codes on active layers */
+    GtkWidget* M_report_window = gtk_scrolled_window_new(NULL, NULL);
+    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(M_report_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
+
+    struct table* M_table = table_new_with_columns(
+        3, _("Code"), G_TYPE_STRING, pgettext("table", "Count"), G_TYPE_UINT, _("Note"), G_TYPE_STRING
+    );
+    table_set_column_align(M_table, 0, 1.0);
+    table_set_column_align(M_table, 1, 1.0);
+    gtk_tree_view_set_headers_clickable(GTK_TREE_VIEW(M_table->widget), TRUE);
+    table_add_row(M_table, "M00", stat->M00, _(drill_m_code_name(0)));
+    table_add_row(M_table, "M01", stat->M01, _(drill_m_code_name(1)));
+    table_add_row(M_table, "M18", stat->M18, _(drill_m_code_name(18)));
+    table_add_row(M_table, "M25", stat->M25, _(drill_m_code_name(25)));
+    table_add_row(M_table, "M30", stat->M30, _(drill_m_code_name(30)));
+    table_add_row(M_table, "M45", stat->M45, _(drill_m_code_name(45)));
+    table_add_row(M_table, "M47", stat->M47, _(drill_m_code_name(47)));
+    table_add_row(M_table, "M48", stat->M48, _(drill_m_code_name(48)));
+    table_add_row(M_table, "M71", stat->M71, _(drill_m_code_name(71)));
+    table_add_row(M_table, "M72", stat->M72, _(drill_m_code_name(72)));
+    table_add_row(M_table, "M95", stat->M95, _(drill_m_code_name(95)));
+    table_add_row(M_table, "M97", stat->M97, _(drill_m_code_name(97)));
+    table_add_row(M_table, "M98", stat->M98, _(drill_m_code_name(98)));
+    table_add_row(M_table, "", stat->M_unknown, _("unknown M-codes"));
+
+    table_set_sortable(M_table);
+    gtk_container_add(GTK_CONTAINER(M_report_window), M_table->widget);
+
+    /* Misc codes */
+    GtkWidget* misc_report_window = gtk_scrolled_window_new(NULL, NULL);
+    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(misc_report_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
+
+    struct table* misc_table = table_new_with_columns(
+        2,
+        /* Count is string for value hide. */
+        pgettext("table", "Count"), G_TYPE_STRING, _("Code"), G_TYPE_STRING
+    );
+    table_set_column_align(misc_table, 0, 1.0);
+    str = g_strdup_printf("%d", stat->comment);
+    table_add_row(misc_table, str, _("Comments"));
+    g_free(str);
+    str = g_strdup_printf("%d", stat->unknown);
+    table_add_row(misc_table, str, _("Unknown codes"));
+    g_free(str);
+    str = g_strdup_printf("%d", stat->R);
+    table_add_row(misc_table, str, _("Repeat hole (R)"));
+    g_free(str);
+    if (stat->detect != NULL) {
+        table_add_row(misc_table, "", stat->detect);
+    }
+
+    table_set_sortable(misc_table);
+    gtk_container_add(GTK_CONTAINER(misc_report_window), misc_table->widget);
+
+    /* Drill usage on active layers */
+    GtkWidget* drill_usage_report_window = gtk_scrolled_window_new(NULL, NULL);
+    gtk_scrolled_window_set_policy(
+        GTK_SCROLLED_WINDOW(drill_usage_report_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC
+    );
+
+    struct table* drill_usage_table = table_new_with_columns(
+        4, _("Drill no."), G_TYPE_UINT, _("Dia."), G_TYPE_DOUBLE, _("Units"), G_TYPE_STRING, pgettext("table", "Count"),
+        G_TYPE_UINT
+    );
+
+    table_set_column_align(drill_usage_table, 0, 1.0);
+    table_set_column_align(drill_usage_table, 3, 1.0);
+    gtk_tree_view_set_headers_clickable(GTK_TREE_VIEW(drill_usage_table->widget), TRUE);
+
+    gerbv_drill_list_t* drill_list;
+    for (drill_list = stat->drill_list; drill_list != NULL; drill_list = drill_list->next) {
+        if (drill_list->drill_num == -1)
+            break; /* No drill list */
+
+        table_add_row(
+            drill_usage_table, drill_list->drill_num, drill_list->drill_size, drill_list->drill_unit,
+            drill_list->drill_count
+        );
+    }
+
+    table_set_sortable(drill_usage_table);
+    gtk_container_add(GTK_CONTAINER(drill_usage_report_window), drill_usage_table->widget);
+
+    /* Create top level dialog window for report */
+    GtkWidget* analyze_active_drill;
+    analyze_active_drill = gtk_dialog_new_with_buttons(
+        _("Drill codes report on visible layers"), NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_STOCK_OK,
+        GTK_RESPONSE_ACCEPT, NULL
+    );
+    gtk_container_set_border_width(GTK_CONTAINER(analyze_active_drill), 5);
+
+    gtk_dialog_set_default_response(GTK_DIALOG(analyze_active_drill), GTK_RESPONSE_ACCEPT);
+    g_signal_connect_after(
+        G_OBJECT(analyze_active_drill), "response", G_CALLBACK(gtk_widget_destroy), GTK_WIDGET(analyze_active_drill)
+    );
+
+    /* Put general report text into scrolled window */
+    GtkWidget* general_report_window = gtk_scrolled_window_new(NULL, NULL);
+    gtk_scrolled_window_set_policy(
+        GTK_SCROLLED_WINDOW(general_report_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC
+    );
+
+    GtkWidget* vbox = gtk_vbox_new(0, 0);
+    gtk_box_pack_start(GTK_BOX(vbox), general_label, 0, 0, 0);
+    gtk_box_pack_start(GTK_BOX(vbox), general_table->widget, 0, 0, 0);
+    gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(general_report_window), vbox);
+
+    /* Create tabbed notebook widget and add report widgets. */
+    GtkWidget* notebook = gtk_notebook_new();
 
+    gtk_notebook_append_page(GTK_NOTEBOOK(notebook), GTK_WIDGET(general_report_window), gtk_label_new(_("General")));
+
+    gtk_notebook_append_page(GTK_NOTEBOOK(notebook), GTK_WIDGET(G_report_window), gtk_label_new(_("G codes")));
+
+    gtk_notebook_append_page(GTK_NOTEBOOK(notebook), GTK_WIDGET(M_report_window), gtk_label_new(_("M codes")));
+
+    gtk_notebook_append_page(GTK_NOTEBOOK(notebook), GTK_WIDGET(misc_report_window), gtk_label_new(_("Misc. codes")));
+
+    gtk_notebook_append_page(
+        GTK_NOTEBOOK(notebook), GTK_WIDGET(drill_usage_report_window), gtk_label_new(_("Drill usage"))
+    );
+
+    /* Now put notebook into dialog window and show the whole thing */
+    gtk_container_add(GTK_CONTAINER(GTK_DIALOG(analyze_active_drill)->vbox), GTK_WIDGET(notebook));
+
+    if (screen.settings) {
+        analyze_window_size_restore(analyze_active_drill);
+        g_signal_connect(
+            G_OBJECT(analyze_active_drill), "response", G_CALLBACK(analyze_window_size_store),
+            GTK_WIDGET(analyze_active_drill)
+        );
+    } else {
+        gtk_window_set_default_size(GTK_WINDOW(analyze_active_drill), 640, 320);
+    }
+
+    gtk_widget_show_all(analyze_active_drill);
+
+    gerbv_drill_stats_destroy(stat);
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_online_manual_activate              (GtkMenuItem     *menuitem,
-                                        gpointer         user_data)
-{
+callbacks_control_gerber_options_activate(GtkMenuItem* menuitem, gpointer user_data) {}
 
-}
+/* --------------------------------------------------------- */
+void
+callbacks_online_manual_activate(GtkMenuItem* menuitem, gpointer user_data) {}
 
 /* --------------------------------------------------------- */
 /**
-  * The file -> quit menu item was selected or
-  * the user requested the main window to be closed by other means.
-  * Check that all changes have been saved, and then quit.
-  *
-  */
+ * The file -> quit menu item was selected or
+ * the user requested the main window to be closed by other means.
+ * Check that all changes have been saved, and then quit.
+ *
+ */
 gboolean
-callbacks_quit_activate                       (GtkMenuItem     *menuitem,
-                                        gpointer         user_data)
-{
-  gboolean layers_dirty = FALSE;
-  gint idx;
-
-  for (idx = 0; idx<=mainProject->last_loaded; idx++) {
-    if (mainProject->file[idx] == NULL) break;
-    layers_dirty = layers_dirty || mainProject->file[idx]->layer_dirty;
-  }
-
-  if (layers_dirty &&
-      !interface_get_alert_dialog_response(
-		_("Do you want to close all open layers and quit the program?"),
-		_("Quitting the program will cause any unsaved changes "
-		"to be lost."),
-		FALSE, NULL, GTK_STOCK_QUIT, GTK_STOCK_CANCEL)) {
-    return TRUE; // stop propagation of the delete_event.
-	// this would destroy the gui but not return from the gtk event loop.
-  }
-
-  /* Save background color */
-  if (screen.settings && !screen.background_is_from_project) {
-    guint clr;
-    GdkColor *bg = &mainProject->background;
-
-    clr = bg->red/257<<16 | bg->green/257<<8 | bg->blue/257;
-    g_settings_set_uint (screen.settings, "background-color", clr);
-  }
-
-  /* Save main window size and postion */
-  if (screen.settings) {
-    GtkWindow *win = GTK_WINDOW(screen.win.topLevelWindow);
-    gint32 xy[2];
-    GVariant *var;
-    gboolean is_max;
-
-    is_max = FALSE != (GDK_WINDOW_STATE_MAXIMIZED & gdk_window_get_state (
-			    gtk_widget_get_window (GTK_WIDGET(win))));
-    g_settings_set_boolean (screen.settings, "window-maximized", is_max);
-
-    if (!is_max) {
-      gtk_window_get_size (win, (gint *)xy, (gint *)(xy+1));
-      var = g_variant_new_fixed_array (G_VARIANT_TYPE_INT32, xy, 2,
-		      sizeof (xy[0]));
-      g_settings_set_value (screen.settings, "window-size", var);
-
-      gtk_window_get_position (win, (gint *)xy, (gint *)(xy+1));
-      var = g_variant_new_fixed_array (G_VARIANT_TYPE_INT32, xy, 2,
-		      sizeof (xy[0]));
-      g_settings_set_value (screen.settings, "window-position", var);
+callbacks_quit_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    gboolean layers_dirty = FALSE;
+    gint     idx;
+
+    for (idx = 0; idx <= mainProject->last_loaded; idx++) {
+        if (mainProject->file[idx] == NULL)
+            break;
+        layers_dirty = layers_dirty || mainProject->file[idx]->layer_dirty;
+    }
+
+    if (layers_dirty
+        && !interface_get_alert_dialog_response(
+            _("Do you want to close all open layers and quit the program?"),
+            _("Quitting the program will cause any unsaved changes "
+              "to be lost."),
+            FALSE, NULL, GTK_STOCK_QUIT, GTK_STOCK_CANCEL
+        )) {
+        return TRUE;  // stop propagation of the delete_event.
+                      // this would destroy the gui but not return from the gtk event loop.
+    }
+
+    /* Save background color */
+    if (screen.settings && !screen.background_is_from_project) {
+        guint     clr;
+        GdkColor* bg = &mainProject->background;
+
+        clr = bg->red / 257 << 16 | bg->green / 257 << 8 | bg->blue / 257;
+        g_settings_set_uint(screen.settings, "background-color", clr);
     }
-  }
 
-  gerbv_unload_all_layers (mainProject);
-  gtk_main_quit();
+    /* Save main window size and postion */
+    if (screen.settings) {
+        GtkWindow* win = GTK_WINDOW(screen.win.topLevelWindow);
+        gint32     xy[2];
+        GVariant*  var;
+        gboolean   is_max;
+
+        is_max = FALSE != (GDK_WINDOW_STATE_MAXIMIZED & gdk_window_get_state(gtk_widget_get_window(GTK_WIDGET(win))));
+        g_settings_set_boolean(screen.settings, "window-maximized", is_max);
+
+        if (!is_max) {
+            gtk_window_get_size(win, (gint*)xy, (gint*)(xy + 1));
+            var = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32, xy, 2, sizeof(xy[0]));
+            g_settings_set_value(screen.settings, "window-size", var);
+
+            gtk_window_get_position(win, (gint*)xy, (gint*)(xy + 1));
+            var = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32, xy, 2, sizeof(xy[0]));
+            g_settings_set_value(screen.settings, "window-position", var);
+        }
+    }
+
+    gerbv_unload_all_layers(mainProject);
+    gtk_main_quit();
 
-  return FALSE;
+    return FALSE;
 }
 
 /* --------------------------------------------------------- */
 /**
-  * The help -> about menu item was selected.  
-  * Show the about dialog.
-  *
-  */
+ * The help -> about menu item was selected.
+ * Show the about dialog.
+ *
+ */
 void
-callbacks_about_activate                     (GtkMenuItem     *menuitem,
-                                        gpointer         user_data)
-{
-	GtkWidget *aboutdialog1;
-	/* TRANSLATORS: Replace this string with your names, one name per line. */
-	gchar *translators = _("translator-credits");
-
-	gchar *string = g_strdup_printf(_(
-		"Gerbv — a Gerber (RS-274/X) viewer\n"
-		"\n"
-		"Version %s\n"
-		"Compiled on %s at %s\n"
-		"\n"
-		"Gerbv was originally developed as part of the gEDA Project "
-		"but is now separately maintained.\n"
-		"\n"
-		"For more information see:\n"
-		"  gerbv homepage: https://gerbv.github.io/\n"
-		"  gerbv repository: https://github.com/gerbv/gerbv"),
-		VERSION, __DATE__, __TIME__);
-
-#if GTK_CHECK_VERSION(2,6,0)
-	gchar *license = g_strdup_printf(_(
-		"Gerbv — a Gerber (RS-274/X) viewer\n"
-		"\n"
-		"Copyright (C) 2000—2007 Stefan Petersen\n"
-		"\n"
-		"This program is free software: you can redistribute it and/or modify\n"
-		"it under the terms of the GNU General Public License as published by\n"
-		"the Free Software Foundation, either version 2 of the License, or\n"
-		"(at your option) any later version.\n"
-		"\n"
-		"This program is distributed in the hope that it will be useful,\n"
-		"but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
-		"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
-		"GNU General Public License for more details.\n\n"
-		"You should have received a copy of the GNU General Public License\n"
-		"along with this program.  If not, see <http://www.gnu.org/licenses/>."));
-
-	#include "authors.c"
-
-	int a_size, i;
-	gchar **a;
-
-	aboutdialog1 = gtk_about_dialog_new ();
-	gtk_container_set_border_width (GTK_CONTAINER (aboutdialog1), 5);
-	gtk_about_dialog_set_version (GTK_ABOUT_DIALOG (aboutdialog1), VERSION);
-	gtk_about_dialog_set_name (GTK_ABOUT_DIALOG (aboutdialog1), _("Gerbv"));
-
-	gtk_about_dialog_set_translator_credits (GTK_ABOUT_DIALOG (aboutdialog1), translators);
-	gtk_about_dialog_set_comments (GTK_ABOUT_DIALOG (aboutdialog1), string);
-	gtk_about_dialog_set_license(GTK_ABOUT_DIALOG (aboutdialog1), license);
-
-	/* The authors.c file is autogenerated at build time */
-	a_size = sizeof(authors_string_array)/sizeof(authors_string_array[0]);
-	a = g_new(gchar *, a_size);
-	for (i = 0; i < a_size; i++)
-		a[i] = _(authors_string_array[i]);
-
-	gtk_about_dialog_set_authors(GTK_ABOUT_DIALOG (aboutdialog1), (const gchar **)a);
-	gtk_about_dialog_set_website(GTK_ABOUT_DIALOG (aboutdialog1), "https://gerbv.github.io/");
-	g_free(a);
-
-	g_signal_connect (G_OBJECT(aboutdialog1),"response",
-		      G_CALLBACK (gtk_widget_destroy), GTK_WIDGET(aboutdialog1));
-
-	g_free (string);
-	g_free (license);
+callbacks_about_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    GtkWidget* aboutdialog1;
+    /* TRANSLATORS: Replace this string with your names, one name per line. */
+    gchar* translators = _("translator-credits");
+
+    gchar* string = g_strdup_printf(
+        _("Gerbv — a Gerber (RS-274/X) viewer\n"
+          "\n"
+          "Version %s\n"
+          "Compiled on %s at %s\n"
+          "\n"
+          "Gerbv was originally developed as part of the gEDA Project "
+          "but is now separately maintained.\n"
+          "\n"
+          "For more information see:\n"
+          "  gerbv homepage: https://gerbv.github.io/\n"
+          "  gerbv repository: https://github.com/gerbv/gerbv"),
+        VERSION, __DATE__, __TIME__
+    );
+
+#if GTK_CHECK_VERSION(2, 6, 0)
+    gchar* license =
+        g_strdup_printf(_("Gerbv — a Gerber (RS-274/X) viewer\n"
+                          "\n"
+                          "Copyright (C) 2000—2007 Stefan Petersen\n"
+                          "\n"
+                          "This program is free software: you can redistribute it and/or modify\n"
+                          "it under the terms of the GNU General Public License as published by\n"
+                          "the Free Software Foundation, either version 2 of the License, or\n"
+                          "(at your option) any later version.\n"
+                          "\n"
+                          "This program is distributed in the hope that it will be useful,\n"
+                          "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
+                          "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n"
+                          "GNU General Public License for more details.\n\n"
+                          "You should have received a copy of the GNU General Public License\n"
+                          "along with this program.  If not, see <http://www.gnu.org/licenses/>."));
+
+#include "authors.c"
+
+    int     a_size, i;
+    gchar** a;
+
+    aboutdialog1 = gtk_about_dialog_new();
+    gtk_container_set_border_width(GTK_CONTAINER(aboutdialog1), 5);
+    gtk_about_dialog_set_version(GTK_ABOUT_DIALOG(aboutdialog1), VERSION);
+    gtk_about_dialog_set_name(GTK_ABOUT_DIALOG(aboutdialog1), _("Gerbv"));
+
+    gtk_about_dialog_set_translator_credits(GTK_ABOUT_DIALOG(aboutdialog1), translators);
+    gtk_about_dialog_set_comments(GTK_ABOUT_DIALOG(aboutdialog1), string);
+    gtk_about_dialog_set_license(GTK_ABOUT_DIALOG(aboutdialog1), license);
+
+    /* The authors.c file is autogenerated at build time */
+    a_size = sizeof(authors_string_array) / sizeof(authors_string_array[0]);
+    a      = g_new(gchar*, a_size);
+    for (i = 0; i < a_size; i++)
+        a[i] = _(authors_string_array[i]);
+
+    gtk_about_dialog_set_authors(GTK_ABOUT_DIALOG(aboutdialog1), (const gchar**)a);
+    gtk_about_dialog_set_website(GTK_ABOUT_DIALOG(aboutdialog1), "https://gerbv.github.io/");
+    g_free(a);
+
+    g_signal_connect(G_OBJECT(aboutdialog1), "response", G_CALLBACK(gtk_widget_destroy), GTK_WIDGET(aboutdialog1));
+
+    g_free(string);
+    g_free(license);
 #else
-	aboutdialog1 = gtk_message_dialog_new (	GTK_WINDOW (screen.win.topLevelWindow),
-					       GTK_DIALOG_DESTROY_WITH_PARENT,
-					       GTK_MESSAGE_INFO,
-					       GTK_BUTTONS_CLOSE,
-					       string
-					       );
-
-	gtk_window_set_title ( GTK_WINDOW (aboutdialog1), _("About Gerbv"));
-
-	/* Destroy the dialog when the user responds to it (e.g. clicks a button) */
-	g_signal_connect_swapped (aboutdialog1, "response",
-				  G_CALLBACK (gtk_widget_destroy),
-				  aboutdialog1);
-	g_free (string);
-#endif
+    aboutdialog1 = gtk_message_dialog_new(
+        GTK_WINDOW(screen.win.topLevelWindow), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_CLOSE,
+        string
+    );
+
+    gtk_window_set_title(GTK_WINDOW(aboutdialog1), _("About Gerbv"));
 
-	gtk_widget_show_all(GTK_WIDGET(aboutdialog1));
+    /* Destroy the dialog when the user responds to it (e.g. clicks a button) */
+    g_signal_connect_swapped(aboutdialog1, "response", G_CALLBACK(gtk_widget_destroy), aboutdialog1);
+    g_free(string);
+#endif
 
+    gtk_widget_show_all(GTK_WIDGET(aboutdialog1));
 }
 
 /* --------------------------------------------------------- */
 /**
-  * The help -> bugs menu item was selected.  
-  * Show the known bugs window
-  *
-  */
+ * The help -> bugs menu item was selected.
+ * Show the known bugs window
+ *
+ */
 void
-callbacks_bugs_activate (GtkMenuItem     *menuitem,
-                             gpointer         user_data)
-{
+callbacks_bugs_activate(GtkMenuItem* menuitem, gpointer user_data) {
     int i;
-    #include "bugs.c"
+#include "bugs.c"
 
     /* Create the top level dialog widget with an OK button */
-    GtkWidget *bugs_dialog = gtk_dialog_new_with_buttons(_("Known bugs in Gerbv"),
-							 NULL,
-							 GTK_DIALOG_DESTROY_WITH_PARENT,
-							 GTK_STOCK_OK, GTK_RESPONSE_ACCEPT,
-							 NULL);
-    gtk_container_set_border_width (GTK_CONTAINER (bugs_dialog), 5);
-    gtk_dialog_set_default_response (GTK_DIALOG(bugs_dialog),
-				     GTK_RESPONSE_ACCEPT);
-    g_signal_connect (G_OBJECT(bugs_dialog), "response",
-		      G_CALLBACK (gtk_widget_destroy), GTK_WIDGET(bugs_dialog));
-    
+    GtkWidget* bugs_dialog = gtk_dialog_new_with_buttons(
+        _("Known bugs in Gerbv"), NULL, GTK_DIALOG_DESTROY_WITH_PARENT, GTK_STOCK_OK, GTK_RESPONSE_ACCEPT, NULL
+    );
+    gtk_container_set_border_width(GTK_CONTAINER(bugs_dialog), 5);
+    gtk_dialog_set_default_response(GTK_DIALOG(bugs_dialog), GTK_RESPONSE_ACCEPT);
+    g_signal_connect(G_OBJECT(bugs_dialog), "response", G_CALLBACK(gtk_widget_destroy), GTK_WIDGET(bugs_dialog));
+
     /* First create single bugs_string from bugs_string_array */
-    GString *bugs_string = g_string_new(NULL);
-    for (i=0; bugs_string_array[i] != NULL; i++) {
-	/* gettext("") will return info string */
-	g_string_append_printf(bugs_string, "%s\n",
-		(bugs_string_array[i][0] == '\0') ? "" : _(bugs_string_array[i]));
+    GString* bugs_string = g_string_new(NULL);
+    for (i = 0; bugs_string_array[i] != NULL; i++) {
+        /* gettext("") will return info string */
+        g_string_append_printf(bugs_string, "%s\n", (bugs_string_array[i][0] == '\0') ? "" : _(bugs_string_array[i]));
     }
-    
+
     /* Create GtkLabel to hold text */
-    GtkWidget *bugs_label = gtk_label_new (bugs_string->str);
+    GtkWidget* bugs_label = gtk_label_new(bugs_string->str);
     g_string_free(bugs_string, FALSE);
     gtk_misc_set_alignment(GTK_MISC(bugs_label), 0, 0);
     gtk_misc_set_padding(GTK_MISC(bugs_label), 7, 7);
-    
+
     /* Put text into scrolled window */
-    GtkWidget *bugs_window = gtk_scrolled_window_new (NULL, NULL);
-    gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(bugs_window),
-                                          GTK_WIDGET(bugs_label));
+    GtkWidget* bugs_window = gtk_scrolled_window_new(NULL, NULL);
+    gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(bugs_window), GTK_WIDGET(bugs_label));
     gtk_widget_set_size_request(bugs_window, 600, 300);
-    gtk_container_add(GTK_CONTAINER(GTK_DIALOG(bugs_dialog)->vbox),
-                      GTK_WIDGET(bugs_window));
+    gtk_container_add(GTK_CONTAINER(GTK_DIALOG(bugs_dialog)->vbox), GTK_WIDGET(bugs_window));
 
     gtk_widget_show_all(GTK_WIDGET(bugs_dialog));
     gtk_dialog_run(GTK_DIALOG(bugs_dialog));
-    
 }
 
 /* --------------------------------------------------------- */
-gdouble callbacks_calculate_actual_distance (gdouble inputDimension) {
-	return screen_units(inputDimension);
+gdouble
+callbacks_calculate_actual_distance(gdouble inputDimension) {
+    return screen_units(inputDimension);
 }
 
 /* --------------------------------------------------------- */
-void callbacks_update_ruler_pointers (void) {
-	double xPosition, yPosition;
-	xPosition = screenRenderInfo.lowerLeftX + (screen.last_x / screenRenderInfo.scaleFactorX);
-	yPosition = screenRenderInfo.lowerLeftY + ((screenRenderInfo.displayHeight - screen.last_y) / screenRenderInfo.scaleFactorY);
-
-	if (!((screen.unit == GERBV_MILS) && ((screenRenderInfo.scaleFactorX < 80)||(screenRenderInfo.scaleFactorY < 80)))) {
-		xPosition = callbacks_calculate_actual_distance (xPosition);
-		yPosition = callbacks_calculate_actual_distance (yPosition);
-	}
-	g_object_set (G_OBJECT (screen.win.hRuler), "position", xPosition, NULL);
-	g_object_set (G_OBJECT (screen.win.vRuler), "position", yPosition, NULL);
+void
+callbacks_update_ruler_pointers(void) {
+    double xPosition, yPosition;
+    xPosition = screenRenderInfo.lowerLeftX + (screen.last_x / screenRenderInfo.scaleFactorX);
+    yPosition = screenRenderInfo.lowerLeftY
+              + ((screenRenderInfo.displayHeight - screen.last_y) / screenRenderInfo.scaleFactorY);
+
+    if (!((screen.unit == GERBV_MILS) && ((screenRenderInfo.scaleFactorX < 80) || (screenRenderInfo.scaleFactorY < 80))
+        )) {
+        xPosition = callbacks_calculate_actual_distance(xPosition);
+        yPosition = callbacks_calculate_actual_distance(yPosition);
+    }
+    g_object_set(G_OBJECT(screen.win.hRuler), "position", xPosition, NULL);
+    g_object_set(G_OBJECT(screen.win.vRuler), "position", yPosition, NULL);
 }
 
 /* --------------------------------------------------------- */
 static void
-callbacks_render_type_changed () {
-	static gboolean isChanging = FALSE;
-	if (isChanging)
-		return;
-
-	isChanging = TRUE;
-	gerbv_render_types_t type = screenRenderInfo.renderType;
-	GtkCheckMenuItem *check_item = screen.win.menu_view_render_group[type];
-	dprintf ("%s():  type = %d, check_item = %p\n", __FUNCTION__, type, check_item);
-	gtk_check_menu_item_set_active (check_item, TRUE);
-	gtk_combo_box_set_active (screen.win.sidepaneRenderComboBox, type);
-
-	render_refresh_rendered_image_on_screen();
-	isChanging = FALSE;
+callbacks_render_type_changed() {
+    static gboolean isChanging = FALSE;
+    if (isChanging)
+        return;
+
+    isChanging                      = TRUE;
+    gerbv_render_types_t type       = screenRenderInfo.renderType;
+    GtkCheckMenuItem*    check_item = screen.win.menu_view_render_group[type];
+    dprintf("%s():  type = %d, check_item = %p\n", __FUNCTION__, type, check_item);
+    gtk_check_menu_item_set_active(check_item, TRUE);
+    gtk_combo_box_set_active(screen.win.sidepaneRenderComboBox, type);
+
+    render_refresh_rendered_image_on_screen();
+    isChanging = FALSE;
 }
 
 /* --------------------------------------------------------- */
 static void
-callbacks_units_changed (gerbv_gui_unit_t unit)
-{
-	static gboolean isChanging = FALSE;
-
-	if (isChanging)
-		return;
-
-	isChanging = TRUE;
-	screen.unit = unit;
-
-	if (unit == GERBV_MILS || unit == GERBV_MMS || unit == GERBV_INS) {
-		gtk_combo_box_set_active (
-				GTK_COMBO_BOX (screen.win.statusUnitComboBox),
-				unit);
-		gtk_check_menu_item_set_active (
-				screen.win.menu_view_unit_group[unit], TRUE);
-	}
-
-	callbacks_update_ruler_scales ();
-	callbacks_update_statusbar_coordinates (screen.last_x, screen.last_y);
-	
-	if (screen.tool == MEASURE)
-		callbacks_update_statusbar_measured_distance (
-				screen.measure_last_x,
-				screen.measure_last_y);
-
-	isChanging = FALSE;
+callbacks_units_changed(gerbv_gui_unit_t unit) {
+    static gboolean isChanging = FALSE;
+
+    if (isChanging)
+        return;
+
+    isChanging  = TRUE;
+    screen.unit = unit;
+
+    if (unit == GERBV_MILS || unit == GERBV_MMS || unit == GERBV_INS) {
+        gtk_combo_box_set_active(GTK_COMBO_BOX(screen.win.statusUnitComboBox), unit);
+        gtk_check_menu_item_set_active(screen.win.menu_view_unit_group[unit], TRUE);
+    }
+
+    callbacks_update_ruler_scales();
+    callbacks_update_statusbar_coordinates(screen.last_x, screen.last_y);
+
+    if (screen.tool == MEASURE)
+        callbacks_update_statusbar_measured_distance(screen.measure_last_x, screen.measure_last_y);
+
+    isChanging = FALSE;
 }
 
 /* --------------------------------------------------------- */
 static void
-callbacks_update_ruler_scales (void) {
-	double xStart, xEnd, yStart, yEnd;
-
-	xStart = screenRenderInfo.lowerLeftX;
-	yStart = screenRenderInfo.lowerLeftY;
-	xEnd = screenRenderInfo.lowerLeftX + (screenRenderInfo.displayWidth / screenRenderInfo.scaleFactorX);
-	yEnd = screenRenderInfo.lowerLeftY + (screenRenderInfo.displayHeight / screenRenderInfo.scaleFactorY);
-	/* mils can get super crowded with large boards, but inches are too
-	   large for most boards.  So, we leave mils in for now and just switch
-	   to inches if the scale factor gets too small */
-	if (!((screen.unit == GERBV_MILS) && ((screenRenderInfo.scaleFactorX < 80)||(screenRenderInfo.scaleFactorY < 80)))) {
-		xStart = callbacks_calculate_actual_distance (xStart);
-		xEnd = callbacks_calculate_actual_distance (xEnd);
-		yStart = callbacks_calculate_actual_distance (yStart);
-		yEnd = callbacks_calculate_actual_distance (yEnd);
-	}
-	/* make sure the widgets actually exist before setting (in case this gets
-	   called before everything is realized */
-	if (screen.win.hRuler)
-		gtk_ruler_set_range (GTK_RULER (screen.win.hRuler), xStart, xEnd, 0, xEnd - xStart);
-	/* reverse y min and max, since the ruler starts at the top */
-	if (screen.win.vRuler)
-		gtk_ruler_set_range (GTK_RULER (screen.win.vRuler), yEnd, yStart, 0, yEnd - yStart);
+callbacks_update_ruler_scales(void) {
+    double xStart, xEnd, yStart, yEnd;
+
+    xStart = screenRenderInfo.lowerLeftX;
+    yStart = screenRenderInfo.lowerLeftY;
+    xEnd   = screenRenderInfo.lowerLeftX + (screenRenderInfo.displayWidth / screenRenderInfo.scaleFactorX);
+    yEnd   = screenRenderInfo.lowerLeftY + (screenRenderInfo.displayHeight / screenRenderInfo.scaleFactorY);
+    /* mils can get super crowded with large boards, but inches are too
+       large for most boards.  So, we leave mils in for now and just switch
+       to inches if the scale factor gets too small */
+    if (!((screen.unit == GERBV_MILS) && ((screenRenderInfo.scaleFactorX < 80) || (screenRenderInfo.scaleFactorY < 80))
+        )) {
+        xStart = callbacks_calculate_actual_distance(xStart);
+        xEnd   = callbacks_calculate_actual_distance(xEnd);
+        yStart = callbacks_calculate_actual_distance(yStart);
+        yEnd   = callbacks_calculate_actual_distance(yEnd);
+    }
+    /* make sure the widgets actually exist before setting (in case this gets
+       called before everything is realized */
+    if (screen.win.hRuler)
+        gtk_ruler_set_range(GTK_RULER(screen.win.hRuler), xStart, xEnd, 0, xEnd - xStart);
+    /* reverse y min and max, since the ruler starts at the top */
+    if (screen.win.vRuler)
+        gtk_ruler_set_range(GTK_RULER(screen.win.vRuler), yEnd, yStart, 0, yEnd - yStart);
 }
 
 /* --------------------------------------------------------- */
-void callbacks_update_scrollbar_limits (void){
-	gerbv_render_info_t tempRenderInfo = {0, 0, 0, 0,
-		GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY,
-		screenRenderInfo.displayWidth,
-		screenRenderInfo.displayHeight};
-
-	GtkAdjustment *hAdjust = (GtkAdjustment *)screen.win.hAdjustment;
-	GtkAdjustment *vAdjust = (GtkAdjustment *)screen.win.vAdjustment;
-	gerbv_render_zoom_to_fit_display (mainProject, &tempRenderInfo);
-	hAdjust->lower = tempRenderInfo.lowerLeftX;
-	hAdjust->page_increment = hAdjust->page_size;
-	hAdjust->step_increment = hAdjust->page_size / 10.0;
-	vAdjust->lower = tempRenderInfo.lowerLeftY;
-	vAdjust->page_increment = vAdjust->page_size;
-	vAdjust->step_increment = vAdjust->page_size / 10.0;
-	hAdjust->upper = tempRenderInfo.lowerLeftX + (tempRenderInfo.displayWidth / tempRenderInfo.scaleFactorX);
-	hAdjust->page_size = screenRenderInfo.displayWidth / screenRenderInfo.scaleFactorX;
-	vAdjust->upper = tempRenderInfo.lowerLeftY + (tempRenderInfo.displayHeight / tempRenderInfo.scaleFactorY);
-	vAdjust->page_size = screenRenderInfo.displayHeight / screenRenderInfo.scaleFactorY;
-	callbacks_update_scrollbar_positions ();
+void
+callbacks_update_scrollbar_limits(void) {
+    gerbv_render_info_t tempRenderInfo = {
+        0, 0, 0, 0, GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY, screenRenderInfo.displayWidth, screenRenderInfo.displayHeight
+    };
+
+    GtkAdjustment* hAdjust = (GtkAdjustment*)screen.win.hAdjustment;
+    GtkAdjustment* vAdjust = (GtkAdjustment*)screen.win.vAdjustment;
+    gerbv_render_zoom_to_fit_display(mainProject, &tempRenderInfo);
+    hAdjust->lower          = tempRenderInfo.lowerLeftX;
+    hAdjust->page_increment = hAdjust->page_size;
+    hAdjust->step_increment = hAdjust->page_size / 10.0;
+    vAdjust->lower          = tempRenderInfo.lowerLeftY;
+    vAdjust->page_increment = vAdjust->page_size;
+    vAdjust->step_increment = vAdjust->page_size / 10.0;
+    hAdjust->upper          = tempRenderInfo.lowerLeftX + (tempRenderInfo.displayWidth / tempRenderInfo.scaleFactorX);
+    hAdjust->page_size      = screenRenderInfo.displayWidth / screenRenderInfo.scaleFactorX;
+    vAdjust->upper          = tempRenderInfo.lowerLeftY + (tempRenderInfo.displayHeight / tempRenderInfo.scaleFactorY);
+    vAdjust->page_size      = screenRenderInfo.displayHeight / screenRenderInfo.scaleFactorY;
+    callbacks_update_scrollbar_positions();
 }
 
 /* --------------------------------------------------------- */
-void callbacks_update_scrollbar_positions (void){
-	gdouble positionX,positionY;
-
-	positionX = screenRenderInfo.lowerLeftX;
-	if (positionX < ((GtkAdjustment *)screen.win.hAdjustment)->lower)
-		positionX = ((GtkAdjustment *)screen.win.hAdjustment)->lower;
-	if (positionX > (((GtkAdjustment *)screen.win.hAdjustment)->upper - ((GtkAdjustment *)screen.win.hAdjustment)->page_size))
-		positionX = (((GtkAdjustment *)screen.win.hAdjustment)->upper - ((GtkAdjustment *)screen.win.hAdjustment)->page_size);
-	gtk_adjustment_set_value ((GtkAdjustment *)screen.win.hAdjustment, positionX);
-	
-	positionY = ((GtkAdjustment *)screen.win.vAdjustment)->upper - screenRenderInfo.lowerLeftY -
-		((GtkAdjustment *)screen.win.vAdjustment)->page_size +
-		((GtkAdjustment *)screen.win.vAdjustment)->lower;
-	if (positionY < ((GtkAdjustment *)screen.win.vAdjustment)->lower)
-		positionY = ((GtkAdjustment *)screen.win.vAdjustment)->lower;
-	if (positionY > (((GtkAdjustment *)screen.win.vAdjustment)->upper - ((GtkAdjustment *)screen.win.vAdjustment)->page_size))
-		positionY = (((GtkAdjustment *)screen.win.vAdjustment)->upper - ((GtkAdjustment *)screen.win.vAdjustment)->page_size);
-	gtk_adjustment_set_value ((GtkAdjustment *)screen.win.vAdjustment, positionY);
+void
+callbacks_update_scrollbar_positions(void) {
+    gdouble positionX, positionY;
+
+    positionX = screenRenderInfo.lowerLeftX;
+    if (positionX < ((GtkAdjustment*)screen.win.hAdjustment)->lower)
+        positionX = ((GtkAdjustment*)screen.win.hAdjustment)->lower;
+    if (positionX
+        > (((GtkAdjustment*)screen.win.hAdjustment)->upper - ((GtkAdjustment*)screen.win.hAdjustment)->page_size))
+        positionX =
+            (((GtkAdjustment*)screen.win.hAdjustment)->upper - ((GtkAdjustment*)screen.win.hAdjustment)->page_size);
+    gtk_adjustment_set_value((GtkAdjustment*)screen.win.hAdjustment, positionX);
+
+    positionY = ((GtkAdjustment*)screen.win.vAdjustment)->upper - screenRenderInfo.lowerLeftY
+              - ((GtkAdjustment*)screen.win.vAdjustment)->page_size + ((GtkAdjustment*)screen.win.vAdjustment)->lower;
+    if (positionY < ((GtkAdjustment*)screen.win.vAdjustment)->lower)
+        positionY = ((GtkAdjustment*)screen.win.vAdjustment)->lower;
+    if (positionY
+        > (((GtkAdjustment*)screen.win.vAdjustment)->upper - ((GtkAdjustment*)screen.win.vAdjustment)->page_size))
+        positionY =
+            (((GtkAdjustment*)screen.win.vAdjustment)->upper - ((GtkAdjustment*)screen.win.vAdjustment)->page_size);
+    gtk_adjustment_set_value((GtkAdjustment*)screen.win.vAdjustment, positionY);
 }
 
 /* --------------------------------------------------------- */
 gboolean
-callbacks_scrollbar_button_released (GtkWidget *widget, GdkEventButton *event){
-	screen.off_x = 0;
-	screen.off_y = 0;
-	screen.state = NORMAL;
-	render_refresh_rendered_image_on_screen();
-	return FALSE;
+callbacks_scrollbar_button_released(GtkWidget* widget, GdkEventButton* event) {
+    screen.off_x = 0;
+    screen.off_y = 0;
+    screen.state = NORMAL;
+    render_refresh_rendered_image_on_screen();
+    return FALSE;
 }
 
 /* --------------------------------------------------------- */
 gboolean
-callbacks_scrollbar_button_pressed (GtkWidget *widget, GdkEventButton *event){
-	//screen.last_x = ((GtkAdjustment *)screen.win.hAdjustment)->value;
-	screen.state = SCROLLBAR;
-	return FALSE;
+callbacks_scrollbar_button_pressed(GtkWidget* widget, GdkEventButton* event) {
+    // screen.last_x = ((GtkAdjustment *)screen.win.hAdjustment)->value;
+    screen.state = SCROLLBAR;
+    return FALSE;
 }
 
 /* --------------------------------------------------------- */
-void callbacks_hadjustment_value_changed (GtkAdjustment *adjustment, gpointer user_data){
-	/* make sure we're actually using the scrollbar to make sure we don't reset
-	   lowerLeftX during a scrollbar redraw during something else */
-	if (screen.state == SCROLLBAR) {
-		screenRenderInfo.lowerLeftX = gtk_adjustment_get_value (adjustment);
-	}
+void
+callbacks_hadjustment_value_changed(GtkAdjustment* adjustment, gpointer user_data) {
+    /* make sure we're actually using the scrollbar to make sure we don't reset
+       lowerLeftX during a scrollbar redraw during something else */
+    if (screen.state == SCROLLBAR) {
+        screenRenderInfo.lowerLeftX = gtk_adjustment_get_value(adjustment);
+    }
 }
 
 /* --------------------------------------------------------- */
-void callbacks_vadjustment_value_changed (GtkAdjustment *adjustment, gpointer user_data){
-	/* make sure we're actually using the scrollbar to make sure we don't reset
-	   lowerLeftY during a scrollbar redraw during something else */
-	if (screen.state == SCROLLBAR) {
-		screenRenderInfo.lowerLeftY = adjustment->upper -
-			(gtk_adjustment_get_value (adjustment) + adjustment->page_size) + adjustment->lower;
-	}
+void
+callbacks_vadjustment_value_changed(GtkAdjustment* adjustment, gpointer user_data) {
+    /* make sure we're actually using the scrollbar to make sure we don't reset
+       lowerLeftY during a scrollbar redraw during something else */
+    if (screen.state == SCROLLBAR) {
+        screenRenderInfo.lowerLeftY =
+            adjustment->upper - (gtk_adjustment_get_value(adjustment) + adjustment->page_size) + adjustment->lower;
+    }
 }
 
 /* --------------------------------------------------------- */
 static void
-callbacks_layer_tree_visibility_toggled (gint index)
-{
-	mainProject->file[index]->isVisible =
-		!mainProject->file[index]->isVisible;
-
-	callbacks_update_layer_tree ();
-	if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
-		render_refresh_rendered_image_on_screen ();
-	} else {
-		render_recreate_composite_surface (screen.drawing_area);
-		callbacks_force_expose_event_for_screen ();
-	}
+callbacks_layer_tree_visibility_toggled(gint index) {
+    mainProject->file[index]->isVisible = !mainProject->file[index]->isVisible;
+
+    callbacks_update_layer_tree();
+    if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
+        render_refresh_rendered_image_on_screen();
+    } else {
+        render_recreate_composite_surface(screen.drawing_area);
+        callbacks_force_expose_event_for_screen();
+    }
 }
 
 /* --------------------------------------------------------- */
 static gint
-callbacks_get_col_num_from_tree_view_col (GtkTreeViewColumn *col)
-{
-	GList *cols;
-	gint   num;
-	
-	g_return_val_if_fail ( col != NULL, -1 );
-	g_return_val_if_fail ( col->tree_view != NULL, -1 );
-	cols = gtk_tree_view_get_columns(GTK_TREE_VIEW(col->tree_view));
-	num = g_list_index(cols, (gpointer) col);
-	g_list_free(cols);
-	return num;
+callbacks_get_col_num_from_tree_view_col(GtkTreeViewColumn* col) {
+    GList* cols;
+    gint   num;
+
+    g_return_val_if_fail(col != NULL, -1);
+    g_return_val_if_fail(col->tree_view != NULL, -1);
+    cols = gtk_tree_view_get_columns(GTK_TREE_VIEW(col->tree_view));
+    num  = g_list_index(cols, (gpointer)col);
+    g_list_free(cols);
+    return num;
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_add_layer_button_clicked (GtkButton *button, gpointer user_data)
-{
-	callbacks_open_activate (NULL, NULL);
+callbacks_add_layer_button_clicked(GtkButton* button, gpointer user_data) {
+    callbacks_open_activate(NULL, NULL);
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_unselect_all_tool_buttons (void) {
-
-}
+callbacks_unselect_all_tool_buttons(void) {}
 
 void
-callbacks_switch_to_normal_tool_cursor (gint toolNumber)
-{
-	GdkWindow *drawing_area_window = screen.drawing_area->window;
-	GdkCursor *cursor;
-
-	switch (toolNumber) {
-	case POINTER:
-		gdk_window_set_cursor(drawing_area_window, GERBV_DEF_CURSOR);
-		break;
-	case PAN:
-		cursor = gdk_cursor_new(GDK_FLEUR);
-		gdk_window_set_cursor(drawing_area_window, cursor);
-		gdk_cursor_destroy(cursor);
-		break;
-	case ZOOM:
-		cursor = gdk_cursor_new(GDK_SIZING);
-		gdk_window_set_cursor(drawing_area_window, cursor);
-		gdk_cursor_destroy(cursor);
-		break;
-	case MEASURE:
-		cursor = gdk_cursor_new(GDK_CROSSHAIR);
-		gdk_window_set_cursor(drawing_area_window, cursor);
-		gdk_cursor_destroy(cursor);
-		break;
-	default:
-		break;
-	}
+callbacks_switch_to_normal_tool_cursor(gint toolNumber) {
+    GdkWindow* drawing_area_window = screen.drawing_area->window;
+    GdkCursor* cursor;
+
+    switch (toolNumber) {
+        case POINTER: gdk_window_set_cursor(drawing_area_window, GERBV_DEF_CURSOR); break;
+        case PAN:
+            cursor = gdk_cursor_new(GDK_FLEUR);
+            gdk_window_set_cursor(drawing_area_window, cursor);
+            gdk_cursor_destroy(cursor);
+            break;
+        case ZOOM:
+            cursor = gdk_cursor_new(GDK_SIZING);
+            gdk_window_set_cursor(drawing_area_window, cursor);
+            gdk_cursor_destroy(cursor);
+            break;
+        case MEASURE:
+            cursor = gdk_cursor_new(GDK_CROSSHAIR);
+            gdk_window_set_cursor(drawing_area_window, cursor);
+            gdk_cursor_destroy(cursor);
+            break;
+        default: break;
+    }
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_switch_to_correct_cursor (void)
-{
-	GdkWindow *drawing_area_window = screen.drawing_area->window;
-	GdkCursor *cursor;
-
-	if (screen.state == IN_MOVE) {
-		cursor = gdk_cursor_new(GDK_FLEUR);
-		gdk_window_set_cursor(drawing_area_window, cursor);
-		gdk_cursor_destroy(cursor);
-		return;
-	}
-	else if (screen.state == IN_ZOOM_OUTLINE) {
-		cursor = gdk_cursor_new(GDK_SIZING);
-		gdk_window_set_cursor(drawing_area_window, cursor);
-		gdk_cursor_destroy(cursor);
-		return;
-	}
-	callbacks_switch_to_normal_tool_cursor (screen.tool);
+callbacks_switch_to_correct_cursor(void) {
+    GdkWindow* drawing_area_window = screen.drawing_area->window;
+    GdkCursor* cursor;
+
+    if (screen.state == IN_MOVE) {
+        cursor = gdk_cursor_new(GDK_FLEUR);
+        gdk_window_set_cursor(drawing_area_window, cursor);
+        gdk_cursor_destroy(cursor);
+        return;
+    } else if (screen.state == IN_ZOOM_OUTLINE) {
+        cursor = gdk_cursor_new(GDK_SIZING);
+        gdk_window_set_cursor(drawing_area_window, cursor);
+        gdk_cursor_destroy(cursor);
+        return;
+    }
+    callbacks_switch_to_normal_tool_cursor(screen.tool);
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_change_tool (GtkButton *button, gpointer   user_data) {
-	gint toolNumber = GPOINTER_TO_INT (user_data);
-	
-	/* make sure se don't get caught in endless recursion here */
-	if (screen.win.updatingTools)
-		return;
-	screen.win.updatingTools = TRUE;
-	gtk_toggle_tool_button_set_active (GTK_TOGGLE_TOOL_BUTTON (screen.win.toolButtonPointer), FALSE);
-	gtk_toggle_tool_button_set_active (GTK_TOGGLE_TOOL_BUTTON (screen.win.toolButtonPan), FALSE);
-	gtk_toggle_tool_button_set_active (GTK_TOGGLE_TOOL_BUTTON (screen.win.toolButtonZoom), FALSE);
-	gtk_toggle_tool_button_set_active (GTK_TOGGLE_TOOL_BUTTON (screen.win.toolButtonMeasure), FALSE);
-	switch (toolNumber) {
-		case POINTER:
-			gtk_toggle_tool_button_set_active (GTK_TOGGLE_TOOL_BUTTON (screen.win.toolButtonPointer), TRUE);
-			screen.tool = POINTER;
-			screen.state = NORMAL;
-			utf8_strncpy(screen.statusbar.diststr,
-				_("Click to select objects in the active layer. "
-					"Middle click and drag to pan."),
-				MAX_DISTLEN);
-			break;
-		case PAN:
-			gtk_toggle_tool_button_set_active (GTK_TOGGLE_TOOL_BUTTON (screen.win.toolButtonPan), TRUE);
-			screen.tool = PAN;
-			screen.state = NORMAL;
-			utf8_strncpy(screen.statusbar.diststr,
-				_("Click and drag to pan. Right click and drag to zoom."),
-				MAX_DISTLEN);
-			break;
-		case ZOOM:
-			gtk_toggle_tool_button_set_active (GTK_TOGGLE_TOOL_BUTTON (screen.win.toolButtonZoom), TRUE);
-			screen.tool = ZOOM;
-			screen.state = NORMAL;
-			utf8_strncpy(screen.statusbar.diststr,
-				_("Click and drag to zoom in. Shift+click to zoom out."),
-				MAX_DISTLEN);
-			break;
-
-		case MEASURE:
-			gtk_toggle_tool_button_set_active (GTK_TOGGLE_TOOL_BUTTON (screen.win.toolButtonMeasure), TRUE);
-			screen.tool = MEASURE;
-			screen.state = NORMAL;
-			utf8_strncpy(screen.statusbar.diststr,
-				_("Click and drag to measure a distance or select two apertures."),
-				MAX_DISTLEN);
-
-			/* To not show previous measure drag-line */
-			screen.measure_start_x = 0;
-			screen.measure_start_y = 0;
-			screen.measure_stop_x =  0;
-			screen.measure_stop_y =  0;
-
-			/* If two items are selected, measure they distance */
-			if (selection_length (&screen.selectionInfo) == 2) {
-				gerbv_selection_item_t item[2];
-				gerbv_net_t *net[2];
-
-				item[0] = selection_get_item_by_index(
-						&screen.selectionInfo, 0);
-				item[1] = selection_get_item_by_index(
-						&screen.selectionInfo, 1);
-				net[0] = item[0].net;
-				net[1] = item[1].net;
-
-				if ((net[0]->aperture_state ==
-						net[1]->aperture_state)
-				 && (net[0]->aperture_state ==
-						GERBV_APERTURE_STATE_FLASH)) {
-					screen.measure_start_x = net[0]->stop_x;
-					screen.measure_start_y = net[0]->stop_y;
-					gerbv_transform_coord_for_image(
-							&screen.measure_start_x,
-							&screen.measure_start_y,
-							item[0].image,
-							mainProject);
-
-					screen.measure_stop_x = net[1]->stop_x;
-					screen.measure_stop_y = net[1]->stop_y;
-					gerbv_transform_coord_for_image(
-							&screen.measure_stop_x,
-							&screen.measure_stop_y,
-							item[1].image,
-							mainProject);
-
-					render_draw_measure_distance();
-				}
-			}
-			break;
-		default:
-			break;
-	}
-
-	callbacks_switch_to_normal_tool_cursor (toolNumber);
-	callbacks_update_statusbar();
-	screen.win.updatingTools = FALSE;
-	callbacks_force_expose_event_for_screen();
+callbacks_change_tool(GtkButton* button, gpointer user_data) {
+    gint toolNumber = GPOINTER_TO_INT(user_data);
+
+    /* make sure se don't get caught in endless recursion here */
+    if (screen.win.updatingTools)
+        return;
+    screen.win.updatingTools = TRUE;
+    gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(screen.win.toolButtonPointer), FALSE);
+    gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(screen.win.toolButtonPan), FALSE);
+    gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(screen.win.toolButtonZoom), FALSE);
+    gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(screen.win.toolButtonMeasure), FALSE);
+    switch (toolNumber) {
+        case POINTER:
+            gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(screen.win.toolButtonPointer), TRUE);
+            screen.tool  = POINTER;
+            screen.state = NORMAL;
+            utf8_strncpy(
+                screen.statusbar.diststr,
+                _("Click to select objects in the active layer. "
+                  "Middle click and drag to pan."),
+                MAX_DISTLEN
+            );
+            break;
+        case PAN:
+            gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(screen.win.toolButtonPan), TRUE);
+            screen.tool  = PAN;
+            screen.state = NORMAL;
+            utf8_strncpy(
+                screen.statusbar.diststr, _("Click and drag to pan. Right click and drag to zoom."), MAX_DISTLEN
+            );
+            break;
+        case ZOOM:
+            gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(screen.win.toolButtonZoom), TRUE);
+            screen.tool  = ZOOM;
+            screen.state = NORMAL;
+            utf8_strncpy(
+                screen.statusbar.diststr, _("Click and drag to zoom in. Shift+click to zoom out."), MAX_DISTLEN
+            );
+            break;
+
+        case MEASURE:
+            gtk_toggle_tool_button_set_active(GTK_TOGGLE_TOOL_BUTTON(screen.win.toolButtonMeasure), TRUE);
+            screen.tool  = MEASURE;
+            screen.state = NORMAL;
+            utf8_strncpy(
+                screen.statusbar.diststr, _("Click and drag to measure a distance or select two apertures."),
+                MAX_DISTLEN
+            );
+
+            /* To not show previous measure drag-line */
+            screen.measure_start_x = 0;
+            screen.measure_start_y = 0;
+            screen.measure_stop_x  = 0;
+            screen.measure_stop_y  = 0;
+
+            /* If two items are selected, measure they distance */
+            if (selection_length(&screen.selectionInfo) == 2) {
+                gerbv_selection_item_t item[2];
+                gerbv_net_t*           net[2];
+
+                item[0] = selection_get_item_by_index(&screen.selectionInfo, 0);
+                item[1] = selection_get_item_by_index(&screen.selectionInfo, 1);
+                net[0]  = item[0].net;
+                net[1]  = item[1].net;
+
+                if ((net[0]->aperture_state == net[1]->aperture_state)
+                    && (net[0]->aperture_state == GERBV_APERTURE_STATE_FLASH)) {
+                    screen.measure_start_x = net[0]->stop_x;
+                    screen.measure_start_y = net[0]->stop_y;
+                    gerbv_transform_coord_for_image(
+                        &screen.measure_start_x, &screen.measure_start_y, item[0].image, mainProject
+                    );
+
+                    screen.measure_stop_x = net[1]->stop_x;
+                    screen.measure_stop_y = net[1]->stop_y;
+                    gerbv_transform_coord_for_image(
+                        &screen.measure_stop_x, &screen.measure_stop_y, item[1].image, mainProject
+                    );
+
+                    render_draw_measure_distance();
+                }
+            }
+            break;
+        default: break;
+    }
+
+    callbacks_switch_to_normal_tool_cursor(toolNumber);
+    callbacks_update_statusbar();
+    screen.win.updatingTools = FALSE;
+    callbacks_force_expose_event_for_screen();
 }
 
 /* --------------------------------------------------------- */
 static void
-callbacks_select_layer_row (gint rowIndex)
-{
-	GtkTreeSelection *selection;
-	GtkTreeIter iter;
-	GtkListStore *list_store = (GtkListStore *) gtk_tree_view_get_model
-			((GtkTreeView *) screen.win.layerTree);
-
-	selection = gtk_tree_view_get_selection((GtkTreeView *) screen.win.layerTree);
-
-	if (gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(list_store),
-				&iter, NULL, rowIndex)) {
-		gtk_tree_selection_select_iter (selection, &iter);
-	}
+callbacks_select_layer_row(gint rowIndex) {
+    GtkTreeSelection* selection;
+    GtkTreeIter       iter;
+    GtkListStore*     list_store = (GtkListStore*)gtk_tree_view_get_model((GtkTreeView*)screen.win.layerTree);
+
+    selection = gtk_tree_view_get_selection((GtkTreeView*)screen.win.layerTree);
+
+    if (gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(list_store), &iter, NULL, rowIndex)) {
+        gtk_tree_selection_select_iter(selection, &iter);
+    }
 }
 
 /* --------------------------------------------------------- */
 /**
-  * This fcn returns the index of selected layer (selected in
-  * the layer window on left).
-  *
-  */
+ * This fcn returns the index of selected layer (selected in
+ * the layer window on left).
+ *
+ */
 static gint
-callbacks_get_selected_row_index (void)
-{
-	GtkTreeSelection *selection;
-	GtkTreeIter       iter;
-	GtkListStore *list_store = (GtkListStore *) gtk_tree_view_get_model
-			((GtkTreeView *) screen.win.layerTree);
-	gint index=-1,i=0;
-
-	/* This will only work in single or browse selection mode! */
-	selection = gtk_tree_view_get_selection((GtkTreeView *) screen.win.layerTree);
-	if (gtk_tree_selection_get_selected(selection, NULL, &iter)) {
-		while (gtk_tree_model_iter_nth_child ((GtkTreeModel *)list_store,
-				&iter, NULL, i)){
-			if (gtk_tree_selection_iter_is_selected (selection, &iter)) {
-				return i;
-			}
-			i++;
-     		}
-	}
-	return index;
+callbacks_get_selected_row_index(void) {
+    GtkTreeSelection* selection;
+    GtkTreeIter       iter;
+    GtkListStore*     list_store = (GtkListStore*)gtk_tree_view_get_model((GtkTreeView*)screen.win.layerTree);
+    gint              index = -1, i = 0;
+
+    /* This will only work in single or browse selection mode! */
+    selection = gtk_tree_view_get_selection((GtkTreeView*)screen.win.layerTree);
+    if (gtk_tree_selection_get_selected(selection, NULL, &iter)) {
+        while (gtk_tree_model_iter_nth_child((GtkTreeModel*)list_store, &iter, NULL, i)) {
+            if (gtk_tree_selection_iter_is_selected(selection, &iter)) {
+                return i;
+            }
+            i++;
+        }
+    }
+    return index;
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_remove_layer_button_clicked (GtkButton *button, gpointer user_data)
-{
-	gint index = callbacks_get_selected_row_index ();
-	
-	if ((index >= 0) && (index <= mainProject->last_loaded)) {
-		render_remove_selected_objects_belonging_to_layer (
-				&screen.selectionInfo,
-				mainProject->file[index]->image);
-		update_selected_object_message (FALSE);
-
-		gerbv_unload_layer (mainProject, index);
-		callbacks_update_layer_tree ();
-
-		index = MAX(0, index - 1);
-		callbacks_select_layer_row (index);
-
-		if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
-			render_refresh_rendered_image_on_screen ();
-		} else {
-			render_recreate_composite_surface (screen.drawing_area);
-			callbacks_force_expose_event_for_screen ();
-		}
-	}
+callbacks_remove_layer_button_clicked(GtkButton* button, gpointer user_data) {
+    gint index = callbacks_get_selected_row_index();
+
+    if ((index >= 0) && (index <= mainProject->last_loaded)) {
+        render_remove_selected_objects_belonging_to_layer(&screen.selectionInfo, mainProject->file[index]->image);
+        update_selected_object_message(FALSE);
+
+        gerbv_unload_layer(mainProject, index);
+        callbacks_update_layer_tree();
+
+        index = MAX(0, index - 1);
+        callbacks_select_layer_row(index);
+
+        if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
+            render_refresh_rendered_image_on_screen();
+        } else {
+            render_recreate_composite_surface(screen.drawing_area);
+            callbacks_force_expose_event_for_screen();
+        }
+    }
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_move_layer_down_menu_activate (GtkMenuItem *menuitem, gpointer user_data) {
-	callbacks_move_layer_down_button_clicked(NULL, NULL);
-	gtk_widget_grab_focus (screen.win.layerTree);
+callbacks_move_layer_down_menu_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    callbacks_move_layer_down_button_clicked(NULL, NULL);
+    gtk_widget_grab_focus(screen.win.layerTree);
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_move_layer_down_button_clicked  (GtkButton *button, gpointer   user_data) {
-	gint index=callbacks_get_selected_row_index();
-	if (index < 0) {
-		show_no_layers_warning ();
-		return;
-	}
-
-	if (index < mainProject->last_loaded) {
-		gerbv_change_layer_order (mainProject, index, index + 1);
-		callbacks_update_layer_tree ();
-		callbacks_select_layer_row (index + 1);
-
-		if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
-			render_refresh_rendered_image_on_screen ();
-		}
-		else {
-			render_recreate_composite_surface (screen.drawing_area);
-			callbacks_force_expose_event_for_screen ();
-		}
-	}
+callbacks_move_layer_down_button_clicked(GtkButton* button, gpointer user_data) {
+    gint index = callbacks_get_selected_row_index();
+    if (index < 0) {
+        show_no_layers_warning();
+        return;
+    }
+
+    if (index < mainProject->last_loaded) {
+        gerbv_change_layer_order(mainProject, index, index + 1);
+        callbacks_update_layer_tree();
+        callbacks_select_layer_row(index + 1);
+
+        if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
+            render_refresh_rendered_image_on_screen();
+        } else {
+            render_recreate_composite_surface(screen.drawing_area);
+            callbacks_force_expose_event_for_screen();
+        }
+    }
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_move_layer_up_menu_activate (GtkMenuItem *menuitem, gpointer user_data) {
-	callbacks_move_layer_up_button_clicked (NULL, NULL);
-	gtk_widget_grab_focus (screen.win.layerTree);
+callbacks_move_layer_up_menu_activate(GtkMenuItem* menuitem, gpointer user_data) {
+    callbacks_move_layer_up_button_clicked(NULL, NULL);
+    gtk_widget_grab_focus(screen.win.layerTree);
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_move_layer_up_button_clicked  (GtkButton *button, gpointer   user_data) {
-	gint index=callbacks_get_selected_row_index();
-	if (index < 0) {
-		show_no_layers_warning ();
-		return;
-	}
-	if (index > 0) {
-		gerbv_change_layer_order (mainProject, index, index - 1);
-		callbacks_update_layer_tree ();
-		callbacks_select_layer_row (index - 1);
-		if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
-			render_refresh_rendered_image_on_screen();
-		}
-		else {
-			render_recreate_composite_surface (screen.drawing_area);
-			callbacks_force_expose_event_for_screen ();
-		}
-	}
+callbacks_move_layer_up_button_clicked(GtkButton* button, gpointer user_data) {
+    gint index = callbacks_get_selected_row_index();
+    if (index < 0) {
+        show_no_layers_warning();
+        return;
+    }
+    if (index > 0) {
+        gerbv_change_layer_order(mainProject, index, index - 1);
+        callbacks_update_layer_tree();
+        callbacks_select_layer_row(index - 1);
+        if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
+            render_refresh_rendered_image_on_screen();
+        } else {
+            render_recreate_composite_surface(screen.drawing_area);
+            callbacks_force_expose_event_for_screen();
+        }
+    }
 }
 
 /* --------------------------------------------------------- */
-void callbacks_layer_tree_row_inserted (GtkTreeModel *tree_model, GtkTreePath  *path,
-                              GtkTreeIter  *oIter, gpointer user_data) {
-	gint *indices=NULL,oldPosition,newPosition;
-      
-	if ((!screen.win.treeIsUpdating)&&(path != NULL)) {
-		indices = gtk_tree_path_get_indices (path);
-		if (indices) {
-			newPosition = indices[0];
-			oldPosition = callbacks_get_selected_row_index ();
-			/* compensate for the fact that the old row has already
-			   been removed */
-			if (oldPosition < newPosition)
-				newPosition--;
-			else
-				oldPosition--;
-			gerbv_change_layer_order (mainProject, oldPosition, newPosition);
-
-			if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
-				render_refresh_rendered_image_on_screen();
-			}
-			else {
-				render_recreate_composite_surface (screen.drawing_area);
-				callbacks_force_expose_event_for_screen ();
-			}
-			/* select the new line */
-			GtkTreeSelection *selection;
-			GtkTreeIter iter;
-			GtkListStore *list_store = (GtkListStore *) gtk_tree_view_get_model
-				((GtkTreeView *) screen.win.layerTree);
-			
-			selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(screen.win.layerTree));
-			if (gtk_tree_model_get_iter ((GtkTreeModel *)list_store, &iter, path))
-				gtk_tree_selection_select_iter (selection, &iter);
-		}
-	}
+void
+callbacks_layer_tree_row_inserted(GtkTreeModel* tree_model, GtkTreePath* path, GtkTreeIter* oIter, gpointer user_data) {
+    gint *indices = NULL, oldPosition, newPosition;
+
+    if ((!screen.win.treeIsUpdating) && (path != NULL)) {
+        indices = gtk_tree_path_get_indices(path);
+        if (indices) {
+            newPosition = indices[0];
+            oldPosition = callbacks_get_selected_row_index();
+            /* compensate for the fact that the old row has already
+               been removed */
+            if (oldPosition < newPosition)
+                newPosition--;
+            else
+                oldPosition--;
+            gerbv_change_layer_order(mainProject, oldPosition, newPosition);
+
+            if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
+                render_refresh_rendered_image_on_screen();
+            } else {
+                render_recreate_composite_surface(screen.drawing_area);
+                callbacks_force_expose_event_for_screen();
+            }
+            /* select the new line */
+            GtkTreeSelection* selection;
+            GtkTreeIter       iter;
+            GtkListStore*     list_store = (GtkListStore*)gtk_tree_view_get_model((GtkTreeView*)screen.win.layerTree);
+
+            selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(screen.win.layerTree));
+            if (gtk_tree_model_get_iter((GtkTreeModel*)list_store, &iter, path))
+                gtk_tree_selection_select_iter(selection, &iter);
+        }
+    }
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_show_color_picker_dialog (gint index){
-	screen.win.colorSelectionDialog = NULL;
-	GtkColorSelectionDialog *cs= (GtkColorSelectionDialog *) gtk_color_selection_dialog_new (_("Select a color"));
-	GtkColorSelection *colorsel = (GtkColorSelection *) cs->colorsel;
-	
-	screen.win.colorSelectionDialog = (GtkWidget *) cs;
-	screen.win.colorSelectionIndex = index;
-	if (index >= 0)
-		gtk_color_selection_set_current_color (colorsel, &mainProject->file[index]->color);
-	else
-		gtk_color_selection_set_current_color (colorsel, &mainProject->background);
-	if ((screenRenderInfo.renderType >= GERBV_RENDER_TYPE_CAIRO_NORMAL)&&(index >= 0)) {
-		gtk_color_selection_set_has_opacity_control (colorsel, TRUE);
-		gtk_color_selection_set_current_alpha (colorsel, mainProject->file[index]->alpha);
-	}
-	gtk_widget_show_all((GtkWidget *)cs);
-	if (gtk_dialog_run ((GtkDialog*)cs) == GTK_RESPONSE_OK) {
-		GtkColorSelection *colorsel = (GtkColorSelection *) cs->colorsel;
-		gint rowIndex = screen.win.colorSelectionIndex;
-		
-		if (index >= 0) {
-			gtk_color_selection_get_current_color (colorsel, &mainProject->file[rowIndex]->color);
-			gdk_colormap_alloc_color(gdk_colormap_get_system(), &mainProject->file[rowIndex]->color, FALSE, TRUE);
-		}
-		else {
-			gtk_color_selection_get_current_color (colorsel, &mainProject->background);
-			gdk_colormap_alloc_color(gdk_colormap_get_system(), &mainProject->background, FALSE, TRUE);
-		}
-		if ((screenRenderInfo.renderType >= GERBV_RENDER_TYPE_CAIRO_NORMAL)&&(index >= 0)) {
-			mainProject->file[rowIndex]->alpha = gtk_color_selection_get_current_alpha (colorsel);
-		}
-		
-		callbacks_update_layer_tree ();
-		render_refresh_rendered_image_on_screen();
-	}
-	gtk_widget_destroy ((GtkWidget *)cs);
-	screen.win.colorSelectionDialog = NULL;
+callbacks_show_color_picker_dialog(gint index) {
+    screen.win.colorSelectionDialog   = NULL;
+    GtkColorSelectionDialog* cs       = (GtkColorSelectionDialog*)gtk_color_selection_dialog_new(_("Select a color"));
+    GtkColorSelection*       colorsel = (GtkColorSelection*)cs->colorsel;
+
+    screen.win.colorSelectionDialog = (GtkWidget*)cs;
+    screen.win.colorSelectionIndex  = index;
+    if (index >= 0)
+        gtk_color_selection_set_current_color(colorsel, &mainProject->file[index]->color);
+    else
+        gtk_color_selection_set_current_color(colorsel, &mainProject->background);
+    if ((screenRenderInfo.renderType >= GERBV_RENDER_TYPE_CAIRO_NORMAL) && (index >= 0)) {
+        gtk_color_selection_set_has_opacity_control(colorsel, TRUE);
+        gtk_color_selection_set_current_alpha(colorsel, mainProject->file[index]->alpha);
+    }
+    gtk_widget_show_all((GtkWidget*)cs);
+    if (gtk_dialog_run((GtkDialog*)cs) == GTK_RESPONSE_OK) {
+        GtkColorSelection* colorsel = (GtkColorSelection*)cs->colorsel;
+        gint               rowIndex = screen.win.colorSelectionIndex;
+
+        if (index >= 0) {
+            gtk_color_selection_get_current_color(colorsel, &mainProject->file[rowIndex]->color);
+            gdk_colormap_alloc_color(gdk_colormap_get_system(), &mainProject->file[rowIndex]->color, FALSE, TRUE);
+        } else {
+            gtk_color_selection_get_current_color(colorsel, &mainProject->background);
+            gdk_colormap_alloc_color(gdk_colormap_get_system(), &mainProject->background, FALSE, TRUE);
+        }
+        if ((screenRenderInfo.renderType >= GERBV_RENDER_TYPE_CAIRO_NORMAL) && (index >= 0)) {
+            mainProject->file[rowIndex]->alpha = gtk_color_selection_get_current_alpha(colorsel);
+        }
+
+        callbacks_update_layer_tree();
+        render_refresh_rendered_image_on_screen();
+    }
+    gtk_widget_destroy((GtkWidget*)cs);
+    screen.win.colorSelectionDialog = NULL;
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_invert_layer_clicked  (GtkButton *button, gpointer   user_data) {
-	gint index=callbacks_get_selected_row_index();
-	if (index < 0) {
-		show_no_layers_warning ();
-		return;
-	}
-	mainProject->file[index]->transform.inverted = !mainProject->file[index]->transform.inverted;
-	render_refresh_rendered_image_on_screen ();
-	callbacks_update_layer_tree ();
+callbacks_invert_layer_clicked(GtkButton* button, gpointer user_data) {
+    gint index = callbacks_get_selected_row_index();
+    if (index < 0) {
+        show_no_layers_warning();
+        return;
+    }
+    mainProject->file[index]->transform.inverted = !mainProject->file[index]->transform.inverted;
+    render_refresh_rendered_image_on_screen();
+    callbacks_update_layer_tree();
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_change_layer_color_clicked  (GtkButton *button, gpointer   user_data) {
-	gint index=callbacks_get_selected_row_index();
-	if (index < 0) {
-		show_no_layers_warning ();
-		return;
-	}
-	callbacks_show_color_picker_dialog (index);
+callbacks_change_layer_color_clicked(GtkButton* button, gpointer user_data) {
+    gint index = callbacks_get_selected_row_index();
+    if (index < 0) {
+        show_no_layers_warning();
+        return;
+    }
+    callbacks_show_color_picker_dialog(index);
 }
 
 void
-callbacks_change_background_color_clicked  (GtkButton *button, gpointer   user_data) {
-	callbacks_show_color_picker_dialog (-1);
+callbacks_change_background_color_clicked(GtkButton* button, gpointer user_data) {
+    callbacks_show_color_picker_dialog(-1);
 }
 
-/* --------------------------------------------------------------------------- */					
+/* --------------------------------------------------------------------------- */
 void
-callbacks_reload_layer_clicked (GtkButton *button, gpointer user_data)
-{
-	gint index = callbacks_get_selected_row_index ();
-
-	if (index < 0) {
-		show_no_layers_warning ();
-		return;
-	}
-
-	render_remove_selected_objects_belonging_to_layer (
-			&screen.selectionInfo, mainProject->file[index]->image);
-	update_selected_object_message (FALSE);
-
-	gerbv_revert_file (mainProject, index);
-	render_refresh_rendered_image_on_screen ();
-	callbacks_update_layer_tree();
+callbacks_reload_layer_clicked(GtkButton* button, gpointer user_data) {
+    gint index = callbacks_get_selected_row_index();
+
+    if (index < 0) {
+        show_no_layers_warning();
+        return;
+    }
+
+    render_remove_selected_objects_belonging_to_layer(&screen.selectionInfo, mainProject->file[index]->image);
+    update_selected_object_message(FALSE);
+
+    gerbv_revert_file(mainProject, index);
+    render_refresh_rendered_image_on_screen();
+    callbacks_update_layer_tree();
 }
 
 void
-callbacks_change_layer_edit_clicked  (GtkButton *button, gpointer userData)
-{
-	gint index = callbacks_get_selected_row_index();
-	gerbv_fileinfo_t **files = mainProject->file;
-	gerbv_user_transformation_t **transforms;
-	int i, j;
-
-	if (index < 0) {
-		show_no_layers_warning ();
-		return;
-	}
-
-	/* last_loaded == 0 if only one file is loaded */
-	transforms = g_new (gerbv_user_transformation_t *,
-			mainProject->last_loaded +
-			2 /* layer + NULL */ +
-			1 /* if selected layer is visible */);
-
-	/* [0] is selected layer */
-	transforms[0] = &mainProject->file[index]->transform;
-
-	/* Get visible Gerber files transformations */
-	j = 1;	/* [0] is alerady used */
-	for (i = 0; i <= mainProject->last_loaded; i++) {
-		if (files[i] && files[i]->isVisible)
-			transforms[j++] = &files[i]->transform;
-	}
-
-	/* Terminate array with NULL */
-	transforms[j] = NULL;
-
-	interface_show_layer_edit_dialog(transforms, screen.unit);
-	g_free (transforms);
-	render_refresh_rendered_image_on_screen ();
-	callbacks_update_layer_tree ();	
+callbacks_change_layer_edit_clicked(GtkButton* button, gpointer userData) {
+    gint                          index = callbacks_get_selected_row_index();
+    gerbv_fileinfo_t**            files = mainProject->file;
+    gerbv_user_transformation_t** transforms;
+    int                           i, j;
+
+    if (index < 0) {
+        show_no_layers_warning();
+        return;
+    }
+
+    /* last_loaded == 0 if only one file is loaded */
+    transforms = g_new(
+        gerbv_user_transformation_t*,
+        mainProject->last_loaded + 2 /* layer + NULL */ + 1 /* if selected layer is visible */
+    );
+
+    /* [0] is selected layer */
+    transforms[0] = &mainProject->file[index]->transform;
+
+    /* Get visible Gerber files transformations */
+    j = 1; /* [0] is alerady used */
+    for (i = 0; i <= mainProject->last_loaded; i++) {
+        if (files[i] && files[i]->isVisible)
+            transforms[j++] = &files[i]->transform;
+    }
+
+    /* Terminate array with NULL */
+    transforms[j] = NULL;
+
+    interface_show_layer_edit_dialog(transforms, screen.unit);
+    g_free(transforms);
+    render_refresh_rendered_image_on_screen();
+    callbacks_update_layer_tree();
 }
 
 /* --------------------------------------------------------------------------- */
 void
-callbacks_change_layer_format_clicked  (GtkButton *button, gpointer   user_data)
-{
-    gerbv_HID_Attribute *attr = NULL;
-    int n = 0;
-    int i;
-    gerbv_HID_Attr_Val * results = NULL;
-    gint index = callbacks_get_selected_row_index();
-    gchar *type;
-    gint rc;
-	if (index < 0) {
-		show_no_layers_warning ();
-		return;
-	}
-    dprintf ("%s(): index = %d\n", __FUNCTION__, index);
+callbacks_change_layer_format_clicked(GtkButton* button, gpointer user_data) {
+    gerbv_HID_Attribute* attr = NULL;
+    int                  n    = 0;
+    int                  i;
+    gerbv_HID_Attr_Val*  results = NULL;
+    gint                 index   = callbacks_get_selected_row_index();
+    gchar*               type;
+    gint                 rc;
+    if (index < 0) {
+        show_no_layers_warning();
+        return;
+    }
+    dprintf("%s(): index = %d\n", __FUNCTION__, index);
     attr = mainProject->file[index]->image->info->attr_list;
-    n =  mainProject->file[index]->image->info->n_attr;
-    type =  mainProject->file[index]->image->info->type;
-    if (type == NULL) 
-	type = N_("Unknown type");
-
-    if (attr == NULL || n == 0) 
-	{
-	  interface_show_alert_dialog(_("This file type does not currently have any editable features"), 
-				      _("Format editing is currently only supported for Excellon drill file formats."),
-				      FALSE,
-				      NULL);
-	  return;
-	}
-
-    dprintf ("%s(): n = %d, attr = %p\n", __FUNCTION__, n, attr);
-    if (n > 0)
-	{
-	    if (mainProject->file[index]->layer_dirty) {
-		rc = interface_get_alert_dialog_response (
-			_("This layer has changed!"),
-			_("Editing the file type will reload the layer, "
-			"destroying your changes.  Click OK to edit "
-			"the file type and destroy your changes, "
-			"or Cancel to leave."),
-			TRUE, NULL, GTK_STOCK_OK, GTK_STOCK_CANCEL);
-		if (rc == 0) return;  /* Return if user hit Cancel */
-	    }
-
-	    results = (gerbv_HID_Attr_Val *) malloc (n * sizeof (gerbv_HID_Attr_Val));
-	    if (results == NULL)
-		GERB_FATAL_ERROR("%s(): malloc failed", __FUNCTION__);
-      
-	    /* non-zero means cancel was picked */
-	    if (attribute_interface_dialog (attr, n, results, 
-					    _("Edit file format"), 
-					    _(type)))
-		{
-		    return;
-		}
-          
+    n    = mainProject->file[index]->image->info->n_attr;
+    type = mainProject->file[index]->image->info->type;
+    if (type == NULL)
+        type = N_("Unknown type");
+
+    if (attr == NULL || n == 0) {
+        interface_show_alert_dialog(
+            _("This file type does not currently have any editable features"),
+            _("Format editing is currently only supported for Excellon drill file formats."), FALSE, NULL
+        );
+        return;
     }
 
-    dprintf ("%s(): reloading layer\n", __func__);
-    gerbv_revert_file (mainProject, index);
+    dprintf("%s(): n = %d, attr = %p\n", __FUNCTION__, n, attr);
+    if (n > 0) {
+        if (mainProject->file[index]->layer_dirty) {
+            rc = interface_get_alert_dialog_response(
+                _("This layer has changed!"),
+                _("Editing the file type will reload the layer, "
+                  "destroying your changes.  Click OK to edit "
+                  "the file type and destroy your changes, "
+                  "or Cancel to leave."),
+                TRUE, NULL, GTK_STOCK_OK, GTK_STOCK_CANCEL
+            );
+            if (rc == 0)
+                return; /* Return if user hit Cancel */
+        }
+
+        results = (gerbv_HID_Attr_Val*)malloc(n * sizeof(gerbv_HID_Attr_Val));
+        if (results == NULL)
+            GERB_FATAL_ERROR("%s(): malloc failed", __FUNCTION__);
+
+        /* non-zero means cancel was picked */
+        if (attribute_interface_dialog(attr, n, results, _("Edit file format"), _(type))) {
+            return;
+        }
+    }
+
+    dprintf("%s(): reloading layer\n", __func__);
+    gerbv_revert_file(mainProject, index);
+
+    for (i = 0; i < n; i++) {
+        if (results[i].str_value)
+            free(results[i].str_value);
+    }
 
-    for (i = 0; i < n; i++)
-	{
-	    if (results[i].str_value)
-		free (results[i].str_value);
-	}
-    
     if (results)
-	free (results);
+        free(results);
     render_refresh_rendered_image_on_screen();
     callbacks_update_layer_tree();
 }
 
 /* --------------------------------------------------------------------------- */
 gboolean
-callbacks_file_drop_event(GtkWidget *widget, GdkDragContext *dc,
-		gint x, gint y, GtkSelectionData *data,
-		guint info, guint time, gpointer p)
-{
-	gchar **uris, **uri;
-	GSList *fns = NULL;
-
-	uris = gtk_selection_data_get_uris(data);
-	if (!uris)
-		return FALSE;
-
-	for (uri = uris; *uri; uri++) {
-		const char *prefix_str =
+callbacks_file_drop_event(
+    GtkWidget* widget, GdkDragContext* dc, gint x, gint y, GtkSelectionData* data, guint info, guint time, gpointer p
+) {
+    gchar **uris, **uri;
+    GSList* fns = NULL;
+
+    uris = gtk_selection_data_get_uris(data);
+    if (!uris)
+        return FALSE;
+
+    for (uri = uris; *uri; uri++) {
+        const char* prefix_str =
 #ifdef WIN32
-			"file:///";
+            "file:///";
 #else
-			"file://";
+            "file://";
 #endif
-		if (g_strrstr(*uri, prefix_str) == *uri)
-			fns = g_slist_append(fns, g_uri_unescape_string(
-					*uri + strlen(prefix_str), NULL));
-	}
+        if (g_strrstr(*uri, prefix_str) == *uri)
+            fns = g_slist_append(fns, g_uri_unescape_string(*uri + strlen(prefix_str), NULL));
+    }
 
-	open_files(fns);
-	g_slist_free_full(fns, g_free);
-	g_strfreev(uris);
+    open_files(fns);
+    g_slist_free_full(fns, g_free);
+    g_strfreev(uris);
 
-	return TRUE;
+    return TRUE;
 }
 
 /* --------------------------------------------------------------------------- */
 gboolean
-callbacks_layer_tree_key_press (GtkWidget *widget, GdkEventKey *event, gpointer user_data) {
-	/* if space is pressed while a color picker icon is in focus,
-	show the color picker dialog. */
-
-	if(event->keyval == GDK_space){
-		GtkTreeView *tree;
-		GtkTreePath *path;
-		GtkTreeViewColumn *col;
-		gint *indices;
-		gint idx;
-
-		tree = (GtkTreeView *) screen.win.layerTree;
-		gtk_tree_view_get_cursor (tree, &path, &col);
-		if (path) {
-			indices = gtk_tree_path_get_indices (path);
-			if (indices) {
-				idx = callbacks_get_col_num_from_tree_view_col (col);
-				if ((idx == 1) && (indices[0] <= mainProject->last_loaded)){
-					callbacks_show_color_picker_dialog (indices[0]);
-				}
-			}
-			gtk_tree_path_free (path);
-		}
-	}
-	/* by default propagate the key press */
-	return FALSE;
+callbacks_layer_tree_key_press(GtkWidget* widget, GdkEventKey* event, gpointer user_data) {
+    /* if space is pressed while a color picker icon is in focus,
+    show the color picker dialog. */
+
+    if (event->keyval == GDK_space) {
+        GtkTreeView*       tree;
+        GtkTreePath*       path;
+        GtkTreeViewColumn* col;
+        gint*              indices;
+        gint               idx;
+
+        tree = (GtkTreeView*)screen.win.layerTree;
+        gtk_tree_view_get_cursor(tree, &path, &col);
+        if (path) {
+            indices = gtk_tree_path_get_indices(path);
+            if (indices) {
+                idx = callbacks_get_col_num_from_tree_view_col(col);
+                if ((idx == 1) && (indices[0] <= mainProject->last_loaded)) {
+                    callbacks_show_color_picker_dialog(indices[0]);
+                }
+            }
+            gtk_tree_path_free(path);
+        }
+    }
+    /* by default propagate the key press */
+    return FALSE;
 }
 
 /* --------------------------------------------------------------------------- */
 gboolean
-callbacks_layer_tree_button_press (GtkWidget *widget, GdkEventButton *event,
-					gpointer user_data)
-{
-	GtkTreePath *path;
-	GtkTreeIter iter;
-	GtkTreeViewColumn *col;
-	gint x,y;
-	gint *indices;
-
-	GtkListStore *list_store = (GtkListStore *) gtk_tree_view_get_model (
-			(GtkTreeView *) screen.win.layerTree);
-
-	if (event->button == 1) {
-		if (gtk_tree_view_get_path_at_pos ((GtkTreeView *) widget,
-				event->x, event->y, &path, &col, &x, &y)
-		&& gtk_tree_model_get_iter ((GtkTreeModel *)list_store,
-				&iter, path)) {
-			indices = gtk_tree_path_get_indices (path);
-			if (indices && (indices[0] <= mainProject->last_loaded)) {
-				switch (callbacks_get_col_num_from_tree_view_col (col)) {
-				case 0:
-					callbacks_select_layer_row (indices[0]);
-					callbacks_layer_tree_visibility_toggled (indices[0]);
-					return TRUE;
-				case 1:
-					callbacks_show_color_picker_dialog (indices[0]);
-					/* don't propagate the signal, since drag and drop can
-					   sometimes activated during color selection */
-					return TRUE;
-				}
-			}
-		}
-	}
-	/* don't pop up the menu if we don't have any loaded files */
-	else if ((event->button == 3)&&(mainProject->last_loaded >= 0)) {
-		gtk_menu_popup (GTK_MENU (screen.win.layerTreePopupMenu),
-				NULL, NULL, NULL, NULL, 
-				event->button, event->time);
-	}
-
-	/* always allow the click to propagate and make sure the line is activated */
-	return FALSE;
+callbacks_layer_tree_button_press(GtkWidget* widget, GdkEventButton* event, gpointer user_data) {
+    GtkTreePath*       path;
+    GtkTreeIter        iter;
+    GtkTreeViewColumn* col;
+    gint               x, y;
+    gint*              indices;
+
+    GtkListStore* list_store = (GtkListStore*)gtk_tree_view_get_model((GtkTreeView*)screen.win.layerTree);
+
+    if (event->button == 1) {
+        if (gtk_tree_view_get_path_at_pos((GtkTreeView*)widget, event->x, event->y, &path, &col, &x, &y)
+            && gtk_tree_model_get_iter((GtkTreeModel*)list_store, &iter, path)) {
+            indices = gtk_tree_path_get_indices(path);
+            if (indices && (indices[0] <= mainProject->last_loaded)) {
+                switch (callbacks_get_col_num_from_tree_view_col(col)) {
+                    case 0:
+                        callbacks_select_layer_row(indices[0]);
+                        callbacks_layer_tree_visibility_toggled(indices[0]);
+                        return TRUE;
+                    case 1:
+                        callbacks_show_color_picker_dialog(indices[0]);
+                        /* don't propagate the signal, since drag and drop can
+                           sometimes activated during color selection */
+                        return TRUE;
+                }
+            }
+        }
+    }
+    /* don't pop up the menu if we don't have any loaded files */
+    else if ((event->button == 3) && (mainProject->last_loaded >= 0)) {
+        gtk_menu_popup(GTK_MENU(screen.win.layerTreePopupMenu), NULL, NULL, NULL, NULL, event->button, event->time);
+    }
+
+    /* always allow the click to propagate and make sure the line is activated */
+    return FALSE;
 }
 
 /* --------------------------------------------------------------------------- */
 void
-callbacks_update_layer_tree (void)
-{
-	GtkListStore *list_store = (GtkListStore *) gtk_tree_view_get_model
-			((GtkTreeView *) screen.win.layerTree);
-	gint idx;
-	GtkTreeIter iter;
-	GtkTreeSelection *selection;
-	gint oldSelectedRow;
-
-	if (screen.win.treeIsUpdating)
-		return;
-
-	screen.win.treeIsUpdating = TRUE;
-
-	oldSelectedRow = callbacks_get_selected_row_index();
-	if (oldSelectedRow < 0)
-		oldSelectedRow = 0;
-
-	gtk_list_store_clear (list_store);
-
-	for (idx = 0; idx <= mainProject->last_loaded; idx++) {
-		GdkPixbuf *pixbuf, *blackPixbuf;
-		unsigned char red, green, blue, alpha;
-		guint32 color;
-		gchar *layerName;
-		gerbv_fileinfo_t *file;
-		
-		file = mainProject->file[idx];
-		if (!file)
-			continue;
-
-		red =   (unsigned char) (file->color.red * 255 / G_MAXUINT16);
-		green = (unsigned char) (file->color.green * 255 / G_MAXUINT16);
-		blue =  (unsigned char) (file->color.blue *255 / G_MAXUINT16);
-		alpha = (unsigned char) (file->alpha * 255 / G_MAXUINT16);
-
-		color = red*(256*256*256) + green*(256*256) + blue*256 + alpha;
-		pixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8, 20, 15);
-		gdk_pixbuf_fill (pixbuf, color);
-
-		blackPixbuf = gdk_pixbuf_new (GDK_COLORSPACE_RGB, TRUE, 8, 20, 15);
-		color = 100*(256*256*256) + 100*(256*256) + 100*256 + 150;
-		gdk_pixbuf_fill (blackPixbuf, color);
-
-		/* copy the color area into the black pixbuf */
-		gdk_pixbuf_copy_area  (pixbuf, 1, 1, 18, 13, blackPixbuf, 1, 1);
-		g_object_unref(pixbuf);
-
-		gtk_list_store_append (list_store, &iter);
-
-		gchar startChar[2],*modifiedCode;
-		/* terminate the letter string */
-		startChar[1] = 0;
-
-		gint numberOfModifications = 0;
-		if (file->transform.inverted) {
-			startChar[0] = 'I';
-			numberOfModifications++;
-		}
-		if (file->transform.mirrorAroundX
-		||  file->transform.mirrorAroundY) {
-			startChar[0] = 'M';
-			numberOfModifications++;
-		}
-		if (fabs(file->transform.translateX)
-					> GERBV_PRECISION_LINEAR_INCH
-		||  fabs(file->transform.translateY)
-					> GERBV_PRECISION_LINEAR_INCH) {
-			startChar[0] = 'T';
-			numberOfModifications++;
-		}
-		if (fabs(file->transform.scaleX - 1)
-					> GERBV_PRECISION_LINEAR_INCH
-		||  fabs(file->transform.scaleY - 1)
-					> GERBV_PRECISION_LINEAR_INCH) {
-			startChar[0] = 'S';
-			numberOfModifications++;
-		}
-		if (fabs(file->transform.rotation)
-					> GERBV_PRECISION_ANGLE_RAD) {
-			startChar[0] = 'R';
-			numberOfModifications++;
-		}
-		if (numberOfModifications > 1)
-			startChar[0] = '*';
-		if (numberOfModifications == 0)
-			modifiedCode = g_strdup ("");
-		else
-			modifiedCode = g_strdup (startChar);
-
-		/* Display any unsaved layers differently to show the user they
-		 * are unsaved */
-		if (file->layer_dirty == TRUE) {
-			/* The layer has unsaved changes in it. Show layer name
-			 * in italics. */
-			layerName = g_strconcat ("*", "<i>", file->name,
-					"</i>", NULL);
-		} else {
-			/* Layer is clean. Show layer name using normal font. */
-			layerName = g_strdup (file->name);
-		}
-
-		gtk_list_store_set (list_store, &iter,
-				    0, file->isVisible,
-				    1, blackPixbuf,
-				    2, layerName,
-				    3, modifiedCode,
-				    -1);
-		g_free (layerName);
-		g_free (modifiedCode);
-		/* pixbuf has a refcount of 2 now, as the list store has added its own reference */
-		g_object_unref(blackPixbuf);
-	}
-
-	selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(screen.win.layerTree));
-
-	/* if no line is selected yet, select the first row (if it has data) */
-	/* or, select the line that was previously selected */
-
-	if (!gtk_tree_selection_get_selected (selection, NULL, &iter)) {
-		if (gtk_tree_model_iter_nth_child ((GtkTreeModel *) list_store,
-						&iter, NULL, oldSelectedRow)) {
-			gtk_tree_selection_select_iter (selection, &iter);
-		}
-	}
-	gboolean showItems = (mainProject->last_loaded >= 0);
-	gtk_widget_set_sensitive (screen.win.curLayerMenuItem, showItems);
-	gtk_widget_set_sensitive (screen.win.curAnalyzeMenuItem, showItems);
-	gtk_widget_set_sensitive (screen.win.curEditMenuItem, showItems);
-	for (unsigned int i = 0;
-			i < G_N_ELEMENTS(screen.win.curFileMenuItem); i++) {
-		gtk_widget_set_sensitive (screen.win.curFileMenuItem[i], showItems);
-	}
-	screen.win.treeIsUpdating = FALSE;
+callbacks_update_layer_tree(void) {
+    GtkListStore*     list_store = (GtkListStore*)gtk_tree_view_get_model((GtkTreeView*)screen.win.layerTree);
+    gint              idx;
+    GtkTreeIter       iter;
+    GtkTreeSelection* selection;
+    gint              oldSelectedRow;
+
+    if (screen.win.treeIsUpdating)
+        return;
+
+    screen.win.treeIsUpdating = TRUE;
+
+    oldSelectedRow = callbacks_get_selected_row_index();
+    if (oldSelectedRow < 0)
+        oldSelectedRow = 0;
+
+    gtk_list_store_clear(list_store);
+
+    for (idx = 0; idx <= mainProject->last_loaded; idx++) {
+        GdkPixbuf *       pixbuf, *blackPixbuf;
+        unsigned char     red, green, blue, alpha;
+        guint32           color;
+        gchar*            layerName;
+        gerbv_fileinfo_t* file;
+
+        file = mainProject->file[idx];
+        if (!file)
+            continue;
+
+        red   = (unsigned char)(file->color.red * 255 / G_MAXUINT16);
+        green = (unsigned char)(file->color.green * 255 / G_MAXUINT16);
+        blue  = (unsigned char)(file->color.blue * 255 / G_MAXUINT16);
+        alpha = (unsigned char)(file->alpha * 255 / G_MAXUINT16);
+
+        color  = red * (256 * 256 * 256) + green * (256 * 256) + blue * 256 + alpha;
+        pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, 20, 15);
+        gdk_pixbuf_fill(pixbuf, color);
+
+        blackPixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, 20, 15);
+        color       = 100 * (256 * 256 * 256) + 100 * (256 * 256) + 100 * 256 + 150;
+        gdk_pixbuf_fill(blackPixbuf, color);
+
+        /* copy the color area into the black pixbuf */
+        gdk_pixbuf_copy_area(pixbuf, 1, 1, 18, 13, blackPixbuf, 1, 1);
+        g_object_unref(pixbuf);
+
+        gtk_list_store_append(list_store, &iter);
+
+        gchar startChar[2], *modifiedCode;
+        /* terminate the letter string */
+        startChar[1] = 0;
+
+        gint numberOfModifications = 0;
+        if (file->transform.inverted) {
+            startChar[0] = 'I';
+            numberOfModifications++;
+        }
+        if (file->transform.mirrorAroundX || file->transform.mirrorAroundY) {
+            startChar[0] = 'M';
+            numberOfModifications++;
+        }
+        if (fabs(file->transform.translateX) > GERBV_PRECISION_LINEAR_INCH
+            || fabs(file->transform.translateY) > GERBV_PRECISION_LINEAR_INCH) {
+            startChar[0] = 'T';
+            numberOfModifications++;
+        }
+        if (fabs(file->transform.scaleX - 1) > GERBV_PRECISION_LINEAR_INCH
+            || fabs(file->transform.scaleY - 1) > GERBV_PRECISION_LINEAR_INCH) {
+            startChar[0] = 'S';
+            numberOfModifications++;
+        }
+        if (fabs(file->transform.rotation) > GERBV_PRECISION_ANGLE_RAD) {
+            startChar[0] = 'R';
+            numberOfModifications++;
+        }
+        if (numberOfModifications > 1)
+            startChar[0] = '*';
+        if (numberOfModifications == 0)
+            modifiedCode = g_strdup("");
+        else
+            modifiedCode = g_strdup(startChar);
+
+        /* Display any unsaved layers differently to show the user they
+         * are unsaved */
+        if (file->layer_dirty == TRUE) {
+            /* The layer has unsaved changes in it. Show layer name
+             * in italics. */
+            layerName = g_strconcat("*", "<i>", file->name, "</i>", NULL);
+        } else {
+            /* Layer is clean. Show layer name using normal font. */
+            layerName = g_strdup(file->name);
+        }
+
+        gtk_list_store_set(list_store, &iter, 0, file->isVisible, 1, blackPixbuf, 2, layerName, 3, modifiedCode, -1);
+        g_free(layerName);
+        g_free(modifiedCode);
+        /* pixbuf has a refcount of 2 now, as the list store has added its own reference */
+        g_object_unref(blackPixbuf);
+    }
+
+    selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(screen.win.layerTree));
+
+    /* if no line is selected yet, select the first row (if it has data) */
+    /* or, select the line that was previously selected */
+
+    if (!gtk_tree_selection_get_selected(selection, NULL, &iter)) {
+        if (gtk_tree_model_iter_nth_child((GtkTreeModel*)list_store, &iter, NULL, oldSelectedRow)) {
+            gtk_tree_selection_select_iter(selection, &iter);
+        }
+    }
+    gboolean showItems = (mainProject->last_loaded >= 0);
+    gtk_widget_set_sensitive(screen.win.curLayerMenuItem, showItems);
+    gtk_widget_set_sensitive(screen.win.curAnalyzeMenuItem, showItems);
+    gtk_widget_set_sensitive(screen.win.curEditMenuItem, showItems);
+    for (unsigned int i = 0; i < G_N_ELEMENTS(screen.win.curFileMenuItem); i++) {
+        gtk_widget_set_sensitive(screen.win.curFileMenuItem[i], showItems);
+    }
+    screen.win.treeIsUpdating = FALSE;
 }
 
 /* --------------------------------------------------------------------------- */
 void
-callbacks_display_object_properties_clicked (GtkButton *button, gpointer user_data)
-{
-	gint index = callbacks_get_selected_row_index ();
-	guint i;
-
-	if (index < 0 || selection_length (&screen.selectionInfo) == 0) {
-		interface_show_alert_dialog(_("No object is currently selected"),
-			_("Objects must be selected using the pointer tool "
-			"before you can view the object properties."),
-			FALSE, NULL);
-		return;
-	}
-	
-	for (i = 0; i < selection_length (&screen.selectionInfo); i++){
-		gerbv_selection_item_t sItem =
-			selection_get_item_by_index (&screen.selectionInfo, i);
-
-		gerbv_net_t *net = sItem.net;
-		gerbv_image_t *image = sItem.image;
-
-		if (net->interpolation == GERBV_INTERPOLATION_PAREA_START) {
-			/* Spacing for a pretty display */
-			if (i != 0)
-				g_message (" ");
-
-			g_message (_("Object type: Polygon"));
-			parea_report (net, image, mainProject);
-			net_layer_file_report (net, image, mainProject);
-		} else {
-			switch (net->aperture_state) {
-
-			case GERBV_APERTURE_STATE_ON:
-			case GERBV_APERTURE_STATE_FLASH:
-				/* Spacing for a pretty display */
-				if (i != 0)
-					g_message (" ");
-				break;
-
-			default:
-				break;
-			}
-
-			aperture_state_report (net, image, mainProject);
-		}
-	}
-	/* Use separator for different report requests */
-	g_message ("---------------------------------------");
+callbacks_display_object_properties_clicked(GtkButton* button, gpointer user_data) {
+    gint  index = callbacks_get_selected_row_index();
+    guint i;
+
+    if (index < 0 || selection_length(&screen.selectionInfo) == 0) {
+        interface_show_alert_dialog(
+            _("No object is currently selected"),
+            _("Objects must be selected using the pointer tool "
+              "before you can view the object properties."),
+            FALSE, NULL
+        );
+        return;
+    }
+
+    for (i = 0; i < selection_length(&screen.selectionInfo); i++) {
+        gerbv_selection_item_t sItem = selection_get_item_by_index(&screen.selectionInfo, i);
+
+        gerbv_net_t*   net   = sItem.net;
+        gerbv_image_t* image = sItem.image;
+
+        if (net->interpolation == GERBV_INTERPOLATION_PAREA_START) {
+            /* Spacing for a pretty display */
+            if (i != 0)
+                g_message(" ");
+
+            g_message(_("Object type: Polygon"));
+            parea_report(net, image, mainProject);
+            net_layer_file_report(net, image, mainProject);
+        } else {
+            switch (net->aperture_state) {
+
+                case GERBV_APERTURE_STATE_ON:
+                case GERBV_APERTURE_STATE_FLASH:
+                    /* Spacing for a pretty display */
+                    if (i != 0)
+                        g_message(" ");
+                    break;
+
+                default: break;
+            }
+
+            aperture_state_report(net, image, mainProject);
+        }
+    }
+    /* Use separator for different report requests */
+    g_message("---------------------------------------");
 }
 
 void
-callbacks_support_benchmark (gerbv_render_info_t *renderInfo) {
-	int i;
-	time_t start, now;
-	GdkPixmap *renderedPixmap = gdk_pixmap_new (NULL, renderInfo->displayWidth,
-								renderInfo->displayHeight, 24);
-								
-	// start by running the GDK (fast) rendering test
-	i = 0;
-	start = time(NULL);
-	now = start;
-	while( now - 30 < start) {
-		i++;
-		dprintf("Benchmark():  Starting redraw #%d\n", i);
-		gerbv_render_to_pixmap_using_gdk (mainProject, renderedPixmap, renderInfo, NULL, NULL);
-		now = time(NULL);
-		dprintf("Elapsed time = %ld seconds\n", (long int) (now - start));
-	}
-	g_message(_("FAST (=GDK) mode benchmark: %d redraws "
-				"in %ld seconds (%g redraws/second)"),
-		      i, (long int) (now - start), (double) i / (double)(now - start));
-	gdk_pixmap_unref(renderedPixmap);
-	
-	// run the cairo (normal) render mode
-	i = 0;
-	start = time(NULL);
-	now = start;
-	renderInfo->renderType = GERBV_RENDER_TYPE_CAIRO_NORMAL;
-	while( now - 30 < start) {
-		i++;
-		dprintf("Benchmark():  Starting redraw #%d\n", i);
-		cairo_surface_t *cSurface = cairo_image_surface_create  (CAIRO_FORMAT_ARGB32,
-	                              renderInfo->displayWidth, renderInfo->displayHeight);
-		cairo_t *cairoTarget = cairo_create (cSurface);
-		gerbv_render_all_layers_to_cairo_target (mainProject, cairoTarget, renderInfo);
-		cairo_destroy (cairoTarget);
-		cairo_surface_destroy (cSurface);
-		now = time(NULL);
-		dprintf("Elapsed time = %ld seconds\n", (long int) (now - start));
-	}
-	g_message(_("NORMAL (=Cairo) mode benchmark: %d redraws "
-				"in %ld seconds (%g redraws/second)"),
-		      i, (long int) (now - start), (double) i / (double)(now - start));
+callbacks_support_benchmark(gerbv_render_info_t* renderInfo) {
+    int        i;
+    time_t     start, now;
+    GdkPixmap* renderedPixmap = gdk_pixmap_new(NULL, renderInfo->displayWidth, renderInfo->displayHeight, 24);
+
+    // start by running the GDK (fast) rendering test
+    i     = 0;
+    start = time(NULL);
+    now   = start;
+    while (now - 30 < start) {
+        i++;
+        dprintf("Benchmark():  Starting redraw #%d\n", i);
+        gerbv_render_to_pixmap_using_gdk(mainProject, renderedPixmap, renderInfo, NULL, NULL);
+        now = time(NULL);
+        dprintf("Elapsed time = %ld seconds\n", (long int)(now - start));
+    }
+    g_message(
+        _("FAST (=GDK) mode benchmark: %d redraws "
+          "in %ld seconds (%g redraws/second)"),
+        i, (long int)(now - start), (double)i / (double)(now - start)
+    );
+    gdk_pixmap_unref(renderedPixmap);
+
+    // run the cairo (normal) render mode
+    i                      = 0;
+    start                  = time(NULL);
+    now                    = start;
+    renderInfo->renderType = GERBV_RENDER_TYPE_CAIRO_NORMAL;
+    while (now - 30 < start) {
+        i++;
+        dprintf("Benchmark():  Starting redraw #%d\n", i);
+        cairo_surface_t* cSurface =
+            cairo_image_surface_create(CAIRO_FORMAT_ARGB32, renderInfo->displayWidth, renderInfo->displayHeight);
+        cairo_t* cairoTarget = cairo_create(cSurface);
+        gerbv_render_all_layers_to_cairo_target(mainProject, cairoTarget, renderInfo);
+        cairo_destroy(cairoTarget);
+        cairo_surface_destroy(cSurface);
+        now = time(NULL);
+        dprintf("Elapsed time = %ld seconds\n", (long int)(now - start));
+    }
+    g_message(
+        _("NORMAL (=Cairo) mode benchmark: %d redraws "
+          "in %ld seconds (%g redraws/second)"),
+        i, (long int)(now - start), (double)i / (double)(now - start)
+    );
 }
 
 /* --------------------------------------------------------------------------- */
 void
-callbacks_benchmark_clicked (GtkButton *button, gpointer   user_data)
-{
-	// prepare render size and options (canvas size width and height are last 2 variables)
-	gerbv_render_info_t renderInfo = {1.0, 1.0, 0, 0,
-					GERBV_RENDER_TYPE_GDK, 640, 480};
-
-	if (!interface_get_alert_dialog_response(_("Performance benchmark"),
-			_("Application will be unresponsive for 1 minute! "
-			"Run performance benchmark?"),
-			FALSE, NULL, GTK_STOCK_OK, GTK_STOCK_CANCEL))
-		return;
-
-	GERB_COMPILE_WARNING(_("Running full zoom benchmark..."));
-	while (g_main_context_iteration(NULL, FALSE)) {} // update log widget
-
-	// autoscale the image for now...maybe we don't want to do this in order to
-	//   allow benchmarking of different zoom levels?
-	gerbv_render_zoom_to_fit_display (mainProject, &renderInfo);
-	callbacks_support_benchmark (&renderInfo);
-
-	GERB_COMPILE_WARNING(_("Running x5 zoom benchmark..."));
-	while (g_main_context_iteration(NULL, FALSE)) {} // update log widget
-
-	renderInfo.lowerLeftX += (screenRenderInfo.displayWidth /
-				screenRenderInfo.scaleFactorX) / 3.0;
-	renderInfo.lowerLeftY += (screenRenderInfo.displayHeight /
-				screenRenderInfo.scaleFactorY) / 3.0;
-	renderInfo.scaleFactorX *= 5;
-	renderInfo.scaleFactorY *= 5;
-	callbacks_support_benchmark (&renderInfo);
+callbacks_benchmark_clicked(GtkButton* button, gpointer user_data) {
+    // prepare render size and options (canvas size width and height are last 2 variables)
+    gerbv_render_info_t renderInfo = { 1.0, 1.0, 0, 0, GERBV_RENDER_TYPE_GDK, 640, 480 };
+
+    if (!interface_get_alert_dialog_response(
+            _("Performance benchmark"),
+            _("Application will be unresponsive for 1 minute! "
+              "Run performance benchmark?"),
+            FALSE, NULL, GTK_STOCK_OK, GTK_STOCK_CANCEL
+        ))
+        return;
+
+    GERB_COMPILE_WARNING(_("Running full zoom benchmark..."));
+    while (g_main_context_iteration(NULL, FALSE)) {}  // update log widget
+
+    // autoscale the image for now...maybe we don't want to do this in order to
+    //   allow benchmarking of different zoom levels?
+    gerbv_render_zoom_to_fit_display(mainProject, &renderInfo);
+    callbacks_support_benchmark(&renderInfo);
+
+    GERB_COMPILE_WARNING(_("Running x5 zoom benchmark..."));
+    while (g_main_context_iteration(NULL, FALSE)) {}  // update log widget
+
+    renderInfo.lowerLeftX += (screenRenderInfo.displayWidth / screenRenderInfo.scaleFactorX) / 3.0;
+    renderInfo.lowerLeftY += (screenRenderInfo.displayHeight / screenRenderInfo.scaleFactorY) / 3.0;
+    renderInfo.scaleFactorX *= 5;
+    renderInfo.scaleFactorY *= 5;
+    callbacks_support_benchmark(&renderInfo);
 }
 
 /* --------------------------------------------------------------------------- */
 void
-callbacks_edit_object_properties_clicked (GtkButton *button, gpointer   user_data){
-}
+callbacks_edit_object_properties_clicked(GtkButton* button, gpointer user_data) {}
+
 /* --------------------------------------------------------------------------- */
-void 
-callbacks_live_edit (GtkWidget *button, gpointer user_data){
-	GtkDialog *toplevel = GTK_DIALOG(gtk_widget_get_toplevel (button));
-	gtk_dialog_response(toplevel, GTK_RESPONSE_APPLY);
+void
+callbacks_live_edit(GtkWidget* button, gpointer user_data) {
+    GtkDialog* toplevel = GTK_DIALOG(gtk_widget_get_toplevel(button));
+    gtk_dialog_response(toplevel, GTK_RESPONSE_APPLY);
 }
+
 /* --------------------------------------------------------------------------- */
 void
-callbacks_move_objects_clicked (GtkButton *button, gpointer   user_data){
-	/* for testing, just hard code in some translations here */
-	gerbv_image_move_selected_objects (screen.selectionInfo.selectedNodeArray, -0.050, 0.050);
-	callbacks_update_layer_tree();
-	selection_clear (&screen.selectionInfo);
-	update_selected_object_message (FALSE);
-	render_refresh_rendered_image_on_screen ();
+callbacks_move_objects_clicked(GtkButton* button, gpointer user_data) {
+    /* for testing, just hard code in some translations here */
+    gerbv_image_move_selected_objects(screen.selectionInfo.selectedNodeArray, -0.050, 0.050);
+    callbacks_update_layer_tree();
+    selection_clear(&screen.selectionInfo);
+    update_selected_object_message(FALSE);
+    render_refresh_rendered_image_on_screen();
 }
 
 /* --------------------------------------------------------------------------- */
 void
-callbacks_reduce_object_area_clicked  (GtkButton *button, gpointer user_data){
-	/* for testing, just hard code in some parameters */
-	gerbv_image_reduce_area_of_selected_objects (screen.selectionInfo.selectedNodeArray, 0.20, 3, 3, 0.01);
-	selection_clear (&screen.selectionInfo);
-	update_selected_object_message (FALSE);
-	render_refresh_rendered_image_on_screen ();
+callbacks_reduce_object_area_clicked(GtkButton* button, gpointer user_data) {
+    /* for testing, just hard code in some parameters */
+    gerbv_image_reduce_area_of_selected_objects(screen.selectionInfo.selectedNodeArray, 0.20, 3, 3, 0.01);
+    selection_clear(&screen.selectionInfo);
+    update_selected_object_message(FALSE);
+    render_refresh_rendered_image_on_screen();
 }
 
 /* --------------------------------------------------------------------------- */
 void
-callbacks_delete_objects_clicked (GtkButton *button, gpointer user_data)
-{
-	if (selection_length (&screen.selectionInfo) == 0) {
-		interface_show_alert_dialog (
-			_("No object is currently selected"),
-			_("Objects must be selected using the pointer tool "
-				"before they can be deleted."),
-			FALSE,
-			NULL);
-		return;
-	}
-
-	gint index = callbacks_get_selected_row_index ();
-	if (index < 0)
-		return;
-
-	if (mainProject->check_before_delete) {
-		if (!interface_get_alert_dialog_response (
-			_("Do you want to permanently delete "
-			"the selected objects from <i>visible</i> layers?"),
-			_("Gerbv currently has no undo function, so "
-			"this action cannot be undone. This action "
-			"will not change the saved file unless you "
-			"save the file afterwards."),
-			TRUE, &(mainProject->check_before_delete),
-			GTK_STOCK_DELETE, GTK_STOCK_CANCEL)) {
-				return;
-		}
-	}
-
-	guint i;
-	for (i = 0; i < selection_length (&screen.selectionInfo);) {
-		gerbv_selection_item_t sel_item =
-			selection_get_item_by_index (&screen.selectionInfo, i);
-		gerbv_fileinfo_t *file_info =
-			gerbv_get_fileinfo_for_image(sel_item.image, mainProject);
-
-		/* Preserve currently invisible selection from deletion */
-		if (!file_info->isVisible) {
-			i++;
-			continue;
-		}
-
-		file_info->layer_dirty = TRUE;
-		selection_clear_item_by_index (&screen.selectionInfo, i);
-		gerbv_image_delete_net (sel_item.net);
-	}
-	update_selected_object_message (FALSE);
-
-	render_refresh_rendered_image_on_screen ();
-	callbacks_update_layer_tree();
+callbacks_delete_objects_clicked(GtkButton* button, gpointer user_data) {
+    if (selection_length(&screen.selectionInfo) == 0) {
+        interface_show_alert_dialog(
+            _("No object is currently selected"),
+            _("Objects must be selected using the pointer tool "
+              "before they can be deleted."),
+            FALSE, NULL
+        );
+        return;
+    }
+
+    gint index = callbacks_get_selected_row_index();
+    if (index < 0)
+        return;
+
+    if (mainProject->check_before_delete) {
+        if (!interface_get_alert_dialog_response(
+                _("Do you want to permanently delete "
+                  "the selected objects from <i>visible</i> layers?"),
+                _("Gerbv currently has no undo function, so "
+                  "this action cannot be undone. This action "
+                  "will not change the saved file unless you "
+                  "save the file afterwards."),
+                TRUE, &(mainProject->check_before_delete), GTK_STOCK_DELETE, GTK_STOCK_CANCEL
+            )) {
+            return;
+        }
+    }
+
+    guint i;
+    for (i = 0; i < selection_length(&screen.selectionInfo);) {
+        gerbv_selection_item_t sel_item  = selection_get_item_by_index(&screen.selectionInfo, i);
+        gerbv_fileinfo_t*      file_info = gerbv_get_fileinfo_for_image(sel_item.image, mainProject);
+
+        /* Preserve currently invisible selection from deletion */
+        if (!file_info->isVisible) {
+            i++;
+            continue;
+        }
+
+        file_info->layer_dirty = TRUE;
+        selection_clear_item_by_index(&screen.selectionInfo, i);
+        gerbv_image_delete_net(sel_item.net);
+    }
+    update_selected_object_message(FALSE);
+
+    render_refresh_rendered_image_on_screen();
+    callbacks_update_layer_tree();
 }
 
 /* --------------------------------------------------------------------------- */
 gboolean
-callbacks_drawingarea_configure_event (GtkWidget *widget, GdkEventConfigure *event)
-{
-	GdkDrawable *drawable = widget->window;
-	
-	gdk_drawable_get_size (drawable, &screenRenderInfo.displayWidth, &screenRenderInfo.displayHeight);
-
-	/* set this up if cairo is compiled, since we may need to switch over to
-	   using the surface at any time */
-	int x_off=0, y_off=0;
-	
-	if (GDK_IS_WINDOW(widget->window)) {
-	      /* query the window's backbuffer if it has one */
-		GdkWindow *window = GDK_WINDOW(widget->window);
-	      gdk_window_get_internal_paint_info (window, &drawable, &x_off, &y_off);
-	}
-	if (screen.windowSurface)
-		cairo_surface_destroy ((cairo_surface_t *)
-			screen.windowSurface);
+callbacks_drawingarea_configure_event(GtkWidget* widget, GdkEventConfigure* event) {
+    GdkDrawable* drawable = widget->window;
+
+    gdk_drawable_get_size(drawable, &screenRenderInfo.displayWidth, &screenRenderInfo.displayHeight);
+
+    /* set this up if cairo is compiled, since we may need to switch over to
+       using the surface at any time */
+    int x_off = 0, y_off = 0;
+
+    if (GDK_IS_WINDOW(widget->window)) {
+        /* query the window's backbuffer if it has one */
+        GdkWindow* window = GDK_WINDOW(widget->window);
+        gdk_window_get_internal_paint_info(window, &drawable, &x_off, &y_off);
+    }
+    if (screen.windowSurface)
+        cairo_surface_destroy((cairo_surface_t*)screen.windowSurface);
 
 #if defined(WIN32) || defined(QUARTZ)
-	cairo_t *cairoTarget = gdk_cairo_create (GDK_WINDOW(widget->window));
-	
-	screen.windowSurface = cairo_get_target (cairoTarget);
-	/* increase surface reference by one so it isn't freed when the cairo_t
-	   is destroyed next */
-	screen.windowSurface = cairo_surface_reference (screen.windowSurface);
-	cairo_destroy (cairoTarget);
+    cairo_t* cairoTarget = gdk_cairo_create(GDK_WINDOW(widget->window));
+
+    screen.windowSurface = cairo_get_target(cairoTarget);
+    /* increase surface reference by one so it isn't freed when the cairo_t
+       is destroyed next */
+    screen.windowSurface = cairo_surface_reference(screen.windowSurface);
+    cairo_destroy(cairoTarget);
 #else
-	GdkVisual *visual = gdk_drawable_get_visual (drawable);
-	screen.windowSurface = (gpointer) cairo_xlib_surface_create (GDK_DRAWABLE_XDISPLAY (drawable),
-                                          GDK_DRAWABLE_XID (drawable),
-                                          GDK_VISUAL_XVISUAL (visual),
-                                          screenRenderInfo.displayWidth,
-                                          screenRenderInfo.displayHeight);
+    GdkVisual* visual    = gdk_drawable_get_visual(drawable);
+    screen.windowSurface = (gpointer)cairo_xlib_surface_create(
+        GDK_DRAWABLE_XDISPLAY(drawable), GDK_DRAWABLE_XID(drawable), GDK_VISUAL_XVISUAL(visual),
+        screenRenderInfo.displayWidth, screenRenderInfo.displayHeight
+    );
 #endif
-	/* if this is the first time, go ahead and call autoscale even if we don't
-	   have a model loaded */
-	if ((screenRenderInfo.scaleFactorX < 0.001)||(screenRenderInfo.scaleFactorY < 0.001)) {
-		gerbv_render_zoom_to_fit_display (mainProject, &screenRenderInfo);
-	}
-	render_refresh_rendered_image_on_screen();
-	return TRUE;
+    /* if this is the first time, go ahead and call autoscale even if we don't
+       have a model loaded */
+    if ((screenRenderInfo.scaleFactorX < 0.001) || (screenRenderInfo.scaleFactorY < 0.001)) {
+        gerbv_render_zoom_to_fit_display(mainProject, &screenRenderInfo);
+    }
+    render_refresh_rendered_image_on_screen();
+    return TRUE;
 }
 
 /* --------------------------------------------------------- */
 gboolean
-callbacks_drawingarea_expose_event (GtkWidget *widget, GdkEventExpose *event)
-{
-	if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
-		GdkPixmap *new_pixmap;
-		GdkGC *gc = gdk_gc_new(widget->window);
-
-		/*
-		* Create a pixmap with default background
-		*/
-		new_pixmap = gdk_pixmap_new(widget->window,
-					widget->allocation.width,
-					widget->allocation.height,
-					-1);
-
-		gdk_gc_set_foreground(gc, &mainProject->background);
-
-		gdk_draw_rectangle(new_pixmap, gc, TRUE, 
-			       event->area.x, event->area.y,
-			       event->area.width, event->area.height);
-
-		/*
-		* Copy gerber pixmap onto background if we have one to copy.
-		* Do translation at the same time.
-		*/
-		if (screen.pixmap != NULL) {
-		gdk_draw_pixmap(new_pixmap,
-				widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
-				screen.pixmap, 
-				event->area.x - screen.off_x, 
-				event->area.y - screen.off_y, 
-				event->area.x, event->area.y,
-				event->area.width, event->area.height);
-		}
-
-		/*
-		* Draw the whole thing onto screen
-		*/
-		gdk_draw_pixmap(widget->window,
-			    widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
-			    new_pixmap,
-			    event->area.x, event->area.y,
-			    event->area.x, event->area.y,
-			    event->area.width, event->area.height);
-
-		gdk_pixmap_unref(new_pixmap);
-		gdk_gc_unref(gc);
-
-		/*
-		* Draw Zooming outline if we are in that mode
-		*/
-		if (screen.state == IN_ZOOM_OUTLINE) {
-			render_draw_zoom_outline(screen.centered_outline_zoom);
-		}
-		else if (screen.state == IN_MEASURE) {
-			render_draw_measure_distance();
-		}
-		if (screen.tool == MEASURE && screen.state != IN_MEASURE) {
-			render_toggle_measure_line();
-		}
- 
-		return FALSE;
-	}
-
-	cairo_t *cr;
-	int width, height;
-	int x_off=0, y_off=0;
-	GdkDrawable *drawable = widget->window;
-
-	if (GDK_IS_WINDOW(widget->window)) {
-	      /* query the window's backbuffer if it has one */
-		GdkWindow *window = GDK_WINDOW(widget->window);
-	      gdk_window_get_internal_paint_info (window,
-	                                          &drawable, &x_off, &y_off);
-	}
-	gdk_drawable_get_size (drawable, &width, &height);
+callbacks_drawingarea_expose_event(GtkWidget* widget, GdkEventExpose* event) {
+    if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
+        GdkPixmap* new_pixmap;
+        GdkGC*     gc = gdk_gc_new(widget->window);
+
+        /*
+         * Create a pixmap with default background
+         */
+        new_pixmap = gdk_pixmap_new(widget->window, widget->allocation.width, widget->allocation.height, -1);
+
+        gdk_gc_set_foreground(gc, &mainProject->background);
+
+        gdk_draw_rectangle(new_pixmap, gc, TRUE, event->area.x, event->area.y, event->area.width, event->area.height);
+
+        /*
+         * Copy gerber pixmap onto background if we have one to copy.
+         * Do translation at the same time.
+         */
+        if (screen.pixmap != NULL) {
+            gdk_draw_pixmap(
+                new_pixmap, widget->style->fg_gc[GTK_WIDGET_STATE(widget)], screen.pixmap, event->area.x - screen.off_x,
+                event->area.y - screen.off_y, event->area.x, event->area.y, event->area.width, event->area.height
+            );
+        }
+
+        /*
+         * Draw the whole thing onto screen
+         */
+        gdk_draw_pixmap(
+            widget->window, widget->style->fg_gc[GTK_WIDGET_STATE(widget)], new_pixmap, event->area.x, event->area.y,
+            event->area.x, event->area.y, event->area.width, event->area.height
+        );
+
+        gdk_pixmap_unref(new_pixmap);
+        gdk_gc_unref(gc);
+
+        /*
+         * Draw Zooming outline if we are in that mode
+         */
+        if (screen.state == IN_ZOOM_OUTLINE) {
+            render_draw_zoom_outline(screen.centered_outline_zoom);
+        } else if (screen.state == IN_MEASURE) {
+            render_draw_measure_distance();
+        }
+        if (screen.tool == MEASURE && screen.state != IN_MEASURE) {
+            render_toggle_measure_line();
+        }
+
+        return FALSE;
+    }
+
+    cairo_t*     cr;
+    int          width, height;
+    int          x_off = 0, y_off = 0;
+    GdkDrawable* drawable = widget->window;
+
+    if (GDK_IS_WINDOW(widget->window)) {
+        /* query the window's backbuffer if it has one */
+        GdkWindow* window = GDK_WINDOW(widget->window);
+        gdk_window_get_internal_paint_info(window, &drawable, &x_off, &y_off);
+    }
+    gdk_drawable_get_size(drawable, &width, &height);
 
 #if defined(WIN32) || defined(QUARTZ)
-	/* FIXME */
-	cr = gdk_cairo_create (GDK_WINDOW(widget->window));
-#else      
-	cairo_surface_t *buffert;
-	
-	GdkVisual *visual = gdk_drawable_get_visual (drawable);
-	buffert = (gpointer) cairo_xlib_surface_create (GDK_DRAWABLE_XDISPLAY (drawable),
-	                                          GDK_DRAWABLE_XID (drawable),
-	                                          GDK_VISUAL_XVISUAL (visual),
-	                                          event->area.width, event->area.height);
-	cr = cairo_create (buffert);
+    /* FIXME */
+    cr = gdk_cairo_create(GDK_WINDOW(widget->window));
+#else
+    cairo_surface_t* buffert;
+
+    GdkVisual* visual = gdk_drawable_get_visual(drawable);
+    buffert           = (gpointer)cairo_xlib_surface_create(
+                  GDK_DRAWABLE_XDISPLAY(drawable), GDK_DRAWABLE_XID(drawable), GDK_VISUAL_XVISUAL(visual), event->area.width,
+                  event->area.height
+              );
+    cr = cairo_create(buffert);
 #endif
-	cairo_translate (cr, -event->area.x + screen.off_x, -event->area.y + screen.off_y);
-	render_project_to_cairo_target (cr);
-	cairo_destroy (cr);
+    cairo_translate(cr, -event->area.x + screen.off_x, -event->area.y + screen.off_y);
+    render_project_to_cairo_target(cr);
+    cairo_destroy(cr);
 #if !defined(WIN32) && !defined(QUARTZ)
-	cairo_surface_destroy (buffert);
+    cairo_surface_destroy(buffert);
 #endif
 
-	if (screen.tool == MEASURE)
-		render_toggle_measure_line();
-	return FALSE;
+    if (screen.tool == MEASURE)
+        render_toggle_measure_line();
+    return FALSE;
 }
 
 /* Transforms screen coordinates to board ones */
 static void
-callbacks_screen2board(gdouble *X, gdouble *Y, gint x, gint y) {
-
-	/* make sure we don't divide by zero (which is possible if the gui
-	   isn't displayed yet */
-	if ((screenRenderInfo.scaleFactorX > 0.001)||(screenRenderInfo.scaleFactorY > 0.001)) {
-		*X = screenRenderInfo.lowerLeftX + (x / screenRenderInfo.scaleFactorX);
-		*Y = screenRenderInfo.lowerLeftY + ((screenRenderInfo.displayHeight - y)
-			/ screenRenderInfo.scaleFactorY);
-	}
-	else {
-		*X = *Y = 0.0;
-	}
+callbacks_screen2board(gdouble* X, gdouble* Y, gint x, gint y) {
+
+    /* make sure we don't divide by zero (which is possible if the gui
+       isn't displayed yet */
+    if ((screenRenderInfo.scaleFactorX > 0.001) || (screenRenderInfo.scaleFactorY > 0.001)) {
+        *X = screenRenderInfo.lowerLeftX + (x / screenRenderInfo.scaleFactorX);
+        *Y = screenRenderInfo.lowerLeftY + ((screenRenderInfo.displayHeight - y) / screenRenderInfo.scaleFactorY);
+    } else {
+        *X = *Y = 0.0;
+    }
 }
 
-const char *gerbv_coords_pattern_mils_str = N_("%8.2f %8.2f");
+const char* gerbv_coords_pattern_mils_str = N_("%8.2f %8.2f");
 
 /* --------------------------------------------------------- */
 static void
-callbacks_update_statusbar_coordinates (gint x, gint y)
-{
-	gdouble X, Y;
-
-	callbacks_screen2board (&X, &Y, x, y);
-
-	switch (screen.unit) {
-	case GERBV_MILS:
-		utf8_snprintf (screen.statusbar.coordstr, MAX_COORDLEN,
-				_(gerbv_coords_pattern_mils_str),
-				COORD2MILS (X), COORD2MILS (Y));
-		break;
-	case GERBV_MMS:
-		utf8_snprintf (screen.statusbar.coordstr, MAX_COORDLEN,
-				_("%8.3f %8.3f"),
-				COORD2MMS (X), COORD2MMS (Y));
-		break;
-	default:
-		utf8_snprintf (screen.statusbar.coordstr, MAX_COORDLEN,
-				_("%4.5f %4.5f"),
-				COORD2INS (X), COORD2INS (Y));
-	}
-
-	callbacks_update_statusbar();
+callbacks_update_statusbar_coordinates(gint x, gint y) {
+    gdouble X, Y;
+
+    callbacks_screen2board(&X, &Y, x, y);
+
+    switch (screen.unit) {
+        case GERBV_MILS:
+            utf8_snprintf(
+                screen.statusbar.coordstr, MAX_COORDLEN, _(gerbv_coords_pattern_mils_str), COORD2MILS(X), COORD2MILS(Y)
+            );
+            break;
+        case GERBV_MMS:
+            utf8_snprintf(screen.statusbar.coordstr, MAX_COORDLEN, _("%8.3f %8.3f"), COORD2MMS(X), COORD2MMS(Y));
+            break;
+        default: utf8_snprintf(screen.statusbar.coordstr, MAX_COORDLEN, _("%4.5f %4.5f"), COORD2INS(X), COORD2INS(Y));
+    }
+
+    callbacks_update_statusbar();
 }
 
 static void
-update_selected_object_message (gboolean userTriedToSelect)
-{
-	if (screen.tool != POINTER)
-		return;
-
-	gint selectionLength = selection_length (&screen.selectionInfo);
-
-	if (selectionLength == 0) {
-		if (userTriedToSelect) {
-			/* Update status bar message to make sure the user
-			 * knows about needing to select the layer */
-			gchar *str = g_new(gchar, MAX_DISTLEN);
-			utf8_strncpy(str,
-					_("No object selected. Objects can "
-					"only be selected in the active "
-					"layer."),
-					MAX_DISTLEN - 7);
-			utf8_snprintf(screen.statusbar.diststr, MAX_DISTLEN,
-					"<b>%s</b>", str);
-			g_free(str);
-		} else {
-			utf8_strncpy(screen.statusbar.diststr,
-					_("Click to select objects in the "
-					"active layer. Middle click and drag "
-					"to pan."),
-					MAX_DISTLEN);
-		}
-	} else {
-		utf8_snprintf(screen.statusbar.diststr, MAX_DISTLEN,
-				ngettext("%d object are currently selected",
-					"%d objects are currently selected",
-					selectionLength), selectionLength);
-	}
-
-	callbacks_update_statusbar();
+update_selected_object_message(gboolean userTriedToSelect) {
+    if (screen.tool != POINTER)
+        return;
+
+    gint selectionLength = selection_length(&screen.selectionInfo);
+
+    if (selectionLength == 0) {
+        if (userTriedToSelect) {
+            /* Update status bar message to make sure the user
+             * knows about needing to select the layer */
+            gchar* str = g_new(gchar, MAX_DISTLEN);
+            utf8_strncpy(
+                str,
+                _("No object selected. Objects can "
+                  "only be selected in the active "
+                  "layer."),
+                MAX_DISTLEN - 7
+            );
+            utf8_snprintf(screen.statusbar.diststr, MAX_DISTLEN, "<b>%s</b>", str);
+            g_free(str);
+        } else {
+            utf8_strncpy(
+                screen.statusbar.diststr,
+                _("Click to select objects in the "
+                  "active layer. Middle click and drag "
+                  "to pan."),
+                MAX_DISTLEN
+            );
+        }
+    } else {
+        utf8_snprintf(
+            screen.statusbar.diststr, MAX_DISTLEN,
+            ngettext("%d object are currently selected", "%d objects are currently selected", selectionLength),
+            selectionLength
+        );
+    }
+
+    callbacks_update_statusbar();
 }
-			
+
 /* --------------------------------------------------------- */
 gboolean
-callbacks_drawingarea_motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
-{
-	int x, y;
-	GdkModifierType state;
-
-	if (event->is_hint)
-		gdk_window_get_pointer (event->window, &x, &y, &state);
-	else {
-		x = event->x;
-		y = event->y;
-		state = event->state;
-	}
-
-	switch (screen.state) {
-		case IN_MOVE: {
-		    if (screen.last_x != 0 || screen.last_y != 0) {
-			/* Move pixmap to get a snappier feel of movement */
-			screen.off_x += x - screen.last_x;
-			screen.off_y += y - screen.last_y;
-		    }
-    		    screenRenderInfo.lowerLeftX -= ((x - screen.last_x) / screenRenderInfo.scaleFactorX);
-		    screenRenderInfo.lowerLeftY += ((y - screen.last_y) / screenRenderInfo.scaleFactorY);
-		    callbacks_force_expose_event_for_screen ();
-		    callbacks_update_scrollbar_positions ();
-			screen.last_x = x;
-			screen.last_y = y;
-		    break;
-		}
-		case IN_ZOOM_OUTLINE: {
-			if (screen.last_x || screen.last_y)
-				render_draw_zoom_outline(screen.centered_outline_zoom);
-			screen.last_x = x;
-			screen.last_y = y;
-			render_draw_zoom_outline(screen.centered_outline_zoom);
-			break;
-		}
-		case IN_MEASURE: {
-			/* clear the previous drawn line by drawing over it */
-			render_toggle_measure_line();
-			callbacks_screen2board(&(screen.measure_stop_x),
-			    &(screen.measure_stop_y), x, y);
-			/* screen.last_[xy] are updated to move the ruler pointers */
-			screen.last_x = x;
-			screen.last_y = y;
-			/* draw the new line and write the new distance */
-			render_draw_measure_distance();
-			break;
-		}
-		case IN_SELECTION_DRAG: {
-			if (screen.last_x || screen.last_y)
-				render_draw_selection_box_outline();
-			screen.last_x = x;
-			screen.last_y = y;
-			render_draw_selection_box_outline();
-			break;
-		}
-		default:
-			screen.last_x = x;
-			screen.last_y = y;
-			break;
-	}
-	callbacks_update_statusbar_coordinates (x, y);
-	callbacks_update_ruler_pointers ();
-	return TRUE;
+callbacks_drawingarea_motion_notify_event(GtkWidget* widget, GdkEventMotion* event) {
+    int             x, y;
+    GdkModifierType state;
+
+    if (event->is_hint)
+        gdk_window_get_pointer(event->window, &x, &y, &state);
+    else {
+        x     = event->x;
+        y     = event->y;
+        state = event->state;
+    }
+
+    switch (screen.state) {
+        case IN_MOVE:
+            {
+                if (screen.last_x != 0 || screen.last_y != 0) {
+                    /* Move pixmap to get a snappier feel of movement */
+                    screen.off_x += x - screen.last_x;
+                    screen.off_y += y - screen.last_y;
+                }
+                screenRenderInfo.lowerLeftX -= ((x - screen.last_x) / screenRenderInfo.scaleFactorX);
+                screenRenderInfo.lowerLeftY += ((y - screen.last_y) / screenRenderInfo.scaleFactorY);
+                callbacks_force_expose_event_for_screen();
+                callbacks_update_scrollbar_positions();
+                screen.last_x = x;
+                screen.last_y = y;
+                break;
+            }
+        case IN_ZOOM_OUTLINE:
+            {
+                if (screen.last_x || screen.last_y)
+                    render_draw_zoom_outline(screen.centered_outline_zoom);
+                screen.last_x = x;
+                screen.last_y = y;
+                render_draw_zoom_outline(screen.centered_outline_zoom);
+                break;
+            }
+        case IN_MEASURE:
+            {
+                /* clear the previous drawn line by drawing over it */
+                render_toggle_measure_line();
+                callbacks_screen2board(&(screen.measure_stop_x), &(screen.measure_stop_y), x, y);
+                /* screen.last_[xy] are updated to move the ruler pointers */
+                screen.last_x = x;
+                screen.last_y = y;
+                /* draw the new line and write the new distance */
+                render_draw_measure_distance();
+                break;
+            }
+        case IN_SELECTION_DRAG:
+            {
+                if (screen.last_x || screen.last_y)
+                    render_draw_selection_box_outline();
+                screen.last_x = x;
+                screen.last_y = y;
+                render_draw_selection_box_outline();
+                break;
+            }
+        default:
+            screen.last_x = x;
+            screen.last_y = y;
+            break;
+    }
+    callbacks_update_statusbar_coordinates(x, y);
+    callbacks_update_ruler_pointers();
+    return TRUE;
 } /* motion_notify_event */
 
 /* --------------------------------------------------------- */
 gboolean
-callbacks_drawingarea_button_press_event (GtkWidget *widget, GdkEventButton *event)
-{
-	GdkWindow *drawing_area_window = screen.drawing_area->window;
-	GdkCursor *cursor;
-	
-	switch (event->button) {
-		case 1 :
-			if (screen.tool == POINTER) {
-				/* select */
-				/* selection will only work with cairo, so do nothing if it's
-				   not compiled */
-				screen.state = IN_SELECTION_DRAG;
-				screen.start_x = event->x;
-				screen.start_y = event->y;
-			}
-			else if (screen.tool == PAN) {
-				/* Plain panning */
-				screen.state = IN_MOVE;
-				screen.last_x = event->x;
-				screen.last_y = event->y;
-			}
-			else if (screen.tool == ZOOM) {
-				screen.state = IN_ZOOM_OUTLINE;
-				/* Zoom outline mode initiated */
-				screen.start_x = event->x;
-				screen.start_y = event->y;
-				screen.centered_outline_zoom = event->state;
-			}
-			else if (screen.tool == MEASURE) {
-				screen.state = IN_MEASURE;
-				callbacks_screen2board(&(screen.measure_start_x), &(screen.measure_start_y),
-								event->x, event->y);
-				screen.measure_stop_x = screen.measure_start_x;
-				screen.measure_stop_y = screen.measure_start_y;
-				/* force an expose event to clear any previous measure lines */
-				callbacks_force_expose_event_for_screen ();
-			}
-			break;
-		case 2 :
-			screen.state = IN_MOVE;
-			screen.last_x = event->x;
-			screen.last_y = event->y;
-			cursor = gdk_cursor_new(GDK_FLEUR);
-			gdk_window_set_cursor(drawing_area_window, cursor);
-			gdk_cursor_destroy(cursor);
-			break;
-		case 3 :
-			if (screen.tool == POINTER) {
-				/* if no items are selected, try and find the item the user
-				   is pointing at */
-				if (selection_length (&screen.selectionInfo) == 0) {
-					gint index=callbacks_get_selected_row_index();
-					if ((index >= 0) && 
-					    (index <= mainProject->last_loaded) &&
-					    (mainProject->file[index]->isVisible)) {
-					  render_fill_selection_buffer_from_mouse_click(
-							  event->x, event->y,
-							  index, SELECTION_REPLACE);
-					} else {
-					    selection_clear (&screen.selectionInfo);
-					    update_selected_object_message (FALSE);
-					    render_refresh_rendered_image_on_screen ();
-					}
-				}
-
-				/* only show the popup if we actually have something selected now */
-				if (selection_length (&screen.selectionInfo) != 0) {
-					update_selected_object_message (TRUE);
-					gtk_menu_popup(GTK_MENU(screen.win.drawWindowPopupMenu), NULL, NULL, NULL, NULL, 
-							event->button, event->time);
-				}
-
-			} else {
-				/* Zoom outline mode initiated */
-				screen.state = IN_ZOOM_OUTLINE;
-				screen.start_x = event->x;
-				screen.start_y = event->y;
-				screen.centered_outline_zoom = event->state & GDK_SHIFT_MASK;
-				cursor = gdk_cursor_new(GDK_SIZING);
-				gdk_window_set_cursor(drawing_area_window, cursor);
-				gdk_cursor_destroy(cursor);
-			}
-			break;
-		case 4 : /* Scroll wheel */
-			render_zoom_display (ZOOM_IN_CMOUSE, 0, event->x, event->y);
-			break;
-		case 5 :  /* Scroll wheel */
-			render_zoom_display (ZOOM_OUT_CMOUSE, 0, event->x, event->y);
-			break;
-		default:
-			break;
-	}
-	callbacks_switch_to_correct_cursor ();
-	return TRUE;
+callbacks_drawingarea_button_press_event(GtkWidget* widget, GdkEventButton* event) {
+    GdkWindow* drawing_area_window = screen.drawing_area->window;
+    GdkCursor* cursor;
+
+    switch (event->button) {
+        case 1:
+            if (screen.tool == POINTER) {
+                /* select */
+                /* selection will only work with cairo, so do nothing if it's
+                   not compiled */
+                screen.state   = IN_SELECTION_DRAG;
+                screen.start_x = event->x;
+                screen.start_y = event->y;
+            } else if (screen.tool == PAN) {
+                /* Plain panning */
+                screen.state  = IN_MOVE;
+                screen.last_x = event->x;
+                screen.last_y = event->y;
+            } else if (screen.tool == ZOOM) {
+                screen.state = IN_ZOOM_OUTLINE;
+                /* Zoom outline mode initiated */
+                screen.start_x               = event->x;
+                screen.start_y               = event->y;
+                screen.centered_outline_zoom = event->state;
+            } else if (screen.tool == MEASURE) {
+                screen.state = IN_MEASURE;
+                callbacks_screen2board(&(screen.measure_start_x), &(screen.measure_start_y), event->x, event->y);
+                screen.measure_stop_x = screen.measure_start_x;
+                screen.measure_stop_y = screen.measure_start_y;
+                /* force an expose event to clear any previous measure lines */
+                callbacks_force_expose_event_for_screen();
+            }
+            break;
+        case 2:
+            screen.state  = IN_MOVE;
+            screen.last_x = event->x;
+            screen.last_y = event->y;
+            cursor        = gdk_cursor_new(GDK_FLEUR);
+            gdk_window_set_cursor(drawing_area_window, cursor);
+            gdk_cursor_destroy(cursor);
+            break;
+        case 3:
+            if (screen.tool == POINTER) {
+                /* if no items are selected, try and find the item the user
+                   is pointing at */
+                if (selection_length(&screen.selectionInfo) == 0) {
+                    gint index = callbacks_get_selected_row_index();
+                    if ((index >= 0) && (index <= mainProject->last_loaded) && (mainProject->file[index]->isVisible)) {
+                        render_fill_selection_buffer_from_mouse_click(event->x, event->y, index, SELECTION_REPLACE);
+                    } else {
+                        selection_clear(&screen.selectionInfo);
+                        update_selected_object_message(FALSE);
+                        render_refresh_rendered_image_on_screen();
+                    }
+                }
+
+                /* only show the popup if we actually have something selected now */
+                if (selection_length(&screen.selectionInfo) != 0) {
+                    update_selected_object_message(TRUE);
+                    gtk_menu_popup(
+                        GTK_MENU(screen.win.drawWindowPopupMenu), NULL, NULL, NULL, NULL, event->button, event->time
+                    );
+                }
+
+            } else {
+                /* Zoom outline mode initiated */
+                screen.state                 = IN_ZOOM_OUTLINE;
+                screen.start_x               = event->x;
+                screen.start_y               = event->y;
+                screen.centered_outline_zoom = event->state & GDK_SHIFT_MASK;
+                cursor                       = gdk_cursor_new(GDK_SIZING);
+                gdk_window_set_cursor(drawing_area_window, cursor);
+                gdk_cursor_destroy(cursor);
+            }
+            break;
+        case 4: /* Scroll wheel */ render_zoom_display(ZOOM_IN_CMOUSE, 0, event->x, event->y); break;
+        case 5: /* Scroll wheel */ render_zoom_display(ZOOM_OUT_CMOUSE, 0, event->x, event->y); break;
+        default: break;
+    }
+    callbacks_switch_to_correct_cursor();
+    return TRUE;
 }
 
 static gboolean
-check_align_files_possibility (gerbv_selection_info_t *sel_info)
-{
-	gerbv_fileinfo_t **f = mainProject->file;
-	GtkMenuItem **menu_items = (GtkMenuItem **) screen.win.curEditAlingItem;
-	gerbv_selection_item_t si[2];
-	int id[2] = {-1, -1};
-	int i;
-
-	/* If has two objects, then can do files aligning */
-	if (selection_length (sel_info) == 2) {
-		si[0] = selection_get_item_by_index(sel_info, 0);
-		si[1] = selection_get_item_by_index(sel_info, 1);
-
-		for (i = 0; i <= mainProject->last_loaded; i++) {
-			if (f[i]->image == si[0].image)
-				id[0] = i;
-						
-			if (f[i]->image == si[1].image)
-				id[1] = i;
-		}
-
-		/* Can align if on different files */
-		if (id[0]*id[1] >= 0 && id[0] != id[1]) {
-			gchar *str;
-
-/* TODO: add color boxes for layers as hint */
-
-			/* Update align menu items */
-			str = g_strdup_printf (_("#_%i %s  >  #%i %s"),
-					id[0]+1, f[id[0]]->name,
-					id[1]+1, f[id[1]]->name);
-			gtk_menu_item_set_label (menu_items[0], str);
-			g_free (str);
-
-			str = g_strdup_printf (_("#_%i %s  >  #%i %s"),
-					id[1]+1, f[id[1]]->name,
-					id[0]+1, f[id[0]]->name);
-			gtk_menu_item_set_label (menu_items[1], str);
-			g_free (str);
-
-			gtk_widget_set_sensitive (
-				screen.win.curEditAlingMenuItem, TRUE);
-
-			return TRUE;
-		}
-	}
-
-	/* Can't align, disable align menu */
-	gtk_widget_set_sensitive (screen.win.curEditAlingMenuItem, FALSE);
-	gtk_menu_item_set_label (menu_items[0], "");
-	gtk_menu_item_set_label (menu_items[1], "");
-
-	return FALSE;
+check_align_files_possibility(gerbv_selection_info_t* sel_info) {
+    gerbv_fileinfo_t**     f          = mainProject->file;
+    GtkMenuItem**          menu_items = (GtkMenuItem**)screen.win.curEditAlingItem;
+    gerbv_selection_item_t si[2];
+    int                    id[2] = { -1, -1 };
+    int                    i;
+
+    /* If has two objects, then can do files aligning */
+    if (selection_length(sel_info) == 2) {
+        si[0] = selection_get_item_by_index(sel_info, 0);
+        si[1] = selection_get_item_by_index(sel_info, 1);
+
+        for (i = 0; i <= mainProject->last_loaded; i++) {
+            if (f[i]->image == si[0].image)
+                id[0] = i;
+
+            if (f[i]->image == si[1].image)
+                id[1] = i;
+        }
+
+        /* Can align if on different files */
+        if (id[0] * id[1] >= 0 && id[0] != id[1]) {
+            gchar* str;
+
+            /* TODO: add color boxes for layers as hint */
+
+            /* Update align menu items */
+            str = g_strdup_printf(_("#_%i %s  >  #%i %s"), id[0] + 1, f[id[0]]->name, id[1] + 1, f[id[1]]->name);
+            gtk_menu_item_set_label(menu_items[0], str);
+            g_free(str);
+
+            str = g_strdup_printf(_("#_%i %s  >  #%i %s"), id[1] + 1, f[id[1]]->name, id[0] + 1, f[id[0]]->name);
+            gtk_menu_item_set_label(menu_items[1], str);
+            g_free(str);
+
+            gtk_widget_set_sensitive(screen.win.curEditAlingMenuItem, TRUE);
+
+            return TRUE;
+        }
+    }
+
+    /* Can't align, disable align menu */
+    gtk_widget_set_sensitive(screen.win.curEditAlingMenuItem, FALSE);
+    gtk_menu_item_set_label(menu_items[0], "");
+    gtk_menu_item_set_label(menu_items[1], "");
+
+    return FALSE;
 }
 
 /** The edit -> align layers menu item was selected.  Align first to second or
-  * second to first layers by selected elements */
+ * second to first layers by selected elements */
 void
-callbacks_align_files_from_sel_clicked (
-		GtkMenuItem *menu_item, gpointer user_data)
-{
-	gerbv_fileinfo_t *fi[2];
-	gerbv_selection_item_t item[2];
-	gerbv_net_t *net;
-	gerbv_selection_info_t *sel_info = &screen.selectionInfo;
-	int align_second_to_first = GPOINTER_TO_INT(user_data);
-	gdouble x[2], y[2];
-	int i;
-
-	if (selection_length (sel_info) != 2)
-		return;
-
-	item[0] = selection_get_item_by_index(sel_info, 0);
-	item[1] = selection_get_item_by_index(sel_info, 1);
-
-	fi[0] = gerbv_get_fileinfo_for_image (item[0].image, mainProject);
-	fi[1] = gerbv_get_fileinfo_for_image (item[1].image, mainProject);
-
-	if (fi[0] == NULL || fi[1] == NULL || fi[0] == fi[1])
-		return;
-
-	/* Calculate aligning coords */
-	for (i = 0; i < 2; i++) {
-		net = item[i].net;
-
-		switch (net->aperture_state) {
-		case GERBV_APERTURE_STATE_FLASH:
-			x[i] = net->stop_x;
-			y[i] = net->stop_y;
-			break;
-		case GERBV_APERTURE_STATE_ON:
-			switch (net->interpolation) {
-			case GERBV_INTERPOLATION_LINEARx1:
-			case GERBV_INTERPOLATION_LINEARx10:
-			case GERBV_INTERPOLATION_LINEARx01:
-			case GERBV_INTERPOLATION_LINEARx001:
-				x[i] = (net->stop_x + net->start_x)/2;
-				y[i] = (net->stop_y + net->start_y)/2;
-				break;
-			case GERBV_INTERPOLATION_CW_CIRCULAR:
-			case GERBV_INTERPOLATION_CCW_CIRCULAR:
-				x[i] = net->cirseg->cp_x;
-				y[i] = net->cirseg->cp_y;
-				break;
-			default:
-				GERB_COMPILE_ERROR (_("Can't align by this "
-							"type of object"));
-				return;
-			}
-			break;
-		default:
-			GERB_COMPILE_ERROR (_("Can't align by this "
-						"type of object"));
-			return;
-		}
-
-		gerbv_transform_coord_for_image(x + i, y + i,
-				item[i].image, mainProject);
-	}
-
-	if (align_second_to_first) {
-		fi[1]->transform.translateX += x[0] - x[1];
-		fi[1]->transform.translateY += y[0] - y[1];
-	} else {
-		fi[0]->transform.translateX += x[1] - x[0];
-		fi[0]->transform.translateY += y[1] - y[0];
-	}
-
-	render_refresh_rendered_image_on_screen ();
-	callbacks_update_layer_tree ();
+callbacks_align_files_from_sel_clicked(GtkMenuItem* menu_item, gpointer user_data) {
+    gerbv_fileinfo_t*       fi[2];
+    gerbv_selection_item_t  item[2];
+    gerbv_net_t*            net;
+    gerbv_selection_info_t* sel_info              = &screen.selectionInfo;
+    int                     align_second_to_first = GPOINTER_TO_INT(user_data);
+    gdouble                 x[2], y[2];
+    int                     i;
+
+    if (selection_length(sel_info) != 2)
+        return;
+
+    item[0] = selection_get_item_by_index(sel_info, 0);
+    item[1] = selection_get_item_by_index(sel_info, 1);
+
+    fi[0] = gerbv_get_fileinfo_for_image(item[0].image, mainProject);
+    fi[1] = gerbv_get_fileinfo_for_image(item[1].image, mainProject);
+
+    if (fi[0] == NULL || fi[1] == NULL || fi[0] == fi[1])
+        return;
+
+    /* Calculate aligning coords */
+    for (i = 0; i < 2; i++) {
+        net = item[i].net;
+
+        switch (net->aperture_state) {
+            case GERBV_APERTURE_STATE_FLASH:
+                x[i] = net->stop_x;
+                y[i] = net->stop_y;
+                break;
+            case GERBV_APERTURE_STATE_ON:
+                switch (net->interpolation) {
+                    case GERBV_INTERPOLATION_LINEARx1:
+                    case GERBV_INTERPOLATION_LINEARx10:
+                    case GERBV_INTERPOLATION_LINEARx01:
+                    case GERBV_INTERPOLATION_LINEARx001:
+                        x[i] = (net->stop_x + net->start_x) / 2;
+                        y[i] = (net->stop_y + net->start_y) / 2;
+                        break;
+                    case GERBV_INTERPOLATION_CW_CIRCULAR:
+                    case GERBV_INTERPOLATION_CCW_CIRCULAR:
+                        x[i] = net->cirseg->cp_x;
+                        y[i] = net->cirseg->cp_y;
+                        break;
+                    default:
+                        GERB_COMPILE_ERROR(
+                            _("Can't align by this "
+                              "type of object")
+                        );
+                        return;
+                }
+                break;
+            default:
+                GERB_COMPILE_ERROR(
+                    _("Can't align by this "
+                      "type of object")
+                );
+                return;
+        }
+
+        gerbv_transform_coord_for_image(x + i, y + i, item[i].image, mainProject);
+    }
+
+    if (align_second_to_first) {
+        fi[1]->transform.translateX += x[0] - x[1];
+        fi[1]->transform.translateY += y[0] - y[1];
+    } else {
+        fi[0]->transform.translateX += x[1] - x[0];
+        fi[0]->transform.translateY += y[1] - y[0];
+    }
+
+    render_refresh_rendered_image_on_screen();
+    callbacks_update_layer_tree();
 }
 
 /* --------------------------------------------------------- */
 gboolean
-callbacks_drawingarea_button_release_event (GtkWidget *widget, GdkEventButton *event)
-{
-	gint index;
-
-	if (event->type != GDK_BUTTON_RELEASE)
-		return TRUE;
-
-	switch (screen.state) {
-	case IN_MOVE:
-		screen.off_x = 0;
-		screen.off_y = 0;
-		render_refresh_rendered_image_on_screen ();
-		callbacks_switch_to_normal_tool_cursor (screen.tool);
-		break;
-
-	case IN_ZOOM_OUTLINE:
-		if ((event->state & GDK_SHIFT_MASK) != 0) {
-			render_zoom_display (ZOOM_OUT_CMOUSE, 0,
-					event->x, event->y);
-		}
-		/* if the user just clicks without dragging, then simply
-		   zoom in a preset amount */
-		else if ((abs(screen.start_x - event->x) < 4) &&
-				(abs(screen.start_y - event->y) < 4)) {
-			render_zoom_display (ZOOM_IN_CMOUSE, 0,
-					event->x, event->y);
-		} else {
-			render_calculate_zoom_from_outline (widget, event);
-		}
-		callbacks_switch_to_normal_tool_cursor (screen.tool);
-		break;
-
-	case IN_SELECTION_DRAG:
-		/* selection will only work with cairo, so do nothing if it's
-		   not compiled */
-		index = callbacks_get_selected_row_index ();
-
-		if ((index >= 0) && mainProject->file[index]->isVisible) {
-			enum selection_action sel_action = SELECTION_REPLACE;
-			
-			if (event->state & GDK_SHIFT_MASK)
-				sel_action = SELECTION_ADD;
-			else if (event->state & GDK_CONTROL_MASK)
-				sel_action = SELECTION_TOGGLE;
-
-			/* determine if this was just a click or a box drag */
-			if ((fabs((double)(screen.last_x - screen.start_x)) < 5)
-			 && (fabs((double)(screen.last_y - screen.start_y)) < 5)) {
-				render_fill_selection_buffer_from_mouse_click (
-						event->x, event->y, index,
-						sel_action);
-			} else {
-				render_fill_selection_buffer_from_mouse_drag (
-						event->x, event->y,
-						screen.start_x, screen.start_y,
-						index, sel_action);
-			}
-
-			/* Check if anything was selected */
-			update_selected_object_message (TRUE);
-
-			check_align_files_possibility (&screen.selectionInfo);
-		} else {
-			render_refresh_rendered_image_on_screen ();
-		}
-		break;
-	default:
-		break;
-	}
-
-	screen.state = NORMAL;
-
-	return TRUE;
+callbacks_drawingarea_button_release_event(GtkWidget* widget, GdkEventButton* event) {
+    gint index;
+
+    if (event->type != GDK_BUTTON_RELEASE)
+        return TRUE;
+
+    switch (screen.state) {
+        case IN_MOVE:
+            screen.off_x = 0;
+            screen.off_y = 0;
+            render_refresh_rendered_image_on_screen();
+            callbacks_switch_to_normal_tool_cursor(screen.tool);
+            break;
+
+        case IN_ZOOM_OUTLINE:
+            if ((event->state & GDK_SHIFT_MASK) != 0) {
+                render_zoom_display(ZOOM_OUT_CMOUSE, 0, event->x, event->y);
+            }
+            /* if the user just clicks without dragging, then simply
+               zoom in a preset amount */
+            else if ((abs(screen.start_x - event->x) < 4) && (abs(screen.start_y - event->y) < 4)) {
+                render_zoom_display(ZOOM_IN_CMOUSE, 0, event->x, event->y);
+            } else {
+                render_calculate_zoom_from_outline(widget, event);
+            }
+            callbacks_switch_to_normal_tool_cursor(screen.tool);
+            break;
+
+        case IN_SELECTION_DRAG:
+            /* selection will only work with cairo, so do nothing if it's
+               not compiled */
+            index = callbacks_get_selected_row_index();
+
+            if ((index >= 0) && mainProject->file[index]->isVisible) {
+                enum selection_action sel_action = SELECTION_REPLACE;
+
+                if (event->state & GDK_SHIFT_MASK)
+                    sel_action = SELECTION_ADD;
+                else if (event->state & GDK_CONTROL_MASK)
+                    sel_action = SELECTION_TOGGLE;
+
+                /* determine if this was just a click or a box drag */
+                if ((fabs((double)(screen.last_x - screen.start_x)) < 5)
+                    && (fabs((double)(screen.last_y - screen.start_y)) < 5)) {
+                    render_fill_selection_buffer_from_mouse_click(event->x, event->y, index, sel_action);
+                } else {
+                    render_fill_selection_buffer_from_mouse_drag(
+                        event->x, event->y, screen.start_x, screen.start_y, index, sel_action
+                    );
+                }
+
+                /* Check if anything was selected */
+                update_selected_object_message(TRUE);
+
+                check_align_files_possibility(&screen.selectionInfo);
+            } else {
+                render_refresh_rendered_image_on_screen();
+            }
+            break;
+        default: break;
+    }
+
+    screen.state = NORMAL;
+
+    return TRUE;
 } /* button_release_event */
 
 /* --------------------------------------------------------- */
 gboolean
-callbacks_window_key_press_event (GtkWidget *widget, GdkEventKey *event)
-{
-	switch (event->keyval) {
-	case GDK_Escape:
-		if (screen.tool == POINTER) {
-			selection_clear (&screen.selectionInfo);
-			update_selected_object_message (FALSE);
-		}
-
-		/* Escape may be used to abort outline zoom and just plain
-		 * repaint */
-		screen.state = NORMAL;
-		render_refresh_rendered_image_on_screen();
-
-		break;
-	default:
-		break;
-	}
-
-	return TRUE;
+callbacks_window_key_press_event(GtkWidget* widget, GdkEventKey* event) {
+    switch (event->keyval) {
+        case GDK_Escape:
+            if (screen.tool == POINTER) {
+                selection_clear(&screen.selectionInfo);
+                update_selected_object_message(FALSE);
+            }
+
+            /* Escape may be used to abort outline zoom and just plain
+             * repaint */
+            screen.state = NORMAL;
+            render_refresh_rendered_image_on_screen();
+
+            break;
+        default: break;
+    }
+
+    return TRUE;
 } /* key_press_event */
 
 /* --------------------------------------------------------- */
 gboolean
-callbacks_window_key_release_event (GtkWidget *widget, GdkEventKey *event)
-{
-	return TRUE;
+callbacks_window_key_release_event(GtkWidget* widget, GdkEventKey* event) {
+    return TRUE;
 } /* key_release_event */
 
 /* --------------------------------------------------------- */
 /* Scroll wheel */
 gboolean
-callbacks_window_scroll_event(GtkWidget *widget, GdkEventScroll *event)
-{
-	switch (event->direction) {
-		case GDK_SCROLL_UP:
-			render_zoom_display (ZOOM_IN_CMOUSE, 0, event->x, event->y);
-			break;
-		case GDK_SCROLL_DOWN:
-			render_zoom_display (ZOOM_OUT_CMOUSE, 0, event->x, event->y);
-			break;
-		case GDK_SCROLL_LEFT: 
-			/* Ignore */
-		case GDK_SCROLL_RIGHT:
-			/* Ignore */
-		default:
-			return TRUE;
-	}
-	return TRUE;
+callbacks_window_scroll_event(GtkWidget* widget, GdkEventScroll* event) {
+    switch (event->direction) {
+        case GDK_SCROLL_UP: render_zoom_display(ZOOM_IN_CMOUSE, 0, event->x, event->y); break;
+        case GDK_SCROLL_DOWN: render_zoom_display(ZOOM_OUT_CMOUSE, 0, event->x, event->y); break;
+        case GDK_SCROLL_LEFT:
+            /* Ignore */
+        case GDK_SCROLL_RIGHT:
+            /* Ignore */
+        default: return TRUE;
+    }
+    return TRUE;
 } /* scroll_event */
 
-
 /* ------------------------------------------------------------------ */
 /** Displays additional information in the statusbar.
     The Statusbar is divided into three sections:\n
     statusbar.coordstr for coords\n
-    statusbar.diststr for displaying measured distances or the designator 
+    statusbar.diststr for displaying measured distances or the designator
     (right click on a graphically marked and also actively selected part)\n
     statusbar.msg for e.g. showing progress of actions*/
 void
-callbacks_update_statusbar(void)
-{
-	if ((screen.statusbar.coordstr != NULL)&&(GTK_IS_LABEL(screen.win.statusMessageLeft))) {
-		gtk_label_set_text(GTK_LABEL(screen.win.statusMessageLeft), screen.statusbar.coordstr);
-	}
-	if ((screen.statusbar.diststr != NULL)&&(GTK_IS_LABEL(screen.win.statusMessageRight))) {
-		gtk_label_set_markup(GTK_LABEL(screen.win.statusMessageRight), screen.statusbar.diststr);
-	}
+callbacks_update_statusbar(void) {
+    if ((screen.statusbar.coordstr != NULL) && (GTK_IS_LABEL(screen.win.statusMessageLeft))) {
+        gtk_label_set_text(GTK_LABEL(screen.win.statusMessageLeft), screen.statusbar.coordstr);
+    }
+    if ((screen.statusbar.diststr != NULL) && (GTK_IS_LABEL(screen.win.statusMessageRight))) {
+        gtk_label_set_markup(GTK_LABEL(screen.win.statusMessageRight), screen.statusbar.diststr);
+    }
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_update_statusbar_measured_distance (gdouble dx, gdouble dy){
-	gdouble delta = hypot(dx, dy);
-	
-	if (screen.unit == GERBV_MILS) {
-	    utf8_snprintf(screen.statusbar.diststr, MAX_DISTLEN,
-		     _("Measured distance: %8.2f mils (%8.2f x, %8.2f y)"),
-		     COORD2MILS(delta), COORD2MILS(dx), COORD2MILS(dy));
-	} 
-	else if (screen.unit == GERBV_MMS) {
-	    utf8_snprintf(screen.statusbar.diststr, MAX_DISTLEN,
-		     _("Measured distance: %8.3f mm (%8.3f x, %8.3f y)"),
-		     COORD2MMS(delta), COORD2MMS(dx), COORD2MMS(dy));
-	}
-	else {
-	    utf8_snprintf(screen.statusbar.diststr, MAX_DISTLEN,
-		     _("Measured distance: %4.5f inches (%4.5f x, %4.5f y)"),
-		     COORD2INS(delta), COORD2INS(dx), COORD2INS(dy));
-	}
-	callbacks_update_statusbar();
+callbacks_update_statusbar_measured_distance(gdouble dx, gdouble dy) {
+    gdouble delta = hypot(dx, dy);
+
+    if (screen.unit == GERBV_MILS) {
+        utf8_snprintf(
+            screen.statusbar.diststr, MAX_DISTLEN, _("Measured distance: %8.2f mils (%8.2f x, %8.2f y)"),
+            COORD2MILS(delta), COORD2MILS(dx), COORD2MILS(dy)
+        );
+    } else if (screen.unit == GERBV_MMS) {
+        utf8_snprintf(
+            screen.statusbar.diststr, MAX_DISTLEN, _("Measured distance: %8.3f mm (%8.3f x, %8.3f y)"),
+            COORD2MMS(delta), COORD2MMS(dx), COORD2MMS(dy)
+        );
+    } else {
+        utf8_snprintf(
+            screen.statusbar.diststr, MAX_DISTLEN, _("Measured distance: %4.5f inches (%4.5f x, %4.5f y)"),
+            COORD2INS(delta), COORD2INS(dx), COORD2INS(dy)
+        );
+    }
+    callbacks_update_statusbar();
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_sidepane_render_type_combo_box_changed (GtkComboBox *widget, gpointer user_data) {
-	gerbv_render_types_t type = gtk_combo_box_get_active (widget);
-	
-	dprintf ("%s():  type = %d\n", __FUNCTION__, type);
+callbacks_sidepane_render_type_combo_box_changed(GtkComboBox* widget, gpointer user_data) {
+    gerbv_render_types_t type = gtk_combo_box_get_active(widget);
 
-	if (type < 0 || type == screenRenderInfo.renderType)
-		return;
+    dprintf("%s():  type = %d\n", __FUNCTION__, type);
 
-	screenRenderInfo.renderType = type;
-	callbacks_render_type_changed ();
+    if (type < 0 || type == screenRenderInfo.renderType)
+        return;
+
+    screenRenderInfo.renderType = type;
+    callbacks_render_type_changed();
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_viewmenu_rendertype_changed (GtkCheckMenuItem *widget, gpointer user_data) {
-	gerbv_render_types_t type = GPOINTER_TO_INT(user_data);
+callbacks_viewmenu_rendertype_changed(GtkCheckMenuItem* widget, gpointer user_data) {
+    gerbv_render_types_t type = GPOINTER_TO_INT(user_data);
 
-	if (type == screenRenderInfo.renderType)
-		return;
+    if (type == screenRenderInfo.renderType)
+        return;
 
-	dprintf ("%s():  type = %d\n", __FUNCTION__, type);
+    dprintf("%s():  type = %d\n", __FUNCTION__, type);
 
-	screenRenderInfo.renderType = type;
-	callbacks_render_type_changed ();
+    screenRenderInfo.renderType = type;
+    callbacks_render_type_changed();
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_viewmenu_units_changed (GtkCheckMenuItem *widget, gpointer user_data) {
-	gerbv_gui_unit_t unit = GPOINTER_TO_INT(user_data);
+callbacks_viewmenu_units_changed(GtkCheckMenuItem* widget, gpointer user_data) {
+    gerbv_gui_unit_t unit = GPOINTER_TO_INT(user_data);
 
-	if (unit < 0 || unit == screen.unit)
-		return;
+    if (unit < 0 || unit == screen.unit)
+        return;
 
-	dprintf ("%s():  unit = %d, screen.unit = %d\n", __FUNCTION__, unit, screen.unit);
+    dprintf("%s():  unit = %d, screen.unit = %d\n", __FUNCTION__, unit, screen.unit);
 
-	callbacks_units_changed (unit);
+    callbacks_units_changed(unit);
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_statusbar_unit_combo_box_changed (GtkComboBox *widget, gpointer user_data) {
-	gerbv_gui_unit_t unit = gtk_combo_box_get_active (widget);
-	int force_change = GPOINTER_TO_INT (user_data);
+callbacks_statusbar_unit_combo_box_changed(GtkComboBox* widget, gpointer user_data) {
+    gerbv_gui_unit_t unit         = gtk_combo_box_get_active(widget);
+    int              force_change = GPOINTER_TO_INT(user_data);
 
-	if (!force_change && (unit < 0 || unit == screen.unit))
-		return;
+    if (!force_change && (unit < 0 || unit == screen.unit))
+        return;
 
-	callbacks_units_changed (unit);
+    callbacks_units_changed(unit);
 }
 
 /* --------------------------------------------------------- */
 void
-callbacks_clear_messages_button_clicked  (GtkButton *button, gpointer   user_data) {
-	GtkTextBuffer *textbuffer;
-	GtkTextIter start, end;
+callbacks_clear_messages_button_clicked(GtkButton* button, gpointer user_data) {
+    GtkTextBuffer* textbuffer;
+    GtkTextIter    start, end;
 
-	screen.length_sum = 0;
+    screen.length_sum = 0;
 
-	textbuffer = gtk_text_view_get_buffer((GtkTextView*)screen.win.messageTextView);
-	gtk_text_buffer_get_start_iter(textbuffer, &start);
-	gtk_text_buffer_get_end_iter(textbuffer, &end);
-	gtk_text_buffer_delete (textbuffer, &start, &end);
+    textbuffer = gtk_text_view_get_buffer((GtkTextView*)screen.win.messageTextView);
+    gtk_text_buffer_get_start_iter(textbuffer, &start);
+    gtk_text_buffer_get_end_iter(textbuffer, &end);
+    gtk_text_buffer_delete(textbuffer, &start, &end);
 }
-            
+
 /* --------------------------------------------------------- */
 void
-callbacks_handle_log_messages(const gchar *log_domain, GLogLevelFlags log_level,
-		      const gchar *message, gpointer user_data)
-{
-	GtkTextBuffer *textbuffer = NULL;
-	GtkTextIter iter;
-	GtkTextTag *tag;
-	GtkTextMark *StartMark = NULL, *StopMark = NULL;
-	GtkTextIter StartIter, StopIter;
-	GtkWidget *dialog, *label;
-
-	if (!screen.win.messageTextView)
-		return;
-		
-	textbuffer = gtk_text_view_get_buffer((GtkTextView*)screen.win.messageTextView);
-
-	/* create a mark for the end of the text. */
-	gtk_text_buffer_get_end_iter(textbuffer, &iter);
-
-	/* get the current end position of the text (it will be the
-	      start of the new text. */
-	StartMark = gtk_text_buffer_create_mark(textbuffer,
-					    "NewTextStart", &iter, TRUE);
-
-	tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer),
-	                              "blue_foreground");
-	/* the tag does not exist: create it and let them exist in the tag table.*/
-	if (tag == NULL)    {
-		tag = gtk_text_buffer_create_tag(textbuffer, "black_foreground",
-		                              "foreground", "black", NULL);
-		tag = gtk_text_buffer_create_tag(textbuffer, "blue_foreground",
-		                              "foreground", "blue", NULL);
-		tag = gtk_text_buffer_create_tag(textbuffer, "red_foreground",
-		                              "foreground", "red", NULL);
-		tag = gtk_text_buffer_create_tag(textbuffer, "darkred_foreground",
-		                              "foreground", "darkred", NULL);
-		tag = gtk_text_buffer_create_tag(textbuffer, "darkblue_foreground",
-		                              "foreground", "darkblue", NULL);
-		tag = gtk_text_buffer_create_tag (textbuffer, "darkgreen_foreground",
-		                              "foreground", "darkgreen", NULL);
-		tag = gtk_text_buffer_create_tag (textbuffer,
-		                              "saddlebrown_foreground",
-		                              "foreground", "saddlebrown", NULL);
-	}
-
-	/* 
-	* See rgb.txt for the color names definition 
-	* (on my PC it is on /usr/X11R6/lib/X11/rgb.txt)
-	*/
-	switch (log_level & G_LOG_LEVEL_MASK) {
-	case G_LOG_LEVEL_ERROR:
-	/* a message of this kind aborts the application calling abort() */
-	      tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer),
-	                                    "red_foreground");
-	      gtk_notebook_set_current_page(GTK_NOTEBOOK(screen.win.sidepane_notebook), 1);
-	      gtk_widget_show(screen.win.sidepane_notebook);
-		break;
-	case G_LOG_LEVEL_CRITICAL:
-	      tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer),
-	                                    "red_foreground");
-	      gtk_notebook_set_current_page(GTK_NOTEBOOK(screen.win.sidepane_notebook), 1);
-	      gtk_widget_show(screen.win.sidepane_notebook);
-		break;
-	case G_LOG_LEVEL_WARNING:
-	      tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer),
-	                                    "darkred_foreground");
-	      gtk_notebook_set_current_page(GTK_NOTEBOOK(screen.win.sidepane_notebook), 1);
-	      gtk_widget_show(screen.win.sidepane_notebook);
-		break;
-	case G_LOG_LEVEL_MESSAGE:
-	      tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer),
-	                                    "darkblue_foreground");
-	      gtk_notebook_set_current_page(GTK_NOTEBOOK(screen.win.sidepane_notebook), 1);
-	      gtk_widget_show(screen.win.sidepane_notebook);
-		break;
-	case G_LOG_LEVEL_INFO:
-	      tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer),
-	                                    "darkgreen_foreground");
-		break;
-	case G_LOG_LEVEL_DEBUG:
-		tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer),
-					"saddlebrown_foreground");
-		break;
-	default:
-	      tag = gtk_text_tag_table_lookup (gtk_text_buffer_get_tag_table(textbuffer),
-	                                    "black_foreground");
-		break;
-	}
-
-	/*
-	* Fatal aborts application. We will try to get the message out anyhow.
-	*/
-	if (log_level & G_LOG_FLAG_FATAL) {
-		fprintf(stderr, _("Fatal error: %s\n"), message);
-
-		/* Try to show dialog box with error message */
-		dialog = gtk_dialog_new_with_buttons(_("Fatal Error"),
-			NULL, GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
-			GTK_STOCK_OK, GTK_RESPONSE_ACCEPT, NULL);
-
-		label = gtk_label_new(g_strdup_printf(_("Fatal error: %s"), message));
-		gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox),
-				label);
-		gtk_label_set_selectable(GTK_LABEL(label), TRUE);
-		gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox),
-				gtk_label_new(_("\nGerbv will be closed now!")));
-
-		gtk_container_set_border_width(GTK_CONTAINER(dialog), 5);
-
-		gtk_widget_show_all(dialog);
-		gtk_dialog_run(GTK_DIALOG(dialog));
-	}
-
-	gtk_text_buffer_insert(textbuffer, &iter, message, -1);
-	gtk_text_buffer_insert(textbuffer, &iter, "\n", -1);
-
-	/* Scroll view to inserted text */
-	g_signal_emit_by_name(textbuffer, "paste-done", NULL);
-
-	gtk_text_buffer_get_end_iter(textbuffer, &iter);
-
-	StopMark = gtk_text_buffer_create_mark(textbuffer,
-					   "NewTextStop", &iter, TRUE);
-
-	gtk_text_buffer_get_iter_at_mark(textbuffer, &StartIter, StartMark);
-	gtk_text_buffer_get_iter_at_mark(textbuffer, &StopIter, StopMark);
-
-	gtk_text_buffer_apply_tag(textbuffer, tag, &StartIter, &StopIter);
+callbacks_handle_log_messages(
+    const gchar* log_domain, GLogLevelFlags log_level, const gchar* message, gpointer user_data
+) {
+    GtkTextBuffer* textbuffer = NULL;
+    GtkTextIter    iter;
+    GtkTextTag*    tag;
+    GtkTextMark *  StartMark = NULL, *StopMark = NULL;
+    GtkTextIter    StartIter, StopIter;
+    GtkWidget *    dialog, *label;
+
+    if (!screen.win.messageTextView)
+        return;
+
+    textbuffer = gtk_text_view_get_buffer((GtkTextView*)screen.win.messageTextView);
+
+    /* create a mark for the end of the text. */
+    gtk_text_buffer_get_end_iter(textbuffer, &iter);
+
+    /* get the current end position of the text (it will be the
+          start of the new text. */
+    StartMark = gtk_text_buffer_create_mark(textbuffer, "NewTextStart", &iter, TRUE);
+
+    tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer), "blue_foreground");
+    /* the tag does not exist: create it and let them exist in the tag table.*/
+    if (tag == NULL) {
+        tag = gtk_text_buffer_create_tag(textbuffer, "black_foreground", "foreground", "black", NULL);
+        tag = gtk_text_buffer_create_tag(textbuffer, "blue_foreground", "foreground", "blue", NULL);
+        tag = gtk_text_buffer_create_tag(textbuffer, "red_foreground", "foreground", "red", NULL);
+        tag = gtk_text_buffer_create_tag(textbuffer, "darkred_foreground", "foreground", "darkred", NULL);
+        tag = gtk_text_buffer_create_tag(textbuffer, "darkblue_foreground", "foreground", "darkblue", NULL);
+        tag = gtk_text_buffer_create_tag(textbuffer, "darkgreen_foreground", "foreground", "darkgreen", NULL);
+        tag = gtk_text_buffer_create_tag(textbuffer, "saddlebrown_foreground", "foreground", "saddlebrown", NULL);
+    }
+
+    /*
+     * See rgb.txt for the color names definition
+     * (on my PC it is on /usr/X11R6/lib/X11/rgb.txt)
+     */
+    switch (log_level & G_LOG_LEVEL_MASK) {
+        case G_LOG_LEVEL_ERROR:
+            /* a message of this kind aborts the application calling abort() */
+            tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer), "red_foreground");
+            gtk_notebook_set_current_page(GTK_NOTEBOOK(screen.win.sidepane_notebook), 1);
+            gtk_widget_show(screen.win.sidepane_notebook);
+            break;
+        case G_LOG_LEVEL_CRITICAL:
+            tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer), "red_foreground");
+            gtk_notebook_set_current_page(GTK_NOTEBOOK(screen.win.sidepane_notebook), 1);
+            gtk_widget_show(screen.win.sidepane_notebook);
+            break;
+        case G_LOG_LEVEL_WARNING:
+            tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer), "darkred_foreground");
+            gtk_notebook_set_current_page(GTK_NOTEBOOK(screen.win.sidepane_notebook), 1);
+            gtk_widget_show(screen.win.sidepane_notebook);
+            break;
+        case G_LOG_LEVEL_MESSAGE:
+            tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer), "darkblue_foreground");
+            gtk_notebook_set_current_page(GTK_NOTEBOOK(screen.win.sidepane_notebook), 1);
+            gtk_widget_show(screen.win.sidepane_notebook);
+            break;
+        case G_LOG_LEVEL_INFO:
+            tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer), "darkgreen_foreground");
+            break;
+        case G_LOG_LEVEL_DEBUG:
+            tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer), "saddlebrown_foreground");
+            break;
+        default: tag = gtk_text_tag_table_lookup(gtk_text_buffer_get_tag_table(textbuffer), "black_foreground"); break;
+    }
+
+    /*
+     * Fatal aborts application. We will try to get the message out anyhow.
+     */
+    if (log_level & G_LOG_FLAG_FATAL) {
+        fprintf(stderr, _("Fatal error: %s\n"), message);
+
+        /* Try to show dialog box with error message */
+        dialog = gtk_dialog_new_with_buttons(
+            _("Fatal Error"), NULL, GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_STOCK_OK,
+            GTK_RESPONSE_ACCEPT, NULL
+        );
+
+        label = gtk_label_new(g_strdup_printf(_("Fatal error: %s"), message));
+        gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), label);
+        gtk_label_set_selectable(GTK_LABEL(label), TRUE);
+        gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), gtk_label_new(_("\nGerbv will be closed now!")));
+
+        gtk_container_set_border_width(GTK_CONTAINER(dialog), 5);
+
+        gtk_widget_show_all(dialog);
+        gtk_dialog_run(GTK_DIALOG(dialog));
+    }
+
+    gtk_text_buffer_insert(textbuffer, &iter, message, -1);
+    gtk_text_buffer_insert(textbuffer, &iter, "\n", -1);
+
+    /* Scroll view to inserted text */
+    g_signal_emit_by_name(textbuffer, "paste-done", NULL);
+
+    gtk_text_buffer_get_end_iter(textbuffer, &iter);
+
+    StopMark = gtk_text_buffer_create_mark(textbuffer, "NewTextStop", &iter, TRUE);
+
+    gtk_text_buffer_get_iter_at_mark(textbuffer, &StartIter, StartMark);
+    gtk_text_buffer_get_iter_at_mark(textbuffer, &StopIter, StopMark);
+
+    gtk_text_buffer_apply_tag(textbuffer, tag, &StartIter, &StopIter);
 }
 
 /* --------------------------------------------------------- */
-void callbacks_force_expose_event_for_screen (void)
-{
-	GdkRectangle update_rect;
-	
-	update_rect.x = 0;
-	update_rect.y = 0;
-	update_rect.width = screenRenderInfo.displayWidth;
-	update_rect.height = screenRenderInfo.displayHeight;
-
-	/* Calls expose_event */
-	gdk_window_invalidate_rect (screen.drawing_area->window, &update_rect, FALSE);
-	
-	/* update other gui things that could have changed */
-	callbacks_update_ruler_scales ();
-	callbacks_update_scrollbar_limits ();
-	callbacks_update_scrollbar_positions ();
+void
+callbacks_force_expose_event_for_screen(void) {
+    GdkRectangle update_rect;
+
+    update_rect.x      = 0;
+    update_rect.y      = 0;
+    update_rect.width  = screenRenderInfo.displayWidth;
+    update_rect.height = screenRenderInfo.displayHeight;
+
+    /* Calls expose_event */
+    gdk_window_invalidate_rect(screen.drawing_area->window, &update_rect, FALSE);
+
+    /* update other gui things that could have changed */
+    callbacks_update_ruler_scales();
+    callbacks_update_scrollbar_limits();
+    callbacks_update_scrollbar_positions();
 }
 
-static double screen_units(double d)
-{
-	switch (screen.unit) {
-	case GERBV_INS:
-		return COORD2INS(d);
-		break;
-	case GERBV_MILS:
-		return COORD2MILS(d);
-		break;
-	case GERBV_MMS:
-		return COORD2MMS(d);
-		break;
-	}
-
-	return d;
+static double
+screen_units(double d) {
+    switch (screen.unit) {
+        case GERBV_INS: return COORD2INS(d); break;
+        case GERBV_MILS: return COORD2MILS(d); break;
+        case GERBV_MMS: return COORD2MMS(d); break;
+    }
+
+    return d;
 }
 
-static const char *screen_units_str(void)
-{
-	/* NOTE: in order of gerbv_gui_unit_t */
-	const char *units_str[] = {N_("mil"), N_("mm"), N_("in")};
+static const char*
+screen_units_str(void) {
+    /* NOTE: in order of gerbv_gui_unit_t */
+    const char* units_str[] = { N_("mil"), N_("mm"), N_("in") };
 
-	return _(units_str[screen.unit]);
+    return _(units_str[screen.unit]);
 }
 
-static double line_length(double x0, double y0, double x1, double y1)
-{
-	double dx = x0 - x1;
-	double dy = y0 - y1;
+static double
+line_length(double x0, double y0, double x1, double y1) {
+    double dx = x0 - x1;
+    double dy = y0 - y1;
 
-	return hypot(dx, dy);
+    return hypot(dx, dy);
 }
 
-static double arc_length(double dia, double angle)
-{
-	return M_PI*dia*(angle/360.0);
+static double
+arc_length(double dia, double angle) {
+    return M_PI * dia * (angle / 360.0);
 }
 
-static void aperture_state_report (gerbv_net_t *net,
-		gerbv_image_t *img, gerbv_project_t *prj)
-{
-	gerbv_layertype_t layer_type = img->layertype;
-
-	gboolean show_length = FALSE;
-	gboolean aperture_is_valid = FALSE;
-	double x, y, len = 0;
-
-	if (net->aperture > 0)
-		aperture_is_valid = TRUE;
-
-	switch (net->aperture_state) {
-
-	case GERBV_APERTURE_STATE_OFF:
-		break;
-
-	case GERBV_APERTURE_STATE_ON:
-		switch (net->interpolation) {
-
-		case GERBV_INTERPOLATION_LINEARx1:
-		case GERBV_INTERPOLATION_LINEARx10:
-		case GERBV_INTERPOLATION_LINEARx01:
-		case GERBV_INTERPOLATION_LINEARx001:
-			if (layer_type != GERBV_LAYERTYPE_DRILL)
-				g_message (_("Object type: Line"));
-			else
-				g_message (_("Object type: Slot (drilled)"));
-
-			len = line_length(net->start_x, net->start_y,
-					net->stop_x, net->stop_y);
-			show_length = 1;
-
-			break;
-
-		case GERBV_INTERPOLATION_CW_CIRCULAR:
-		case GERBV_INTERPOLATION_CCW_CIRCULAR:
-			g_message (_("Object type: Arc"));
-			len = arc_length(net->cirseg->width,
-					fabs(net->cirseg->angle1 -
-						net->cirseg->angle2));
-			show_length = 1;
-
-			break;
-		default:
-			g_message (_("Object type: Unknown"));
-			break;
-		}
-
-		if (layer_type != GERBV_LAYERTYPE_DRILL)
-			g_message (_("    Exposure: On"));
-
-		if (aperture_is_valid) {
-			if (layer_type != GERBV_LAYERTYPE_DRILL)
-				aperture_report(img->aperture, net->aperture,
-						net->start_x, net->start_y,
-						img, prj);
-			else
-				drill_report(img->aperture, net->aperture);
-		}
-
-		x = net->start_x;
-		y = net->start_y;
-		gerbv_transform_coord_for_image(&x, &y, img, prj);
-		g_message (_("    Start: (%g, %g) %s"),
-				screen_units(x),
-				screen_units(y),
-				screen_units_str());
-
-		x = net->stop_x;
-		y = net->stop_y;
-		gerbv_transform_coord_for_image(&x, &y, img, prj);
-		g_message (_("    Stop: (%g, %g) %s"),
-				screen_units(x),
-				screen_units(y),
-				screen_units_str());
-
-		switch (net->interpolation) {
-
-		case GERBV_INTERPOLATION_CW_CIRCULAR:
-		case GERBV_INTERPOLATION_CCW_CIRCULAR:
-			x = net->cirseg->cp_x;
-			y = net->cirseg->cp_y;
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("    Center: (%g, %g) %s"),
-					screen_units(x),
-					screen_units(y),
-					screen_units_str());
-
-			x = net->cirseg->width/2;
-			y = x;
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("    Radius: %g %s"),
-					screen_units(x),
-					screen_units_str());
-
-			g_message (_("    Angle: %g deg"),
-					fabs(net->cirseg->angle1 -
-						net->cirseg->angle2));
-			g_message (_("    Angles: (%g, %g) deg"),
-					net->cirseg->angle1,
-					net->cirseg->angle2);
-			g_message (_("    Direction: %s"),
-					(net->interpolation ==
-					 GERBV_INTERPOLATION_CW_CIRCULAR)?
-						_("CW"): _("CCW"));
-			break;
-
-		default:
-			break;
-		}
-
-		if (show_length) {
-			gerbv_aperture_t *aper = img->aperture[net->aperture];
-
-			if (layer_type == GERBV_LAYERTYPE_DRILL
-			&&  aperture_is_valid
-			&&  aper->type == GERBV_APTYPE_CIRCLE) {
-				double dia = aper->parameter[0];
-				g_message (_("    Slot length: %g %s"),
-						screen_units(len + dia),
-						screen_units_str());
-			}
-
-			screen.length_sum += len;
-			g_message (_("    Length: %g (sum: %g) %s"),
-					screen_units(len),
-					screen_units(screen.length_sum),
-					screen_units_str());
-		}
-
-		net_layer_file_report (net, img, prj);
-
-		break;
-
-	case GERBV_APERTURE_STATE_FLASH:
-		if (layer_type != GERBV_LAYERTYPE_DRILL)
-			g_message (_("Object type: Flashed aperture"));
-		else
-			g_message (_("Object type: Drill"));
-
-		if (aperture_is_valid) {
-			if (layer_type != GERBV_LAYERTYPE_DRILL)
-				aperture_report(img->aperture, net->aperture,
-						net->stop_x, net->stop_y,
-						img, prj);
-			else
-				drill_report(img->aperture, net->aperture);
-		}
-
-		x = net->stop_x;
-		y = net->stop_y;
-		gerbv_transform_coord_for_image(&x, &y, img, prj);
-		g_message (_("    Location: (%g, %g) %s"),
-				screen_units(x),
-				screen_units(y),
-				screen_units_str());
-
-		net_layer_file_report (net, img, prj);
-
-		break;
-	}
+static void
+aperture_state_report(gerbv_net_t* net, gerbv_image_t* img, gerbv_project_t* prj) {
+    gerbv_layertype_t layer_type = img->layertype;
+
+    gboolean show_length       = FALSE;
+    gboolean aperture_is_valid = FALSE;
+    double   x, y, len = 0;
+
+    if (net->aperture > 0)
+        aperture_is_valid = TRUE;
+
+    switch (net->aperture_state) {
+
+        case GERBV_APERTURE_STATE_OFF: break;
+
+        case GERBV_APERTURE_STATE_ON:
+            switch (net->interpolation) {
+
+                case GERBV_INTERPOLATION_LINEARx1:
+                case GERBV_INTERPOLATION_LINEARx10:
+                case GERBV_INTERPOLATION_LINEARx01:
+                case GERBV_INTERPOLATION_LINEARx001:
+                    if (layer_type != GERBV_LAYERTYPE_DRILL)
+                        g_message(_("Object type: Line"));
+                    else
+                        g_message(_("Object type: Slot (drilled)"));
+
+                    len         = line_length(net->start_x, net->start_y, net->stop_x, net->stop_y);
+                    show_length = 1;
+
+                    break;
+
+                case GERBV_INTERPOLATION_CW_CIRCULAR:
+                case GERBV_INTERPOLATION_CCW_CIRCULAR:
+                    g_message(_("Object type: Arc"));
+                    len         = arc_length(net->cirseg->width, fabs(net->cirseg->angle1 - net->cirseg->angle2));
+                    show_length = 1;
+
+                    break;
+                default: g_message(_("Object type: Unknown")); break;
+            }
+
+            if (layer_type != GERBV_LAYERTYPE_DRILL)
+                g_message(_("    Exposure: On"));
+
+            if (aperture_is_valid) {
+                if (layer_type != GERBV_LAYERTYPE_DRILL)
+                    aperture_report(img->aperture, net->aperture, net->start_x, net->start_y, img, prj);
+                else
+                    drill_report(img->aperture, net->aperture);
+            }
+
+            x = net->start_x;
+            y = net->start_y;
+            gerbv_transform_coord_for_image(&x, &y, img, prj);
+            g_message(_("    Start: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+
+            x = net->stop_x;
+            y = net->stop_y;
+            gerbv_transform_coord_for_image(&x, &y, img, prj);
+            g_message(_("    Stop: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+
+            switch (net->interpolation) {
+
+                case GERBV_INTERPOLATION_CW_CIRCULAR:
+                case GERBV_INTERPOLATION_CCW_CIRCULAR:
+                    x = net->cirseg->cp_x;
+                    y = net->cirseg->cp_y;
+                    gerbv_transform_coord_for_image(&x, &y, img, prj);
+                    g_message(_("    Center: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+
+                    x = net->cirseg->width / 2;
+                    y = x;
+                    gerbv_transform_coord_for_image(&x, &y, img, prj);
+                    g_message(_("    Radius: %g %s"), screen_units(x), screen_units_str());
+
+                    g_message(_("    Angle: %g deg"), fabs(net->cirseg->angle1 - net->cirseg->angle2));
+                    g_message(_("    Angles: (%g, %g) deg"), net->cirseg->angle1, net->cirseg->angle2);
+                    g_message(
+                        _("    Direction: %s"),
+                        (net->interpolation == GERBV_INTERPOLATION_CW_CIRCULAR) ? _("CW") : _("CCW")
+                    );
+                    break;
+
+                default: break;
+            }
+
+            if (show_length) {
+                gerbv_aperture_t* aper = img->aperture[net->aperture];
+
+                if (layer_type == GERBV_LAYERTYPE_DRILL && aperture_is_valid && aper->type == GERBV_APTYPE_CIRCLE) {
+                    double dia = aper->parameter[0];
+                    g_message(_("    Slot length: %g %s"), screen_units(len + dia), screen_units_str());
+                }
+
+                screen.length_sum += len;
+                g_message(
+                    _("    Length: %g (sum: %g) %s"), screen_units(len), screen_units(screen.length_sum),
+                    screen_units_str()
+                );
+            }
+
+            net_layer_file_report(net, img, prj);
+
+            break;
+
+        case GERBV_APERTURE_STATE_FLASH:
+            if (layer_type != GERBV_LAYERTYPE_DRILL)
+                g_message(_("Object type: Flashed aperture"));
+            else
+                g_message(_("Object type: Drill"));
+
+            if (aperture_is_valid) {
+                if (layer_type != GERBV_LAYERTYPE_DRILL)
+                    aperture_report(img->aperture, net->aperture, net->stop_x, net->stop_y, img, prj);
+                else
+                    drill_report(img->aperture, net->aperture);
+            }
+
+            x = net->stop_x;
+            y = net->stop_y;
+            gerbv_transform_coord_for_image(&x, &y, img, prj);
+            g_message(_("    Location: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+
+            net_layer_file_report(net, img, prj);
+
+            break;
+    }
 }
 
 static void
-aperture_report(gerbv_aperture_t *apertures[], int aperture_num,
-		double x, double y, gerbv_image_t *img, gerbv_project_t *prj)
-{
-	gerbv_aperture_type_t type = apertures[aperture_num]->type;
-	double *params = apertures[aperture_num]->parameter;
-	gerbv_simplified_amacro_t *sam = apertures[aperture_num]->simplified;
-
-	g_message (_("    Aperture used: D%d"), aperture_num);
-	g_message (_("    Aperture type: %s"),
-		(type == GERBV_APTYPE_MACRO)?
-			_(gerbv_aperture_type_name(sam->type)):
-			_(gerbv_aperture_type_name(type)));
-
-	switch (type) {
-	case GERBV_APTYPE_CIRCLE:
-		g_message (_("    Diameter: %g %s"),
-			screen_units(params[0]),
-			screen_units_str());
-		break;
-	case GERBV_APTYPE_RECTANGLE:
-	case GERBV_APTYPE_OVAL:
-		g_message (_("    Dimensions: %gx%g %s"),
-			screen_units(params[0]),
-			screen_units(params[1]),
-			screen_units_str());
-		break;
-	case GERBV_APTYPE_MACRO: {
-		switch (sam->type) {
-		case GERBV_APTYPE_MACRO_CIRCLE:
-			g_message (_("    Diameter: %g %s"),
-				screen_units(sam->parameter[CIRCLE_DIAMETER]),
-				screen_units_str());
-			x += sam->parameter[CIRCLE_CENTER_X];
-			y += sam->parameter[CIRCLE_CENTER_Y];
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("    Center: (%g, %g) %s"),
-				screen_units(x), screen_units(y),
-				screen_units_str());
-			break;
-
-		case GERBV_APTYPE_MACRO_OUTLINE:
-			g_message (_("    Number of points: %g"),
-				sam->parameter[OUTLINE_NUMBER_OF_POINTS]);
-			x += sam->parameter[OUTLINE_FIRST_X];
-			y += sam->parameter[OUTLINE_FIRST_Y];
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("    Start: (%g, %g) %s"),
-				screen_units(x), screen_units(y),
-				screen_units_str());
-			g_message (_("    Rotation: %g deg"),
-				sam->parameter[OUTLINE_ROTATION_IDX(sam->parameter)]);
-			break;
-
-		case GERBV_APTYPE_MACRO_POLYGON:
-			g_message (_("    Number of points: %g"),
-				sam->parameter[POLYGON_NUMBER_OF_POINTS]);
-			g_message (_("    Diameter: %g %s"),
-				screen_units(sam->parameter[POLYGON_DIAMETER]),
-				screen_units_str());
-			x += sam->parameter[POLYGON_CENTER_X];
-			y += sam->parameter[POLYGON_CENTER_Y];
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("    Center: (%g, %g) %s"),
-				screen_units(x), screen_units(y),
-				screen_units_str());
-			g_message (_("    Rotation: %g deg"),
-				sam->parameter[POLYGON_ROTATION]);
-			break;
-
-		case GERBV_APTYPE_MACRO_MOIRE:
-			g_message (_("    Outside diameter: %g %s"),
-				screen_units(sam->parameter[MOIRE_OUTSIDE_DIAMETER]),
-				screen_units_str());
-			g_message (_("    Ring thickness: %g %s"),
-				screen_units(sam->parameter[MOIRE_CIRCLE_THICKNESS]),
-				screen_units_str());
-			g_message (_("    Gap width: %g %s"),
-				screen_units(sam->parameter[MOIRE_GAP_WIDTH]),
-				screen_units_str());
-			g_message (_("    Number of rings: %g"),
-				sam->parameter[MOIRE_NUMBER_OF_CIRCLES]);
-			g_message (_("    Crosshair thickness: %g %s"),
-				screen_units(
-					sam->parameter[MOIRE_CROSSHAIR_THICKNESS]),
-				screen_units_str());
-			g_message (_("    Crosshair length: %g %s"),
-				screen_units(sam->parameter[MOIRE_CROSSHAIR_LENGTH]),
-				screen_units_str());
-			x += sam->parameter[MOIRE_CENTER_X];
-			y += sam->parameter[MOIRE_CENTER_Y];
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("    Center: (%g, %g) %s"),
-				screen_units(x), screen_units(y),
-				screen_units_str());
-			g_message (_("    Rotation: %g deg"),
-				sam->parameter[MOIRE_ROTATION]);
-			break;
-
-		case GERBV_APTYPE_MACRO_THERMAL:
-			g_message (_("    Outside diameter: %g %s"),
-				screen_units(sam->parameter[THERMAL_OUTSIDE_DIAMETER]),
-				screen_units_str());
-			g_message (_("    Inside diameter: %g %s"),
-				screen_units(sam->parameter[THERMAL_INSIDE_DIAMETER]),
-				screen_units_str());
-			g_message (_("    Crosshair thickness: %g %s"),
-				screen_units(
-					sam->parameter[THERMAL_CROSSHAIR_THICKNESS]),
-				screen_units_str());
-			x += sam->parameter[THERMAL_CENTER_X];
-			y += sam->parameter[THERMAL_CENTER_Y];
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("    Center: (%g, %g) %s"),
-				screen_units(x), screen_units(y),
-				screen_units_str());
-			g_message (_("    Rotation: %g deg"),
-				sam->parameter[THERMAL_ROTATION]);
-			break;
-
-		case GERBV_APTYPE_MACRO_LINE20:
-			g_message (_("    Width: %g %s"),
-				screen_units(sam->parameter[LINE20_WIDTH]),
-				screen_units_str());
-			x += sam->parameter[LINE20_START_X];
-			y += sam->parameter[LINE20_START_Y];
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("    Start: (%g, %g) %s"),
-				screen_units(x), screen_units(y),
-				screen_units_str());
-			x += sam->parameter[LINE20_END_X];
-			y += sam->parameter[LINE20_END_Y];
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("    Stop: (%g, %g) %s"),
-				screen_units(x), screen_units(y),
-				screen_units_str());
-			g_message (_("    Rotation: %g deg"),
-					sam->parameter[LINE20_ROTATION]);
-			break;
-
-		case GERBV_APTYPE_MACRO_LINE21:
-			g_message (_("    Width: %g %s"),
-				screen_units(sam->parameter[LINE21_WIDTH]),
-				screen_units_str());
-			g_message (_("    Height: %g %s"),
-				screen_units(sam->parameter[LINE21_HEIGHT]),
-				screen_units_str());
-			x += sam->parameter[LINE21_CENTER_X];
-			y += sam->parameter[LINE21_CENTER_Y];
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("    Center: (%g, %g) %s"),
-				screen_units(x), screen_units(y),
-				screen_units_str());
-			g_message (_("    Rotation: %g deg"),
-					sam->parameter[LINE21_ROTATION]);
-			break;
-
-		case GERBV_APTYPE_MACRO_LINE22:
-			g_message (_("    Width: %g %s"),
-				screen_units(sam->parameter[LINE22_WIDTH]),
-				screen_units_str());
-			g_message (_("    Height: %g %s"),
-				screen_units(sam->parameter[LINE22_HEIGHT]),
-				screen_units_str());
-			x += sam->parameter[LINE22_LOWER_LEFT_X];
-			y += sam->parameter[LINE22_LOWER_LEFT_Y];
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("    Lower left: (%g, %g) %s"),
-				screen_units(x), screen_units(y),
-				screen_units_str());
-			g_message (_("    Rotation: %g deg"),
-					sam->parameter[LINE22_ROTATION]);
-			break;
-
-		default:
-			break;
-		}
-		break;
-	}
-	default:
-		break;
-	}
+aperture_report(
+    gerbv_aperture_t* apertures[], int aperture_num, double x, double y, gerbv_image_t* img, gerbv_project_t* prj
+) {
+    gerbv_aperture_type_t      type   = apertures[aperture_num]->type;
+    double*                    params = apertures[aperture_num]->parameter;
+    gerbv_simplified_amacro_t* sam    = apertures[aperture_num]->simplified;
+
+    g_message(_("    Aperture used: D%d"), aperture_num);
+    g_message(
+        _("    Aperture type: %s"),
+        (type == GERBV_APTYPE_MACRO) ? _(gerbv_aperture_type_name(sam->type)) : _(gerbv_aperture_type_name(type))
+    );
+
+    switch (type) {
+        case GERBV_APTYPE_CIRCLE:
+            g_message(_("    Diameter: %g %s"), screen_units(params[0]), screen_units_str());
+            break;
+        case GERBV_APTYPE_RECTANGLE:
+        case GERBV_APTYPE_OVAL:
+            g_message(
+                _("    Dimensions: %gx%g %s"), screen_units(params[0]), screen_units(params[1]), screen_units_str()
+            );
+            break;
+        case GERBV_APTYPE_MACRO:
+            {
+                switch (sam->type) {
+                    case GERBV_APTYPE_MACRO_CIRCLE:
+                        g_message(
+                            _("    Diameter: %g %s"), screen_units(sam->parameter[CIRCLE_DIAMETER]), screen_units_str()
+                        );
+                        x += sam->parameter[CIRCLE_CENTER_X];
+                        y += sam->parameter[CIRCLE_CENTER_Y];
+                        gerbv_transform_coord_for_image(&x, &y, img, prj);
+                        g_message(_("    Center: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+                        break;
+
+                    case GERBV_APTYPE_MACRO_OUTLINE:
+                        g_message(_("    Number of points: %g"), sam->parameter[OUTLINE_NUMBER_OF_POINTS]);
+                        x += sam->parameter[OUTLINE_FIRST_X];
+                        y += sam->parameter[OUTLINE_FIRST_Y];
+                        gerbv_transform_coord_for_image(&x, &y, img, prj);
+                        g_message(_("    Start: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+                        g_message(_("    Rotation: %g deg"), sam->parameter[OUTLINE_ROTATION_IDX(sam->parameter)]);
+                        break;
+
+                    case GERBV_APTYPE_MACRO_POLYGON:
+                        g_message(_("    Number of points: %g"), sam->parameter[POLYGON_NUMBER_OF_POINTS]);
+                        g_message(
+                            _("    Diameter: %g %s"), screen_units(sam->parameter[POLYGON_DIAMETER]), screen_units_str()
+                        );
+                        x += sam->parameter[POLYGON_CENTER_X];
+                        y += sam->parameter[POLYGON_CENTER_Y];
+                        gerbv_transform_coord_for_image(&x, &y, img, prj);
+                        g_message(_("    Center: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+                        g_message(_("    Rotation: %g deg"), sam->parameter[POLYGON_ROTATION]);
+                        break;
+
+                    case GERBV_APTYPE_MACRO_MOIRE:
+                        g_message(
+                            _("    Outside diameter: %g %s"), screen_units(sam->parameter[MOIRE_OUTSIDE_DIAMETER]),
+                            screen_units_str()
+                        );
+                        g_message(
+                            _("    Ring thickness: %g %s"), screen_units(sam->parameter[MOIRE_CIRCLE_THICKNESS]),
+                            screen_units_str()
+                        );
+                        g_message(
+                            _("    Gap width: %g %s"), screen_units(sam->parameter[MOIRE_GAP_WIDTH]), screen_units_str()
+                        );
+                        g_message(_("    Number of rings: %g"), sam->parameter[MOIRE_NUMBER_OF_CIRCLES]);
+                        g_message(
+                            _("    Crosshair thickness: %g %s"),
+                            screen_units(sam->parameter[MOIRE_CROSSHAIR_THICKNESS]), screen_units_str()
+                        );
+                        g_message(
+                            _("    Crosshair length: %g %s"), screen_units(sam->parameter[MOIRE_CROSSHAIR_LENGTH]),
+                            screen_units_str()
+                        );
+                        x += sam->parameter[MOIRE_CENTER_X];
+                        y += sam->parameter[MOIRE_CENTER_Y];
+                        gerbv_transform_coord_for_image(&x, &y, img, prj);
+                        g_message(_("    Center: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+                        g_message(_("    Rotation: %g deg"), sam->parameter[MOIRE_ROTATION]);
+                        break;
+
+                    case GERBV_APTYPE_MACRO_THERMAL:
+                        g_message(
+                            _("    Outside diameter: %g %s"), screen_units(sam->parameter[THERMAL_OUTSIDE_DIAMETER]),
+                            screen_units_str()
+                        );
+                        g_message(
+                            _("    Inside diameter: %g %s"), screen_units(sam->parameter[THERMAL_INSIDE_DIAMETER]),
+                            screen_units_str()
+                        );
+                        g_message(
+                            _("    Crosshair thickness: %g %s"),
+                            screen_units(sam->parameter[THERMAL_CROSSHAIR_THICKNESS]), screen_units_str()
+                        );
+                        x += sam->parameter[THERMAL_CENTER_X];
+                        y += sam->parameter[THERMAL_CENTER_Y];
+                        gerbv_transform_coord_for_image(&x, &y, img, prj);
+                        g_message(_("    Center: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+                        g_message(_("    Rotation: %g deg"), sam->parameter[THERMAL_ROTATION]);
+                        break;
+
+                    case GERBV_APTYPE_MACRO_LINE20:
+                        g_message(
+                            _("    Width: %g %s"), screen_units(sam->parameter[LINE20_WIDTH]), screen_units_str()
+                        );
+                        x += sam->parameter[LINE20_START_X];
+                        y += sam->parameter[LINE20_START_Y];
+                        gerbv_transform_coord_for_image(&x, &y, img, prj);
+                        g_message(_("    Start: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+                        x += sam->parameter[LINE20_END_X];
+                        y += sam->parameter[LINE20_END_Y];
+                        gerbv_transform_coord_for_image(&x, &y, img, prj);
+                        g_message(_("    Stop: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+                        g_message(_("    Rotation: %g deg"), sam->parameter[LINE20_ROTATION]);
+                        break;
+
+                    case GERBV_APTYPE_MACRO_LINE21:
+                        g_message(
+                            _("    Width: %g %s"), screen_units(sam->parameter[LINE21_WIDTH]), screen_units_str()
+                        );
+                        g_message(
+                            _("    Height: %g %s"), screen_units(sam->parameter[LINE21_HEIGHT]), screen_units_str()
+                        );
+                        x += sam->parameter[LINE21_CENTER_X];
+                        y += sam->parameter[LINE21_CENTER_Y];
+                        gerbv_transform_coord_for_image(&x, &y, img, prj);
+                        g_message(_("    Center: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+                        g_message(_("    Rotation: %g deg"), sam->parameter[LINE21_ROTATION]);
+                        break;
+
+                    case GERBV_APTYPE_MACRO_LINE22:
+                        g_message(
+                            _("    Width: %g %s"), screen_units(sam->parameter[LINE22_WIDTH]), screen_units_str()
+                        );
+                        g_message(
+                            _("    Height: %g %s"), screen_units(sam->parameter[LINE22_HEIGHT]), screen_units_str()
+                        );
+                        x += sam->parameter[LINE22_LOWER_LEFT_X];
+                        y += sam->parameter[LINE22_LOWER_LEFT_Y];
+                        gerbv_transform_coord_for_image(&x, &y, img, prj);
+                        g_message(
+                            _("    Lower left: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str()
+                        );
+                        g_message(_("    Rotation: %g deg"), sam->parameter[LINE22_ROTATION]);
+                        break;
+
+                    default: break;
+                }
+                break;
+            }
+        default: break;
+    }
 }
 
-static void drill_report(gerbv_aperture_t *apertures[], int aperture_num)
-{
-	gerbv_aperture_type_t type = apertures[aperture_num]->type;
-	double *params = apertures[aperture_num]->parameter;
+static void
+drill_report(gerbv_aperture_t* apertures[], int aperture_num) {
+    gerbv_aperture_type_t type   = apertures[aperture_num]->type;
+    double*               params = apertures[aperture_num]->parameter;
 
-	g_message (_("    Tool used: T%d"), aperture_num);
-	if (type == GERBV_APTYPE_CIRCLE)
-		g_message (_("    Diameter: %g %s"),
-				screen_units(params[0]),
-				screen_units_str());
+    g_message(_("    Tool used: T%d"), aperture_num);
+    if (type == GERBV_APTYPE_CIRCLE)
+        g_message(_("    Diameter: %g %s"), screen_units(params[0]), screen_units_str());
 }
 
-static void parea_report (gerbv_net_t *net,
-		gerbv_image_t *img, gerbv_project_t *prj)
-{
-	gerbv_net_t *n;
-	unsigned int c = 0;
-	gerbv_interpolation_t inter_prev;
-	double x, y;
-
-	if (net->interpolation != GERBV_INTERPOLATION_PAREA_START)
-		return;
-
-	/* Count vertices */
-	for (gerbv_net_t *n = net->next; n != NULL; n = n->next) {
-		if (n->interpolation == GERBV_INTERPOLATION_PAREA_END)
-			break;
-		c++;
-	}
-
-	g_message (_("    Number of vertices: %u"), c - 1);
-
-	for (n = net->next, inter_prev = net->interpolation;
-			n != NULL
-			&& n->interpolation != GERBV_INTERPOLATION_PAREA_END;
-			n = n->next) {
-
-		switch (n->interpolation) {
-
-		case GERBV_INTERPOLATION_LINEARx1:
-
-			if (inter_prev != n->interpolation) {
-				x = n->start_x;
-				y = n->start_y;
-				gerbv_transform_coord_for_image(&x, &y,
-						img, prj);
-				g_message (_("    Line from: (%g, %g) %s"),
-						screen_units(x),
-						screen_units(y),
-						screen_units_str());
-			}
-
-			x = n->stop_x;
-			y = n->stop_y;
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("        Line to: (%g, %g) %s"),
-					screen_units(x), screen_units(y),
-					screen_units_str());
-			break;
-
-		case GERBV_INTERPOLATION_CW_CIRCULAR:
-		case GERBV_INTERPOLATION_CCW_CIRCULAR:
-
-			x = n->start_x;
-			y = n->start_y;
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("    Arc from: (%g, %g) %s"),
-					screen_units(x), screen_units(y),
-					screen_units_str());
-
-			x = n->stop_x;
-			y = n->stop_y;
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("        Arc to: (%g, %g) %s"),
-					screen_units(x), screen_units(y),
-					screen_units_str());
-
-			x = n->cirseg->cp_x;
-			y = n->cirseg->cp_y;
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("        Center: (%g, %g) %s"),
-					screen_units(x), screen_units(y),
-					screen_units_str());
-
-			x = n->cirseg->width;
-			y = n->cirseg->height;
-			gerbv_transform_coord_for_image(&x, &y, img, prj);
-			g_message (_("        Radius: %g %s"),
-					screen_units(x)/2, screen_units_str());
-
-			g_message (_("        Angle: %g deg"),
-				fabs(n->cirseg->angle1 - n->cirseg->angle2));
-			g_message (_("        Angles: (%g, %g) deg"),
-					n->cirseg->angle1, n->cirseg->angle2);
-			g_message (_("        Direction: %s"),
-					(n->interpolation ==
-					 GERBV_INTERPOLATION_CW_CIRCULAR)?
-						_("CW"): _("CCW"));
-			break;
-
-		default:
-			g_message("       Skipping interpolation: %s",
-				_(gerbv_interpolation_name(n->interpolation)));
-		}
-
-		inter_prev = n->interpolation;
-	}
+static void
+parea_report(gerbv_net_t* net, gerbv_image_t* img, gerbv_project_t* prj) {
+    gerbv_net_t*          n;
+    unsigned int          c = 0;
+    gerbv_interpolation_t inter_prev;
+    double                x, y;
+
+    if (net->interpolation != GERBV_INTERPOLATION_PAREA_START)
+        return;
+
+    /* Count vertices */
+    for (gerbv_net_t* n = net->next; n != NULL; n = n->next) {
+        if (n->interpolation == GERBV_INTERPOLATION_PAREA_END)
+            break;
+        c++;
+    }
+
+    g_message(_("    Number of vertices: %u"), c - 1);
+
+    for (n = net->next, inter_prev = net->interpolation; n != NULL && n->interpolation != GERBV_INTERPOLATION_PAREA_END;
+         n = n->next) {
+
+        switch (n->interpolation) {
+
+            case GERBV_INTERPOLATION_LINEARx1:
+
+                if (inter_prev != n->interpolation) {
+                    x = n->start_x;
+                    y = n->start_y;
+                    gerbv_transform_coord_for_image(&x, &y, img, prj);
+                    g_message(_("    Line from: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+                }
+
+                x = n->stop_x;
+                y = n->stop_y;
+                gerbv_transform_coord_for_image(&x, &y, img, prj);
+                g_message(_("        Line to: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+                break;
+
+            case GERBV_INTERPOLATION_CW_CIRCULAR:
+            case GERBV_INTERPOLATION_CCW_CIRCULAR:
+
+                x = n->start_x;
+                y = n->start_y;
+                gerbv_transform_coord_for_image(&x, &y, img, prj);
+                g_message(_("    Arc from: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+
+                x = n->stop_x;
+                y = n->stop_y;
+                gerbv_transform_coord_for_image(&x, &y, img, prj);
+                g_message(_("        Arc to: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+
+                x = n->cirseg->cp_x;
+                y = n->cirseg->cp_y;
+                gerbv_transform_coord_for_image(&x, &y, img, prj);
+                g_message(_("        Center: (%g, %g) %s"), screen_units(x), screen_units(y), screen_units_str());
+
+                x = n->cirseg->width;
+                y = n->cirseg->height;
+                gerbv_transform_coord_for_image(&x, &y, img, prj);
+                g_message(_("        Radius: %g %s"), screen_units(x) / 2, screen_units_str());
+
+                g_message(_("        Angle: %g deg"), fabs(n->cirseg->angle1 - n->cirseg->angle2));
+                g_message(_("        Angles: (%g, %g) deg"), n->cirseg->angle1, n->cirseg->angle2);
+                g_message(
+                    _("        Direction: %s"),
+                    (n->interpolation == GERBV_INTERPOLATION_CW_CIRCULAR) ? _("CW") : _("CCW")
+                );
+                break;
+
+            default: g_message("       Skipping interpolation: %s", _(gerbv_interpolation_name(n->interpolation)));
+        }
+
+        inter_prev = n->interpolation;
+    }
 }
 
-static void net_layer_file_report(gerbv_net_t *net,
-		gerbv_image_t *img, gerbv_project_t *prj)
-{
-	/* Don't report "no net" to keep log short */
-	if (net->label != NULL)
-		g_message (_("    Net label: %s"), net->label->str);
-
-	/* Don't report "no layer name" to keep log short */
-	if (net->layer->name != NULL)
-		g_message (_("    Layer name: %s"), net->layer->name);
- 
-	/* Search file name in project files array */
-	for (int i = 0; i <= prj->last_loaded; i++) {
-		if (img == prj->file[i]->image)
-			g_message (_("    In file: %s"), prj->file[i]->name);
-	}
+static void
+net_layer_file_report(gerbv_net_t* net, gerbv_image_t* img, gerbv_project_t* prj) {
+    /* Don't report "no net" to keep log short */
+    if (net->label != NULL)
+        g_message(_("    Net label: %s"), net->label->str);
+
+    /* Don't report "no layer name" to keep log short */
+    if (net->layer->name != NULL)
+        g_message(_("    Layer name: %s"), net->layer->name);
+
+    /* Search file name in project files array */
+    for (int i = 0; i <= prj->last_loaded; i++) {
+        if (img == prj->file[i]->image)
+            g_message(_("    In file: %s"), prj->file[i]->name);
+    }
 }
 
 /* Restore report window size and postion */
 static void
-analyze_window_size_restore(GtkWidget *win)
-{
-	GVariant *var;
-	const gint32 *xy;
-	gsize num;
-
-	if (!screen.settings)
-		return;
-
-	var = g_settings_get_value (screen.settings, "analyze-window-size");
-	xy = g_variant_get_fixed_array (var, &num, sizeof (*xy));
-	if (num == 2)
-		gtk_window_set_default_size (GTK_WINDOW (win), xy[0], xy[1]);
-	g_variant_unref (var);
-
-	var = g_settings_get_value (screen.settings, "analyze-window-position");
-	xy = g_variant_get_fixed_array (var, &num, sizeof (*xy));
-	if (num == 2)
-		gtk_window_move (GTK_WINDOW (win), xy[0], xy[1]);
-	g_variant_unref (var);
+analyze_window_size_restore(GtkWidget* win) {
+    GVariant*     var;
+    const gint32* xy;
+    gsize         num;
+
+    if (!screen.settings)
+        return;
+
+    var = g_settings_get_value(screen.settings, "analyze-window-size");
+    xy  = g_variant_get_fixed_array(var, &num, sizeof(*xy));
+    if (num == 2)
+        gtk_window_set_default_size(GTK_WINDOW(win), xy[0], xy[1]);
+    g_variant_unref(var);
+
+    var = g_settings_get_value(screen.settings, "analyze-window-position");
+    xy  = g_variant_get_fixed_array(var, &num, sizeof(*xy));
+    if (num == 2)
+        gtk_window_move(GTK_WINDOW(win), xy[0], xy[1]);
+    g_variant_unref(var);
 }
 
 /* Store report window size and postion */
 static void
-analyze_window_size_store(GtkWidget *win, gpointer user_data)
-{
-	gint32 xy[2];
-	GVariant *var;
-	gboolean is_max;
-
-	if (!screen.settings)
-		return;
-
-	is_max = FALSE != (GDK_WINDOW_STATE_MAXIMIZED &
-			gdk_window_get_state (gtk_widget_get_window (win)));
-	if (is_max)
-		return;
-
-	gtk_window_get_size (GTK_WINDOW (win), (gint *)xy, (gint *)(xy+1));
-	var = g_variant_new_fixed_array (G_VARIANT_TYPE_INT32,
-			xy, 2, sizeof (xy[0]));
-	g_settings_set_value (screen.settings, "analyze-window-size", var);
-
-	gtk_window_get_position (GTK_WINDOW (win),
-			(gint *)xy, (gint *)(xy+1));
-	var = g_variant_new_fixed_array (G_VARIANT_TYPE_INT32,
-			xy, 2, sizeof (xy[0]));
-	g_settings_set_value (screen.settings, "analyze-window-position", var);
+analyze_window_size_store(GtkWidget* win, gpointer user_data) {
+    gint32    xy[2];
+    GVariant* var;
+    gboolean  is_max;
+
+    if (!screen.settings)
+        return;
+
+    is_max = FALSE != (GDK_WINDOW_STATE_MAXIMIZED & gdk_window_get_state(gtk_widget_get_window(win)));
+    if (is_max)
+        return;
+
+    gtk_window_get_size(GTK_WINDOW(win), (gint*)xy, (gint*)(xy + 1));
+    var = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32, xy, 2, sizeof(xy[0]));
+    g_settings_set_value(screen.settings, "analyze-window-size", var);
+
+    gtk_window_get_position(GTK_WINDOW(win), (gint*)xy, (gint*)(xy + 1));
+    var = g_variant_new_fixed_array(G_VARIANT_TYPE_INT32, xy, 2, sizeof(xy[0]));
+    g_settings_set_value(screen.settings, "analyze-window-position", var);
 }
diff --git a/src/callbacks.h b/src/callbacks.h
index bd4dfaf..05786f1 100644
--- a/src/callbacks.h
+++ b/src/callbacks.h
@@ -27,282 +27,187 @@
 */
 
 typedef enum {
-	CALLBACKS_SAVE_PROJECT_AS,
-	CALLBACKS_SAVE_FILE_PS,
-	CALLBACKS_SAVE_FILE_PDF,
-	CALLBACKS_SAVE_FILE_SVG,
-	CALLBACKS_SAVE_FILE_PNG,
-	CALLBACKS_SAVE_FILE_DXF,
-	CALLBACKS_SAVE_FILE_GEDA_PCB,
-	CALLBACKS_SAVE_FILE_RS274X,
-	CALLBACKS_SAVE_FILE_DRILL,
-	CALLBACKS_SAVE_FILE_RS274XM,
-	CALLBACKS_SAVE_FILE_DRILLM,
-	CALLBACKS_SAVE_LAYER_AS,
-	CALLBACKS_SAVE_FILE_IDRILL
-	
+    CALLBACKS_SAVE_PROJECT_AS,
+    CALLBACKS_SAVE_FILE_PS,
+    CALLBACKS_SAVE_FILE_PDF,
+    CALLBACKS_SAVE_FILE_SVG,
+    CALLBACKS_SAVE_FILE_PNG,
+    CALLBACKS_SAVE_FILE_DXF,
+    CALLBACKS_SAVE_FILE_GEDA_PCB,
+    CALLBACKS_SAVE_FILE_RS274X,
+    CALLBACKS_SAVE_FILE_DRILL,
+    CALLBACKS_SAVE_FILE_RS274XM,
+    CALLBACKS_SAVE_FILE_DRILLM,
+    CALLBACKS_SAVE_LAYER_AS,
+    CALLBACKS_SAVE_FILE_IDRILL
+
 } CALLBACKS_SAVE_FILE_TYPE;
 
 typedef enum {
-	LAYER_SELECTED =	-1,
-	LAYER_ALL_ON =		-2,
-	LAYER_ALL_OFF =		-3,
+    LAYER_SELECTED = -1,
+    LAYER_ALL_ON   = -2,
+    LAYER_ALL_OFF  = -3,
 } toggle_layer;
 
-void
-callbacks_new_project_activate                (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_new_project_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void open_project (char *project_filename);
+void open_project(char* project_filename);
 
-void callbacks_open_activate (GtkMenuItem *menuitem, gpointer user_data);
+void callbacks_open_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void open_files (GSList *filenames);
+void open_files(GSList* filenames);
 
-void
-callbacks_revert_activate                     (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_revert_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_save_layer_activate                       (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_save_layer_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_save_project_activate                       (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
-                                        
-void
-callbacks_generic_save_activate                    (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_save_project_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_print_activate                      (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_generic_save_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-gboolean
-callbacks_quit_activate                       (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_print_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_fullscreen_toggled                  (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+gboolean callbacks_quit_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_show_toolbar_toggled                (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_fullscreen_toggled(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_show_sidepane_toggled               (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_show_toolbar_toggled(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_show_selection_on_invisible         (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_show_sidepane_toggled(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_show_cross_on_drill_holes           (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_show_selection_on_invisible(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_toggle_layer_visibility_activate                (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_show_cross_on_drill_holes(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_zoom_in_activate                    (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_toggle_layer_visibility_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_zoom_out_activate                   (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_zoom_in_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_fit_to_window_activate              (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_zoom_out_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_analyze_active_gerbers_activate       (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_fit_to_window_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_analyze_active_drill_activate     (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_analyze_active_gerbers_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_control_gerber_options_activate     (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_analyze_active_drill_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_online_manual_activate              (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_control_gerber_options_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_about_activate                      (GtkMenuItem     *menuitem,
-                                        gpointer         user_data);
+void callbacks_online_manual_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_bugs_activate (GtkMenuItem     *menuitem,
-			 gpointer         user_data);
+void callbacks_about_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-gboolean
-callbacks_window_scroll_event(GtkWidget *widget, GdkEventScroll *event);
+void callbacks_bugs_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-gboolean
-callbacks_window_key_release_event (GtkWidget *widget, GdkEventKey *event);
+gboolean callbacks_window_scroll_event(GtkWidget* widget, GdkEventScroll* event);
 
-gboolean
-callbacks_window_key_press_event (GtkWidget *widget, GdkEventKey *event);
+gboolean callbacks_window_key_release_event(GtkWidget* widget, GdkEventKey* event);
 
-gboolean
-callbacks_drawingarea_button_release_event (GtkWidget *widget, GdkEventButton *event);
+gboolean callbacks_window_key_press_event(GtkWidget* widget, GdkEventKey* event);
 
-gboolean
-callbacks_drawingarea_button_press_event (GtkWidget *widget, GdkEventButton *event);
+gboolean callbacks_drawingarea_button_release_event(GtkWidget* widget, GdkEventButton* event);
 
-gboolean
-callbacks_scrollbar_button_released (GtkWidget *widget, GdkEventButton *event);
+gboolean callbacks_drawingarea_button_press_event(GtkWidget* widget, GdkEventButton* event);
 
-gboolean
-callbacks_scrollbar_button_pressed (GtkWidget *widget, GdkEventButton *event);
+gboolean callbacks_scrollbar_button_released(GtkWidget* widget, GdkEventButton* event);
 
-gboolean
-callbacks_drawingarea_motion_notify_event (GtkWidget *widget, GdkEventMotion *event);
+gboolean callbacks_scrollbar_button_pressed(GtkWidget* widget, GdkEventButton* event);
 
-gboolean
-callbacks_drawingarea_configure_event (GtkWidget *widget, GdkEventConfigure *event);
+gboolean callbacks_drawingarea_motion_notify_event(GtkWidget* widget, GdkEventMotion* event);
 
-gboolean
-callbacks_drawingarea_expose_event (GtkWidget *widget, GdkEventExpose *event);
+gboolean callbacks_drawingarea_configure_event(GtkWidget* widget, GdkEventConfigure* event);
 
-void
-callbacks_handle_log_messages(const gchar *log_domain,
-		      GLogLevelFlags log_level,
-		      const gchar *message, 
-		      gpointer user_data);
+gboolean callbacks_drawingarea_expose_event(GtkWidget* widget, GdkEventExpose* event);
 
-void
-callbacks_clear_messages_button_clicked  (GtkButton *button, gpointer   user_data);
+void callbacks_handle_log_messages(
+    const gchar* log_domain, GLogLevelFlags log_level, const gchar* message, gpointer user_data
+);
 
-void
-callbacks_statusbar_unit_combo_box_changed (GtkComboBox *widget, gpointer user_data);
+void callbacks_clear_messages_button_clicked(GtkButton* button, gpointer user_data);
 
-void
-callbacks_viewmenu_units_changed (GtkCheckMenuItem *widget, gpointer user_data);
+void callbacks_statusbar_unit_combo_box_changed(GtkComboBox* widget, gpointer user_data);
 
-void
-callbacks_viewmenu_rendertype_changed (GtkCheckMenuItem *widget, gpointer user_data);
+void callbacks_viewmenu_units_changed(GtkCheckMenuItem* widget, gpointer user_data);
 
-void
-callbacks_sidepane_render_type_combo_box_changed (GtkComboBox *widget, gpointer user_data);
+void callbacks_viewmenu_rendertype_changed(GtkCheckMenuItem* widget, gpointer user_data);
 
-void
-callbacks_layer_tree_visibility_button_toggled (GtkCellRendererToggle *cell_renderer,
-                                                        gchar *path,
-                                                        gpointer user_data);
-gboolean
-callbacks_drawingarea_leave_notify_event (GtkWidget *widget, GdkEventCrossing *event,
-					gpointer user_data);
-gboolean
-callbacks_drawingarea_enter_notify_event (GtkWidget *widget, GdkEventCrossing *event,
-					gpointer user_data);
-
-void 
-callbacks_update_statusbar(void);
+void callbacks_sidepane_render_type_combo_box_changed(GtkComboBox* widget, gpointer user_data);
 
 void
-callbacks_update_statusbar_measured_distance (gdouble dx, gdouble dy);
+callbacks_layer_tree_visibility_button_toggled(GtkCellRendererToggle* cell_renderer, gchar* path, gpointer user_data);
+gboolean callbacks_drawingarea_leave_notify_event(GtkWidget* widget, GdkEventCrossing* event, gpointer user_data);
+gboolean callbacks_drawingarea_enter_notify_event(GtkWidget* widget, GdkEventCrossing* event, gpointer user_data);
 
-void
-callbacks_update_layer_tree (void);
+void callbacks_update_statusbar(void);
 
-gboolean
-callbacks_layer_tree_key_press (GtkWidget *widget, GdkEventKey *event,
-                                   gpointer user_data);
+void callbacks_update_statusbar_measured_distance(gdouble dx, gdouble dy);
 
-gboolean
-callbacks_layer_tree_button_press (GtkWidget *widget, GdkEventButton *event,
-                                   gpointer user_data);
+void callbacks_update_layer_tree(void);
 
-gboolean
-callbacks_file_drop_event (GtkWidget *widget, GdkDragContext *dc,
-		gint x, gint y, GtkSelectionData *data,
-		guint info, guint time, gpointer p);
+gboolean callbacks_layer_tree_key_press(GtkWidget* widget, GdkEventKey* event, gpointer user_data);
 
-void callbacks_add_layer_button_clicked  (GtkButton *button, gpointer   user_data);
+gboolean callbacks_layer_tree_button_press(GtkWidget* widget, GdkEventButton* event, gpointer user_data);
 
-void callbacks_remove_layer_button_clicked  (GtkButton *button, gpointer   user_data);
+gboolean callbacks_file_drop_event(
+    GtkWidget* widget, GdkDragContext* dc, gint x, gint y, GtkSelectionData* data, guint info, guint time, gpointer p
+);
 
-void callbacks_move_layer_down_menu_activate (GtkMenuItem *menuitem, gpointer user_data);
+void callbacks_add_layer_button_clicked(GtkButton* button, gpointer user_data);
 
-void callbacks_move_layer_down_button_clicked  (GtkButton *button, gpointer   user_data);
+void callbacks_remove_layer_button_clicked(GtkButton* button, gpointer user_data);
 
-void callbacks_move_layer_up_menu_activate (GtkMenuItem *menuitem, gpointer user_data);
+void callbacks_move_layer_down_menu_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void callbacks_move_layer_up_button_clicked  (GtkButton *button, gpointer   user_data);
+void callbacks_move_layer_down_button_clicked(GtkButton* button, gpointer user_data);
 
-void callbacks_layer_tree_row_inserted (GtkTreeModel *tree_model, GtkTreePath  *path,
-                              GtkTreeIter  *oIter, gpointer      user_data);
-void
-callbacks_invert_layer_clicked (GtkButton *button, gpointer   user_data);
+void callbacks_move_layer_up_menu_activate(GtkMenuItem* menuitem, gpointer user_data);
 
-void
-callbacks_display_object_properties_clicked (GtkButton *button, gpointer   user_data);
+void callbacks_move_layer_up_button_clicked(GtkButton* button, gpointer user_data);
 
 void
-callbacks_benchmark_clicked (GtkButton *button, gpointer   user_data);
+callbacks_layer_tree_row_inserted(GtkTreeModel* tree_model, GtkTreePath* path, GtkTreeIter* oIter, gpointer user_data);
+void callbacks_invert_layer_clicked(GtkButton* button, gpointer user_data);
 
-void
-callbacks_edit_object_properties_clicked (GtkButton *button, gpointer   user_data);
+void callbacks_display_object_properties_clicked(GtkButton* button, gpointer user_data);
 
-void
-callbacks_live_edit (GtkWidget *button, gpointer user_data);
+void callbacks_benchmark_clicked(GtkButton* button, gpointer user_data);
 
-void
-callbacks_move_objects_clicked (GtkButton *button, gpointer   user_data);
+void callbacks_edit_object_properties_clicked(GtkButton* button, gpointer user_data);
 
-void
-callbacks_reduce_object_area_clicked (GtkButton *button, gpointer   user_data);
+void callbacks_live_edit(GtkWidget* button, gpointer user_data);
 
-void
-callbacks_delete_objects_clicked (GtkButton *button, gpointer   user_data);
+void callbacks_move_objects_clicked(GtkButton* button, gpointer user_data);
 
-void
-callbacks_align_files_from_sel_clicked (GtkMenuItem *menu_item, gpointer user_data);
+void callbacks_reduce_object_area_clicked(GtkButton* button, gpointer user_data);
 
-void
-callbacks_change_layer_edit_clicked (GtkButton *button, gpointer   user_data);
+void callbacks_delete_objects_clicked(GtkButton* button, gpointer user_data);
 
-void
-callbacks_change_layer_color_clicked  (GtkButton *button, gpointer   user_data);
+void callbacks_align_files_from_sel_clicked(GtkMenuItem* menu_item, gpointer user_data);
 
-void
-callbacks_change_background_color_clicked  (GtkButton *button, gpointer   user_data);
+void callbacks_change_layer_edit_clicked(GtkButton* button, gpointer user_data);
 
-void
-callbacks_reload_layer_clicked  (GtkButton *button, gpointer   user_data);
+void callbacks_change_layer_color_clicked(GtkButton* button, gpointer user_data);
 
-void
-callbacks_change_layer_format_clicked  (GtkButton *button, gpointer   user_data);
+void callbacks_change_background_color_clicked(GtkButton* button, gpointer user_data);
 
-void callbacks_update_scrollbar_limits (void);
+void callbacks_reload_layer_clicked(GtkButton* button, gpointer user_data);
 
-void callbacks_update_scrollbar_positions (void);
+void callbacks_change_layer_format_clicked(GtkButton* button, gpointer user_data);
 
-void callbacks_hadjustment_value_changed (GtkAdjustment *adjustment,
-			gpointer user_data);
+void callbacks_update_scrollbar_limits(void);
 
-void callbacks_vadjustment_value_changed (GtkAdjustment *adjustment,
-			gpointer user_data);
+void callbacks_update_scrollbar_positions(void);
 
-void callbacks_force_expose_event_for_screen (void);
+void callbacks_hadjustment_value_changed(GtkAdjustment* adjustment, gpointer user_data);
 
-void
-callbacks_change_tool  (GtkButton *button, gpointer   user_data);
+void callbacks_vadjustment_value_changed(GtkAdjustment* adjustment, gpointer user_data);
 
-void
-callbacks_switch_to_correct_cursor (void);
+void callbacks_force_expose_event_for_screen(void);
+
+void callbacks_change_tool(GtkButton* button, gpointer user_data);
 
-cairo_surface_t *
-callbacks_create_window_surface (GtkWidget *widget);
+void callbacks_switch_to_correct_cursor(void);
 
-void utf8_snprintf(gchar *dst, gsize byte_len, const gchar *fmt, ...);
+cairo_surface_t* callbacks_create_window_surface(GtkWidget* widget);
 
+void utf8_snprintf(gchar* dst, gsize byte_len, const gchar* fmt, ...);
diff --git a/src/common.h b/src/common.h
index 2d27e2c..2c4d4d0 100644
--- a/src/common.h
+++ b/src/common.h
@@ -33,23 +33,22 @@
 #endif
 
 #ifndef __GNUC__
-#define __FUNCTION1(a,b) a ":" #b
-#define __FUNCTION2(a,b) __FUNCTION1(a,b)
-#define __FUNCTION__ __FUNCTION2(__FILE__,__LINE__)
+#define __FUNCTION1(a, b) a ":" #b
+#define __FUNCTION2(a, b) __FUNCTION1(a, b)
+#define __FUNCTION__ __FUNCTION2(__FILE__, __LINE__)
 #endif
 
 #include "locale.h"
 #include "gettext.h"
 #define _(str) gettext(str)
 #ifdef ENABLE_NLS
-# ifdef gettext_noop
-#  define N_(str) gettext_noop(str)
-# else
-#  define N_(str) (str)
-# endif
+#ifdef gettext_noop
+#define N_(str) gettext_noop(str)
 #else
-# define N_(str) (str)
+#define N_(str) (str)
+#endif
+#else
+#define N_(str) (str)
 #endif
 
 #endif /* __COMMON_H__ */
-
diff --git a/src/csv.c b/src/csv.c
index fb1b9e0..e68d594 100644
--- a/src/csv.c
+++ b/src/csv.c
@@ -2,17 +2,17 @@
  * Copyright (c) 2003 Michael B. Allen <mba2000 ioplex.com>
  *
  * The MIT License
- * 
+ *
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
  * to deal in the Software without restriction, including without limitation
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
+ *
  * The above copyright notice and this permission notice shall be included
  * in all copies or substantial portions of the Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
@@ -39,7 +39,6 @@
 #include <config.h>
 #endif /* HAVE_CONFIG_H */
 
-
 #include <stdlib.h>
 #include <string.h>
 #include <stdio.h>
@@ -56,333 +55,333 @@
 #define ST_COLLECT   2
 #define ST_TAILSPACE 3
 #define ST_END_QUOTE 4
-#define istspace iswspace
-
+#define istspace     iswspace
 
 struct sinput {
-	FILE *in;
-	const char *src;
-	size_t sn;
-	size_t count;
+    FILE*       in;
+    const char* src;
+    size_t      sn;
+    size_t      count;
 };
 
-
 struct winput {
-	const wchar_t *src;
-	size_t sn;
-	size_t count;
+    const wchar_t* src;
+    size_t         sn;
+    size_t         count;
 };
 
-
 static int
-snextch(struct sinput *in)
-{
-	int ch;
-
-	if (in->in) {
-		if ((ch = fgetc(in->in)) == EOF) {
-			if (ferror(in->in)) {
-				GERB_MESSAGE("errno:%d", errno);
-				return -1;
-			}
-			return 0;
-		}
-	} else {
-		if (in->sn == 0) {
-			return 0;
-		}
-		ch = (unsigned char) *(in->src)++;
-		in->sn--;
-	}
-	in->count++;
-
-	return ch;
-}/* snextch */
-
+snextch(struct sinput* in) {
+    int ch;
+
+    if (in->in) {
+        if ((ch = fgetc(in->in)) == EOF) {
+            if (ferror(in->in)) {
+                GERB_MESSAGE("errno:%d", errno);
+                return -1;
+            }
+            return 0;
+        }
+    } else {
+        if (in->sn == 0) {
+            return 0;
+        }
+        ch = (unsigned char)*(in->src)++;
+        in->sn--;
+    }
+    in->count++;
+
+    return ch;
+} /* snextch */
 
 static int
-wnextch(struct winput *in)
-{
-	int ch;
+wnextch(struct winput* in) {
+    int ch;
 
-	if (in->sn == 0) {
-		return 0;
-	}
-	ch = *(in->src)++;
-	in->sn--;
-	in->count++;
+    if (in->sn == 0) {
+        return 0;
+    }
+    ch = *(in->src)++;
+    in->sn--;
+    in->count++;
 
-	return ch;
-}/* wnextch */
+    return ch;
+} /* wnextch */
 
 static int
-csv_parse_str(struct sinput *in, char *buf, size_t bn, char *row[], int rn, int sep, int flags)
-{
-	int trim, quotes, ch, state, r, j, t, inquotes;
-
-	trim = flags & CSV_TRIM;
-	quotes = flags & CSV_QUOTES;
-	state = ST_START;
-	inquotes = 0;
-	ch = r = j = t = 0;
-
-	memset(row, 0, sizeof(char *) * rn);
-
-	while (rn && bn && (ch = snextch(in)) > 0) {
-		switch (state) {
-			case ST_START:
-				if (ch != '\n' && ch != sep && isspace(ch)) {
-					if (!trim) {
-						buf[j++] = ch; bn--;
-						t = j;
-					}
-					break;
-				} else if (quotes && ch == '"') {
-					j = t = 0;
-					state = ST_COLLECT;
-					inquotes = 1;
-					break;
-				}
-				state = ST_COLLECT;
-			case ST_COLLECT:
-				if (inquotes) {
-					if (ch == '"') {
-						state = ST_END_QUOTE;
-						break;
-					}
-				} else if (ch == sep || ch == '\n') {
-					row[r++] = buf; rn--;
-					buf[t] = '\0'; bn--;
-					buf += t + 1;
-					j = t = 0;
-
-					state = ST_START;
-					inquotes = 0;
-					if (ch == '\n') {
-						rn = 0;
-					}
-					break;
-				} else if (quotes && ch == '"') {
-					errno = EILSEQ;
-					GERB_MESSAGE(_("%d: unexpected quote in element"),errno);
-					return -1;
-				}
-				buf[j++] = ch; bn--;
-				if (!trim || isspace(ch) == 0) {
-					t = j;
-				}
-				break;
-			case ST_TAILSPACE:
-			case ST_END_QUOTE:
-				if (ch == sep || ch == '\n') {
-					row[r++] = buf; rn--;
-					buf[j] = '\0'; bn--;
-					buf += j + 1;
-					j = t =  0;
-					state = ST_START;
-					inquotes = 0;
-					if (ch == '\n') {
-						rn = 0;
-					}
-					break;
-				} else if (quotes && ch == '"' && state != ST_TAILSPACE) {
-					buf[j++] = '"';	bn--;		 /* nope, just an escaped quote */
-					t = j;
-					state = ST_COLLECT;
-					break;
-				} else if (isspace(ch)) {
-					state = ST_TAILSPACE;
-					break;
-				}
-				errno = EILSEQ;
-				GERB_MESSAGE(_("%d: bad end quote in element"), errno);
-				return -1;
-		}
-	}
-	if (ch <= 0) {
-		/* treat EOF as EOL, so the last record is accepted even when
-		   \n is not present. Some users parse strings, not lines */
-		if(state == ST_TAILSPACE || state == ST_END_QUOTE
-			|| (state == ST_COLLECT && ! inquotes)) {
-			row[r++] = buf; rn--;
-			buf[j] = '\0'; bn--;
-			buf += j + 1;
-			inquotes = 0;
-			rn = 0;
-		} else {
-	//		AMSG("");
-			return -1;
-		}
-	}
-	if (bn == 0) {
-		errno = E2BIG;
-		GERB_MESSAGE("E2BIG %d ", errno);
-		return -1;
-	}
-	if (rn) {
-		if (inquotes) {
-			errno = EILSEQ;
-			GERB_MESSAGE("EILSEQ %d ", errno);
-			return -1;
-		}
-		row[r] = buf;
-		buf[t] = '\0';
-	}
-	// return error if we can't read the minimum number of fields
-	if (r < 4) {
-		return -1;
-	}
-	return in->count;
-}/* csv_parse_str */
-
+csv_parse_str(struct sinput* in, char* buf, size_t bn, char* row[], int rn, int sep, int flags) {
+    int trim, quotes, ch, state, r, j, t, inquotes;
+
+    trim     = flags & CSV_TRIM;
+    quotes   = flags & CSV_QUOTES;
+    state    = ST_START;
+    inquotes = 0;
+    ch = r = j = t = 0;
+
+    memset(row, 0, sizeof(char*) * rn);
+
+    while (rn && bn && (ch = snextch(in)) > 0) {
+        switch (state) {
+            case ST_START:
+                if (ch != '\n' && ch != sep && isspace(ch)) {
+                    if (!trim) {
+                        buf[j++] = ch;
+                        bn--;
+                        t = j;
+                    }
+                    break;
+                } else if (quotes && ch == '"') {
+                    j = t    = 0;
+                    state    = ST_COLLECT;
+                    inquotes = 1;
+                    break;
+                }
+                state = ST_COLLECT;
+            case ST_COLLECT:
+                if (inquotes) {
+                    if (ch == '"') {
+                        state = ST_END_QUOTE;
+                        break;
+                    }
+                } else if (ch == sep || ch == '\n') {
+                    row[r++] = buf;
+                    rn--;
+                    buf[t] = '\0';
+                    bn--;
+                    buf += t + 1;
+                    j = t = 0;
+
+                    state    = ST_START;
+                    inquotes = 0;
+                    if (ch == '\n') {
+                        rn = 0;
+                    }
+                    break;
+                } else if (quotes && ch == '"') {
+                    errno = EILSEQ;
+                    GERB_MESSAGE(_("%d: unexpected quote in element"), errno);
+                    return -1;
+                }
+                buf[j++] = ch;
+                bn--;
+                if (!trim || isspace(ch) == 0) {
+                    t = j;
+                }
+                break;
+            case ST_TAILSPACE:
+            case ST_END_QUOTE:
+                if (ch == sep || ch == '\n') {
+                    row[r++] = buf;
+                    rn--;
+                    buf[j] = '\0';
+                    bn--;
+                    buf += j + 1;
+                    j = t    = 0;
+                    state    = ST_START;
+                    inquotes = 0;
+                    if (ch == '\n') {
+                        rn = 0;
+                    }
+                    break;
+                } else if (quotes && ch == '"' && state != ST_TAILSPACE) {
+                    buf[j++] = '"';
+                    bn--; /* nope, just an escaped quote */
+                    t     = j;
+                    state = ST_COLLECT;
+                    break;
+                } else if (isspace(ch)) {
+                    state = ST_TAILSPACE;
+                    break;
+                }
+                errno = EILSEQ;
+                GERB_MESSAGE(_("%d: bad end quote in element"), errno);
+                return -1;
+        }
+    }
+    if (ch <= 0) {
+        /* treat EOF as EOL, so the last record is accepted even when
+           \n is not present. Some users parse strings, not lines */
+        if (state == ST_TAILSPACE || state == ST_END_QUOTE || (state == ST_COLLECT && !inquotes)) {
+            row[r++] = buf;
+            rn--;
+            buf[j] = '\0';
+            bn--;
+            buf += j + 1;
+            inquotes = 0;
+            rn       = 0;
+        } else {
+            //		AMSG("");
+            return -1;
+        }
+    }
+    if (bn == 0) {
+        errno = E2BIG;
+        GERB_MESSAGE("E2BIG %d ", errno);
+        return -1;
+    }
+    if (rn) {
+        if (inquotes) {
+            errno = EILSEQ;
+            GERB_MESSAGE("EILSEQ %d ", errno);
+            return -1;
+        }
+        row[r] = buf;
+        buf[t] = '\0';
+    }
+    // return error if we can't read the minimum number of fields
+    if (r < 4) {
+        return -1;
+    }
+    return in->count;
+} /* csv_parse_str */
 
 static int
-csv_parse_wcs(struct winput *in, wchar_t *buf, size_t bn, wchar_t *row[], int rn, wint_t sep, int flags)
-{
-	int trim, quotes, state, r, j, t, inquotes;
-	wint_t ch;
-
-	trim = flags & CSV_TRIM;
-	quotes = flags & CSV_QUOTES;
-	state = ST_START;
-	inquotes = 0;
-	ch = r = j = t = 0;
-
-	memset(row, 0, sizeof(wchar_t *) * rn);
-
-	while (rn && bn && (ch = wnextch(in)) > 0) {
-		switch (state) {
-			case ST_START:
-				if (ch != L'\n' && ch != sep && iswspace(ch)) {
-					if (!trim) {
-						buf[j++] = ch; bn--;
-						t = j;
-					}
-					break;
-				} else if (quotes && ch == L'"') {
-					j = t = 0;
-					state = ST_COLLECT;
-					inquotes = 1;
-					break;
-				}
-				state = ST_COLLECT;
-			case ST_COLLECT:
-				if (inquotes) {
-					if (ch == L'"') {
-						state = ST_END_QUOTE;
-						break;
-					}
-				} else if (ch == sep || ch == L'\n') {
-					row[r++] = buf; rn--;
-					buf[t] = L'\0'; bn--;
-					buf += t + 1;
-					j = t = 0;
-					state = ST_START;
-					inquotes = 0;
-					if (ch == L'\n') {
-						rn = 0;
-					}
-					break;
-				} else if (quotes && ch == L'"') {
-					errno = EILSEQ;
-					GERB_MESSAGE(_("%d: unexpected quote in element"), errno);
-					return -1;
-				}
-				buf[j++] = ch; bn--;
-				if (!trim || iswspace(ch) == 0) {
-					t = j;
-				}
-				break;
-			case ST_TAILSPACE:
-			case ST_END_QUOTE:
-				if (ch == sep || ch == L'\n') {
-					row[r++] = buf; rn--;
-					buf[j] = L'\0'; bn--;
-					buf += j + 1;
-					j = t =  0;
-					state = ST_START;
-					inquotes = 0;
-					if (ch == L'\n') {
-						rn = 0;
-					}
-					break;
-				} else if (quotes && ch == L'"' && state != ST_TAILSPACE) {
-					buf[j++] = L'"'; bn--;		 /* nope, just an escaped quote */
-					t = j;
-					state = ST_COLLECT;
-					break;
-				} else if (iswspace(ch)) {
-					state = ST_TAILSPACE;
-					break;
-				}
-				errno = EILSEQ;
-				GERB_MESSAGE(_("%d: bad end quote in element "), errno);
-				return -1;
-		}
-	}
-	if (ch <= 0) {
-		/* treat EOF as EOL, so the last record is accepted even when
-		   \n is not present. Some users parse strings, not lines */
-		if(state == ST_TAILSPACE || state == ST_END_QUOTE
-			|| (state == ST_COLLECT && ! inquotes)) {
-			row[r++] = buf; rn--;
-			buf[j] = L'\0'; bn--;
-			buf += j + 1;
-			inquotes = 0;
-			rn = 0;
-		} else {
-	//		AMSG("");
-			return -1;
-		}
-	}
-	if (bn == 0) {
-		errno = E2BIG;
-	GERB_MESSAGE("%d", errno);
-		return -1;
-	}
-	if (rn) {
-		if (inquotes) {
-			errno = EILSEQ;
-		GERB_MESSAGE("%d", errno);
-			return -1;
-		}
-		row[r] = buf;
-		buf[t] = L'\0';
-	}
-
-	return in->count;
-}/*csv_row_parse_wcs*/
-
+csv_parse_wcs(struct winput* in, wchar_t* buf, size_t bn, wchar_t* row[], int rn, wint_t sep, int flags) {
+    int    trim, quotes, state, r, j, t, inquotes;
+    wint_t ch;
+
+    trim     = flags & CSV_TRIM;
+    quotes   = flags & CSV_QUOTES;
+    state    = ST_START;
+    inquotes = 0;
+    ch = r = j = t = 0;
+
+    memset(row, 0, sizeof(wchar_t*) * rn);
+
+    while (rn && bn && (ch = wnextch(in)) > 0) {
+        switch (state) {
+            case ST_START:
+                if (ch != L'\n' && ch != sep && iswspace(ch)) {
+                    if (!trim) {
+                        buf[j++] = ch;
+                        bn--;
+                        t = j;
+                    }
+                    break;
+                } else if (quotes && ch == L'"') {
+                    j = t    = 0;
+                    state    = ST_COLLECT;
+                    inquotes = 1;
+                    break;
+                }
+                state = ST_COLLECT;
+            case ST_COLLECT:
+                if (inquotes) {
+                    if (ch == L'"') {
+                        state = ST_END_QUOTE;
+                        break;
+                    }
+                } else if (ch == sep || ch == L'\n') {
+                    row[r++] = buf;
+                    rn--;
+                    buf[t] = L'\0';
+                    bn--;
+                    buf += t + 1;
+                    j = t    = 0;
+                    state    = ST_START;
+                    inquotes = 0;
+                    if (ch == L'\n') {
+                        rn = 0;
+                    }
+                    break;
+                } else if (quotes && ch == L'"') {
+                    errno = EILSEQ;
+                    GERB_MESSAGE(_("%d: unexpected quote in element"), errno);
+                    return -1;
+                }
+                buf[j++] = ch;
+                bn--;
+                if (!trim || iswspace(ch) == 0) {
+                    t = j;
+                }
+                break;
+            case ST_TAILSPACE:
+            case ST_END_QUOTE:
+                if (ch == sep || ch == L'\n') {
+                    row[r++] = buf;
+                    rn--;
+                    buf[j] = L'\0';
+                    bn--;
+                    buf += j + 1;
+                    j = t    = 0;
+                    state    = ST_START;
+                    inquotes = 0;
+                    if (ch == L'\n') {
+                        rn = 0;
+                    }
+                    break;
+                } else if (quotes && ch == L'"' && state != ST_TAILSPACE) {
+                    buf[j++] = L'"';
+                    bn--; /* nope, just an escaped quote */
+                    t     = j;
+                    state = ST_COLLECT;
+                    break;
+                } else if (iswspace(ch)) {
+                    state = ST_TAILSPACE;
+                    break;
+                }
+                errno = EILSEQ;
+                GERB_MESSAGE(_("%d: bad end quote in element "), errno);
+                return -1;
+        }
+    }
+    if (ch <= 0) {
+        /* treat EOF as EOL, so the last record is accepted even when
+           \n is not present. Some users parse strings, not lines */
+        if (state == ST_TAILSPACE || state == ST_END_QUOTE || (state == ST_COLLECT && !inquotes)) {
+            row[r++] = buf;
+            rn--;
+            buf[j] = L'\0';
+            bn--;
+            buf += j + 1;
+            inquotes = 0;
+            rn       = 0;
+        } else {
+            //		AMSG("");
+            return -1;
+        }
+    }
+    if (bn == 0) {
+        errno = E2BIG;
+        GERB_MESSAGE("%d", errno);
+        return -1;
+    }
+    if (rn) {
+        if (inquotes) {
+            errno = EILSEQ;
+            GERB_MESSAGE("%d", errno);
+            return -1;
+        }
+        row[r] = buf;
+        buf[t] = L'\0';
+    }
+
+    return in->count;
+} /*csv_row_parse_wcs*/
 
 int
-csv_row_parse_wcs(const wchar_t *src, size_t sn, wchar_t *buf, size_t bn, wchar_t *row[], int rn, int sep, int trim)
-{
-	struct winput input;
-	input.src = src;
-	input.sn = sn;
-	input.count = 0;
-	return csv_parse_wcs(&input, buf, bn, row, rn, (wint_t)sep, trim);
-}/*csv_row_parse_wcs*/
-
+csv_row_parse_wcs(const wchar_t* src, size_t sn, wchar_t* buf, size_t bn, wchar_t* row[], int rn, int sep, int trim) {
+    struct winput input;
+    input.src   = src;
+    input.sn    = sn;
+    input.count = 0;
+    return csv_parse_wcs(&input, buf, bn, row, rn, (wint_t)sep, trim);
+} /*csv_row_parse_wcs*/
 
 int
-csv_row_parse_str(const char *src, size_t sn, char *buf, size_t bn, char *row[], int rn, int sep, int trim)
-{
-	struct sinput input;
-	input.in = NULL;
-	input.src = src;
-	input.sn = sn;
-	input.count = 0;
-	return csv_parse_str(&input, buf, bn, row, rn, sep, trim);
-}/*csv_row_parse_str*/
-
+csv_row_parse_str(const char* src, size_t sn, char* buf, size_t bn, char* row[], int rn, int sep, int trim) {
+    struct sinput input;
+    input.in    = NULL;
+    input.src   = src;
+    input.sn    = sn;
+    input.count = 0;
+    return csv_parse_str(&input, buf, bn, row, rn, sep, trim);
+} /*csv_row_parse_str*/
 
 int
-csv_row_fread(FILE *in, char *buf, size_t bn, char *row[], int numcols, int sep, int trim)
-{
-	struct sinput input;
-	input.in = in;
-	input.count = 0;
-	return csv_parse_str(&input, buf, bn, row, numcols, sep, trim);
-}/*csv_row_fread*/
-
+csv_row_fread(FILE* in, char* buf, size_t bn, char* row[], int numcols, int sep, int trim) {
+    struct sinput input;
+    input.in    = in;
+    input.count = 0;
+    return csv_parse_str(&input, buf, bn, row, numcols, sep, trim);
+} /*csv_row_fread*/
diff --git a/src/csv.h b/src/csv.h
index e3fabd7..f54fd8f 100644
--- a/src/csv.h
+++ b/src/csv.h
@@ -2,17 +2,17 @@
  * Copyright (c) 2003 Michael B. Allen <mba2000 ioplex.com>
  *
  * The MIT License
- * 
+ *
  * Permission is hereby granted, free of charge, to any person obtaining a
  * copy of this software and associated documentation files (the "Software"),
  * to deal in the Software without restriction, including without limitation
  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  * and/or sell copies of the Software, and to permit persons to whom the
  * Software is furnished to do so, subject to the following conditions:
- * 
+ *
  * The above copyright notice and this permission notice shall be included
  * in all copies or substantial portions of the Software.
- * 
+ *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
@@ -45,7 +45,7 @@
 extern "C" {
 #endif
 
-# define LIBMBA_API extern
+#define LIBMBA_API extern
 
 #include <stdio.h>
 /*#include "text.h"*/
@@ -59,9 +59,11 @@ extern "C" {
 #define CSV_TRIM   0x01
 #define CSV_QUOTES 0x02
 
-LIBMBA_API int csv_row_parse_str(const char *src, size_t sn, char *buf, size_t bn, char *row[], int rn, int sep, int flags);
-LIBMBA_API int csv_row_parse_wcs(const wchar_t *src, size_t sn, wchar_t *buf, size_t bn, wchar_t *row[], int rn, int sep, int flags);
-LIBMBA_API int csv_row_fread(FILE *in, char *buf, size_t bn, char *row[], int numcols, int sep, int flags);
+LIBMBA_API int
+csv_row_parse_str(const char* src, size_t sn, char* buf, size_t bn, char* row[], int rn, int sep, int flags);
+LIBMBA_API int
+csv_row_parse_wcs(const wchar_t* src, size_t sn, wchar_t* buf, size_t bn, wchar_t* row[], int rn, int sep, int flags);
+LIBMBA_API int csv_row_fread(FILE* in, char* buf, size_t bn, char* row[], int numcols, int sep, int flags);
 
 #ifdef __cplusplus
 }
diff --git a/src/csv_defines.h b/src/csv_defines.h
index 67f3b4f..6e40cee 100644
--- a/src/csv_defines.h
+++ b/src/csv_defines.h
@@ -1,22 +1,22 @@
 #ifndef DEFINES_H
 #define DEFINES_H
 /** 	\file csv_defines.h
-	\brief Sets up internal definitions for handling csv-style files
-	\ingroup libgerbv
+    \brief Sets up internal definitions for handling csv-style files
+    \ingroup libgerbv
 */
 
 #if defined(__sparc__)
 
-#define HAVE_ENCDEC 0
-#define HAVE_STRDUP 1
-#define HAVE_STRNLEN 0
-#define HAVE_EXPAT 0
-#define HAVE_MBSTATE 0
-#define HAVE_WCWIDTH 1
-#define HAVE_SNPRINTF 1
+#define HAVE_ENCDEC    0
+#define HAVE_STRDUP    1
+#define HAVE_STRNLEN   0
+#define HAVE_EXPAT     0
+#define HAVE_MBSTATE   0
+#define HAVE_WCWIDTH   1
+#define HAVE_SNPRINTF  1
 #define HAVE_VSNPRINTF 1
-#define HAVE_VARMACRO 1
-#define HAVE_LANGINFO 1
+#define HAVE_VARMACRO  1
+#define HAVE_LANGINFO  1
 
 #elif defined(_WIN32)
 
@@ -24,38 +24,38 @@
 #define HAVE_STRDUP 1
 
 #ifndef HAVE_STRNLEN
-# define HAVE_STRNLEN 0
+#define HAVE_STRNLEN 0
 #endif
 
-#define HAVE_EXPAT 0
+#define HAVE_EXPAT   0
 #define HAVE_MBSTATE 0
 #define HAVE_WCWIDTH 0
 
 #ifndef HAVE_SNPRINTF
-# define HAVE_SNPRINTF 0
+#define HAVE_SNPRINTF 0
 #endif
 
 #define HAVE_VSNPRINTF 0
-#define HAVE_VARMACRO 0
-#define HAVE_LANGINFO 0
+#define HAVE_VARMACRO  0
+#define HAVE_LANGINFO  0
 
 #else
 
-#define HAVE_ENCDEC 0
-#define HAVE_STRDUP 1
-#define HAVE_STRNLEN 1
-#define HAVE_EXPAT 0
-#define HAVE_MBSTATE 1
-#define HAVE_WCWIDTH 1
-#define HAVE_SNPRINTF 1
+#define HAVE_ENCDEC    0
+#define HAVE_STRDUP    1
+#define HAVE_STRNLEN   1
+#define HAVE_EXPAT     0
+#define HAVE_MBSTATE   1
+#define HAVE_WCWIDTH   1
+#define HAVE_SNPRINTF  1
 #define HAVE_VSNPRINTF 0
-#define HAVE_VARMACRO 1
-#define HAVE_LANGINFO 1
+#define HAVE_VARMACRO  1
+#define HAVE_LANGINFO  1
 
 #endif
 
 #ifdef __GNUC__
-#define UNUSED __attribute__ ((unused))
+#define UNUSED __attribute__((unused))
 #else
 #define UNUSED
 #endif
diff --git a/src/draw-gdk.c b/src/draw-gdk.c
index b2fbabd..1e9cba5 100644
--- a/src/draw-gdk.c
+++ b/src/draw-gdk.c
@@ -32,7 +32,7 @@
 
 #include <stdio.h>
 #include <stdlib.h>
-#include <math.h>  /* ceil(), atan2() */
+#include <math.h> /* ceil(), atan2() */
 
 #ifdef HAVE_STRING_H
 #include <string.h>
@@ -46,7 +46,9 @@
 #undef round
 #define round(x) ceil((double)(x))
 
-#define dprintf if(DEBUG) printf
+#define dprintf \
+    if (DEBUG)  \
+    printf
 
 /*
  * If you want to rotate a
@@ -60,42 +62,38 @@
  * angels.
  *
  */
-static GdkPoint 
-rotate_point(GdkPoint point, double angle)
-{
-    double sint, cost;
+static GdkPoint
+rotate_point(GdkPoint point, double angle) {
+    double   sint, cost;
     GdkPoint returned;
-    
+
     if (angle == 0.0)
-	return point;
+        return point;
 
     sint = sin(DEG2RAD(-angle));
     cost = cos(DEG2RAD(-angle));
-    
-    returned.x = lround(cost*point.x - sint*point.y);
-    returned.y = lround(sint*point.x + cost*point.y);
-    
+
+    returned.x = lround(cost * point.x - sint * point.y);
+    returned.y = lround(sint * point.x + cost * point.y);
+
     return returned;
 }
 
-
 /*
  * Aperture macro primitive 1 (Circle)
  */
 static void
-gerbv_gdk_draw_prim1(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s, 
-		     double scale, gint x, gint y)
-{
-    const int exposure_idx = 0;
-    const int diameter_idx = 1;
-    const int x_offset_idx = 2;
-    const int y_offset_idx = 3;
-    const gint full_circle = 23360;
-    GdkGC *local_gc = gdk_gc_new(pixmap);
-    gint dia    = round(fabs(s->parameter[diameter_idx] * scale));
-    gint real_x = x - dia / 2;
-    gint real_y = y - dia / 2;
-    GdkColor color;
+gerbv_gdk_draw_prim1(GdkPixmap* pixmap, GdkGC* gc, gerbv_simplified_amacro_t* s, double scale, gint x, gint y) {
+    const int  exposure_idx = 0;
+    const int  diameter_idx = 1;
+    const int  x_offset_idx = 2;
+    const int  y_offset_idx = 3;
+    const gint full_circle  = 23360;
+    GdkGC*     local_gc     = gdk_gc_new(pixmap);
+    gint       dia          = round(fabs(s->parameter[diameter_idx] * scale));
+    gint       real_x       = x - dia / 2;
+    gint       real_y       = y - dia / 2;
+    GdkColor   color;
 
     gdk_gc_copy(local_gc, gc);
 
@@ -104,79 +102,73 @@ gerbv_gdk_draw_prim1(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s,
 
     /* Exposure */
     if (s->parameter[exposure_idx] == 0.0) {
-	color.pixel = 0;
-	gdk_gc_set_foreground(local_gc, &color);
+        color.pixel = 0;
+        gdk_gc_set_foreground(local_gc, &color);
     }
 
-    gdk_gc_set_line_attributes(local_gc, 
-			       1, /* outline always 1 pixels */
-			       GDK_LINE_SOLID, 
-			       GDK_CAP_BUTT, 
-			       GDK_JOIN_MITER);
+    gdk_gc_set_line_attributes(
+        local_gc, 1, /* outline always 1 pixels */
+        GDK_LINE_SOLID, GDK_CAP_BUTT, GDK_JOIN_MITER
+    );
 
-    /* 
-     * A filled circle 
+    /*
+     * A filled circle
      */
-    gdk_draw_arc(pixmap, local_gc, 1, real_x, real_y, dia, dia, 
-		 0, full_circle);
+    gdk_draw_arc(pixmap, local_gc, 1, real_x, real_y, dia, dia, 0, full_circle);
 
     gdk_gc_unref(local_gc);
 
     return;
 } /* gerbv_gdk_draw_prim1 */
 
-
 /*
  * Aperture macro primitive 4 (outline)
  * - Start point is not included in number of points.
  * - Outline is 1 pixel.
  */
 static void
-gerbv_gdk_draw_prim4(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s, 
-		     double scale, gint x, gint y)
-{
-    const int exposure_idx = 0;
+gerbv_gdk_draw_prim4(GdkPixmap* pixmap, GdkGC* gc, gerbv_simplified_amacro_t* s, double scale, gint x, gint y) {
+    const int exposure_idx   = 0;
     const int nuf_points_idx = 1;
-    const int first_x_idx = 2;
-    const int first_y_idx = 3;
-    const int rotext_idx = 4;
-    GdkGC *local_gc = gdk_gc_new(pixmap);
-    int nuf_points, point;
-    double rotation;
-    GdkPoint *points;
-    GdkColor color;
+    const int first_x_idx    = 2;
+    const int first_y_idx    = 3;
+    const int rotext_idx     = 4;
+    GdkGC*    local_gc       = gdk_gc_new(pixmap);
+    int       nuf_points, point;
+    double    rotation;
+    GdkPoint* points;
+    GdkColor  color;
 
     /* Include start point */
     nuf_points = (int)s->parameter[nuf_points_idx] + 1;
-    points = g_new(GdkPoint, nuf_points);
+    points     = g_new(GdkPoint, nuf_points);
     if (!points) {
-	g_free(points);
-	return;
+        g_free(points);
+        return;
     }
 
     rotation = s->parameter[(nuf_points - 1) * 2 + rotext_idx];
     for (point = 0; point < nuf_points; point++) {
-	points[point].x = (int)round(scale * s->parameter[point * 2 + first_x_idx]);
-	points[point].y = -(int)round(scale * s->parameter[point * 2 + first_y_idx]);
-	if (rotation != 0.0)
-	    points[point] = rotate_point(points[point], rotation);
-	points[point].x += x;
-	points[point].y += y;
+        points[point].x = (int)round(scale * s->parameter[point * 2 + first_x_idx]);
+        points[point].y = -(int)round(scale * s->parameter[point * 2 + first_y_idx]);
+        if (rotation != 0.0)
+            points[point] = rotate_point(points[point], rotation);
+        points[point].x += x;
+        points[point].y += y;
     }
 
     gdk_gc_copy(local_gc, gc);
 
     /* Exposure */
     if (s->parameter[exposure_idx] == 0.0) {
-	color.pixel = 0;
-	gdk_gc_set_foreground(local_gc, &color);
+        color.pixel = 0;
+        gdk_gc_set_foreground(local_gc, &color);
     }
 
-    gdk_gc_set_line_attributes(local_gc, 
-			       1, /* outline always 1 pixels */
-			       GDK_LINE_SOLID, 
-			       GDK_CAP_BUTT, 
-			       GDK_JOIN_MITER);
+    gdk_gc_set_line_attributes(
+        local_gc, 1, /* outline always 1 pixels */
+        GDK_LINE_SOLID, GDK_CAP_BUTT, GDK_JOIN_MITER
+    );
     gdk_draw_polygon(pixmap, local_gc, 1, points, nuf_points);
 
     g_free(points);
@@ -186,48 +178,45 @@ gerbv_gdk_draw_prim4(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s,
     return;
 } /* gerbv_gdk_draw_prim4 */
 
-
 /*
  * Aperture macro primitive 5 (polygon)
  */
 static void
-gerbv_gdk_draw_prim5(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s, 
-		     double scale, gint x, gint y)
-{
-    const int exposure_idx = 0;
+gerbv_gdk_draw_prim5(GdkPixmap* pixmap, GdkGC* gc, gerbv_simplified_amacro_t* s, double scale, gint x, gint y) {
+    const int exposure_idx     = 0;
     const int nuf_vertices_idx = 1;
-    const int center_x_idx = 2;
-    const int center_y_idx = 3;
-    const int diameter_idx = 4;
-    const int rotation_idx = 5;
-    int nuf_vertices, i;
-    double vertex, tick, rotation, radius;
-    GdkPoint *points;
-    GdkGC *local_gc = gdk_gc_new(pixmap);
-    GdkColor color;
+    const int center_x_idx     = 2;
+    const int center_y_idx     = 3;
+    const int diameter_idx     = 4;
+    const int rotation_idx     = 5;
+    int       nuf_vertices, i;
+    double    vertex, tick, rotation, radius;
+    GdkPoint* points;
+    GdkGC*    local_gc = gdk_gc_new(pixmap);
+    GdkColor  color;
 
     nuf_vertices = (int)s->parameter[nuf_vertices_idx];
-    points = g_new(GdkPoint, nuf_vertices);
+    points       = g_new(GdkPoint, nuf_vertices);
     if (!points) {
-	g_free(points);
-	return;
+        g_free(points);
+        return;
     }
 
     gdk_gc_copy(local_gc, gc);
 
     /* Exposure */
     if (s->parameter[exposure_idx] == 0.0) {
-	color.pixel = 0;
-	gdk_gc_set_foreground(local_gc, &color);
+        color.pixel = 0;
+        gdk_gc_set_foreground(local_gc, &color);
     }
 
-    tick = 2 * M_PI / (double)nuf_vertices;
+    tick     = 2 * M_PI / (double)nuf_vertices;
     rotation = DEG2RAD(-s->parameter[rotation_idx]);
-    radius = s->parameter[diameter_idx] / 2.0;
+    radius   = s->parameter[diameter_idx] / 2.0;
     for (i = 0; i < nuf_vertices; i++) {
-	vertex =  tick * (double)i + rotation;
-	points[i].x = (int)round(scale * (radius * cos(vertex) + s->parameter[center_x_idx])) + x;
-	points[i].y = (int)round(scale * (radius * sin(vertex) - s->parameter[center_y_idx])) + y;
+        vertex      = tick * (double)i + rotation;
+        points[i].x = (int)round(scale * (radius * cos(vertex) + s->parameter[center_x_idx])) + x;
+        points[i].y = (int)round(scale * (radius * sin(vertex) - s->parameter[center_y_idx])) + y;
     }
 
     gdk_draw_polygon(pixmap, local_gc, 1, points, nuf_vertices);
@@ -238,7 +227,6 @@ gerbv_gdk_draw_prim5(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s,
     return;
 } /* gerbv_gdk_draw_prim5 */
 
-
 /*
  * Doesn't handle and explicit x,y yet
  * Questions:
@@ -246,47 +234,42 @@ gerbv_gdk_draw_prim5(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s,
  *    center of line of circle?
  */
 static void
-gerbv_gdk_draw_prim6(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s, 
-		 double scale, gint x, gint y)
-{
-    const int outside_dia_idx = 2;
+gerbv_gdk_draw_prim6(GdkPixmap* pixmap, GdkGC* gc, gerbv_simplified_amacro_t* s, double scale, gint x, gint y) {
+    const int outside_dia_idx  = 2;
     const int ci_thickness_idx = 3;
-    const int gap_idx = 4;
-    const int nuf_circles_idx = 5;
+    const int gap_idx          = 4;
+    const int nuf_circles_idx  = 5;
     const int ch_thickness_idx = 6;
-    const int ch_length_idx = 7;
-    const int rotation_idx = 8;
-    GdkGC *local_gc = gdk_gc_new(pixmap);
-    double real_dia;
-    double real_dia_diff;
-    int circle;
-    GdkPoint crosshair[4];
-    int point;
+    const int ch_length_idx    = 7;
+    const int rotation_idx     = 8;
+    GdkGC*    local_gc         = gdk_gc_new(pixmap);
+    double    real_dia;
+    double    real_dia_diff;
+    int       circle;
+    GdkPoint  crosshair[4];
+    int       point;
 
     gdk_gc_copy(local_gc, gc);
-    gdk_gc_set_line_attributes(local_gc, 
-			       (int)round(scale * s->parameter[ci_thickness_idx]),
-			       GDK_LINE_SOLID, 
-			       GDK_CAP_BUTT, 
-			       GDK_JOIN_MITER);
-
-    real_dia = s->parameter[outside_dia_idx] -  s->parameter[ci_thickness_idx] / 2.0;
-    real_dia_diff = 2*(s->parameter[gap_idx] + s->parameter[ci_thickness_idx]);
-
-    for (circle = 0; circle != (int)s->parameter[nuf_circles_idx];  circle++) {
-	/* 
-	 * Non filled circle 
-	 */
-	const gint full_circle = 23360;
-	gint dia = (real_dia - real_dia_diff * circle) * scale;
-	if (dia >= 0){
-		gdk_draw_arc(pixmap, local_gc, 0, x - dia / 2, y - dia / 2, 
-				dia, dia, 0, full_circle);
-	}
+    gdk_gc_set_line_attributes(
+        local_gc, (int)round(scale * s->parameter[ci_thickness_idx]), GDK_LINE_SOLID, GDK_CAP_BUTT, GDK_JOIN_MITER
+    );
+
+    real_dia      = s->parameter[outside_dia_idx] - s->parameter[ci_thickness_idx] / 2.0;
+    real_dia_diff = 2 * (s->parameter[gap_idx] + s->parameter[ci_thickness_idx]);
+
+    for (circle = 0; circle != (int)s->parameter[nuf_circles_idx]; circle++) {
+        /*
+         * Non filled circle
+         */
+        const gint full_circle = 23360;
+        gint       dia         = (real_dia - real_dia_diff * circle) * scale;
+        if (dia >= 0) {
+            gdk_draw_arc(pixmap, local_gc, 0, x - dia / 2, y - dia / 2, dia, dia, 0, full_circle);
+        }
     }
 
     /*
-     * Cross Hair 
+     * Cross Hair
      */
     memset(crosshair, 0, sizeof(GdkPoint) * 4);
     crosshair[0].x = (int)((s->parameter[ch_length_idx] / 2.0) * scale);
@@ -298,135 +281,112 @@ gerbv_gdk_draw_prim6(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s,
     /*crosshair[3].x = 0;*/
     crosshair[3].y = -crosshair[0].x;
 
-    gdk_gc_set_line_attributes(local_gc, 
-			       (int)round(scale * s->parameter[ch_thickness_idx]),
-			       GDK_LINE_SOLID, 
-			       GDK_CAP_BUTT, 
-			       GDK_JOIN_MITER);
+    gdk_gc_set_line_attributes(
+        local_gc, (int)round(scale * s->parameter[ch_thickness_idx]), GDK_LINE_SOLID, GDK_CAP_BUTT, GDK_JOIN_MITER
+    );
 
     for (point = 0; point < 4; point++) {
-	crosshair[point] = rotate_point(crosshair[point], 
-					s->parameter[rotation_idx]);
-	crosshair[point].x += x;
-	crosshair[point].y += y;
+        crosshair[point] = rotate_point(crosshair[point], s->parameter[rotation_idx]);
+        crosshair[point].x += x;
+        crosshair[point].y += y;
     }
-    gdk_draw_line(pixmap, local_gc, 
-		  crosshair[0].x, crosshair[0].y, 
-		  crosshair[1].x, crosshair[1].y);
-    gdk_draw_line(pixmap, local_gc, 
-		  crosshair[2].x, crosshair[2].y, 
-		  crosshair[3].x, crosshair[3].y);
+    gdk_draw_line(pixmap, local_gc, crosshair[0].x, crosshair[0].y, crosshair[1].x, crosshair[1].y);
+    gdk_draw_line(pixmap, local_gc, crosshair[2].x, crosshair[2].y, crosshair[3].x, crosshair[3].y);
 
     gdk_gc_unref(local_gc);
 
     return;
 } /* gerbv_gdk_draw_prim6 */
 
-
 static void
-gerbv_gdk_draw_prim7(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s, 
-		 double scale, gint x, gint y)
-{
-    const int outside_dia_idx = 2;
-    const int inside_dia_idx = 3;
-    const int ch_thickness_idx = 4;
-    const int rotation_idx = 5;
-    const gint full_circle = 23360;
+gerbv_gdk_draw_prim7(GdkPixmap* pixmap, GdkGC* gc, gerbv_simplified_amacro_t* s, double scale, gint x, gint y) {
+    const int   outside_dia_idx  = 2;
+    const int   inside_dia_idx   = 3;
+    const int   ch_thickness_idx = 4;
+    const int   rotation_idx     = 5;
+    const gint  full_circle      = 23360;
     GdkGCValues gc_val;
-    int diameter, i;
-    GdkGC *local_gc = gdk_gc_new(pixmap);
-    GdkPoint point[4];
-    double ci_thickness = (s->parameter[outside_dia_idx] - 
-			   s->parameter[inside_dia_idx]) / 2.0;
+    int         diameter, i;
+    GdkGC*      local_gc = gdk_gc_new(pixmap);
+    GdkPoint    point[4];
+    double      ci_thickness = (s->parameter[outside_dia_idx] - s->parameter[inside_dia_idx]) / 2.0;
 
     gdk_gc_copy(local_gc, gc);
-    gdk_gc_set_line_attributes(local_gc, 
-			       (int)round(scale * ci_thickness),
-			       GDK_LINE_SOLID, 
-			       GDK_CAP_BUTT, 
-			       GDK_JOIN_MITER);
-
-    /* 
-     * Non filled circle 
+    gdk_gc_set_line_attributes(
+        local_gc, (int)round(scale * ci_thickness), GDK_LINE_SOLID, GDK_CAP_BUTT, GDK_JOIN_MITER
+    );
+
+    /*
+     * Non filled circle
      */
     diameter = (s->parameter[inside_dia_idx] + ci_thickness) * scale;
-    gdk_draw_arc(pixmap, local_gc, 0, x - diameter / 2, y - diameter / 2, 
-		 diameter, diameter, 0, full_circle);
+    gdk_draw_arc(pixmap, local_gc, 0, x - diameter / 2, y - diameter / 2, diameter, diameter, 0, full_circle);
 
     /*
      * Cross hair
-     */ 
-    /* Calculate the end points of the crosshair */    
+     */
+    /* Calculate the end points of the crosshair */
     /* GDK doesn't always remove all of the circle (round of error probably)
-       I extend the crosshair line with 2 (one pixel in each end) to make 
+       I extend the crosshair line with 2 (one pixel in each end) to make
        sure all of the circle is removed with the crosshair */
     for (i = 0; i < 4; i++) {
-	point[i].x = round((s->parameter[outside_dia_idx] / 2.0) * scale) + 2;
-	point[i].y = 0;
-	point[i] = rotate_point(point[i], s->parameter[rotation_idx] + 90 * i);
-	point[i].x += x;
-	point[i].y += y;
+        point[i].x = round((s->parameter[outside_dia_idx] / 2.0) * scale) + 2;
+        point[i].y = 0;
+        point[i]   = rotate_point(point[i], s->parameter[rotation_idx] + 90 * i);
+        point[i].x += x;
+        point[i].y += y;
     }
 
-    gdk_gc_set_line_attributes(local_gc, 
-			       (int)round(scale * s->parameter[ch_thickness_idx]),
-			       GDK_LINE_SOLID, 
-			       GDK_CAP_BUTT, 
-			       GDK_JOIN_MITER);
+    gdk_gc_set_line_attributes(
+        local_gc, (int)round(scale * s->parameter[ch_thickness_idx]), GDK_LINE_SOLID, GDK_CAP_BUTT, GDK_JOIN_MITER
+    );
 
     /* The cross hair should "cut out" parts of the circle, hence inverse */
     gdk_gc_get_values(local_gc, &gc_val);
     if (gc_val.foreground.pixel == 1)
-	gc_val.foreground.pixel = 0;
+        gc_val.foreground.pixel = 0;
     else
-	gc_val.foreground.pixel = 1;
+        gc_val.foreground.pixel = 1;
     gdk_gc_set_foreground(local_gc, &(gc_val.foreground));
 
     /* Draw the actual cross */
-    gdk_draw_line(pixmap, local_gc, 
-		  point[0].x, point[0].y, point[2].x, point[2].y);
-    gdk_draw_line(pixmap, local_gc,
-		  point[1].x, point[1].y, point[3].x, point[3].y);
+    gdk_draw_line(pixmap, local_gc, point[0].x, point[0].y, point[2].x, point[2].y);
+    gdk_draw_line(pixmap, local_gc, point[1].x, point[1].y, point[3].x, point[3].y);
 
     gdk_gc_unref(local_gc);
 
     return;
 } /* gerbv_gdk_draw_prim7 */
 
-
 /*
  * Doesn't handle and explicit x,y yet
  */
 static void
-gerbv_gdk_draw_prim20(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s, 
-		  double scale, gint x, gint y)
-{
-    const int exposure_idx = 0;
+gerbv_gdk_draw_prim20(GdkPixmap* pixmap, GdkGC* gc, gerbv_simplified_amacro_t* s, double scale, gint x, gint y) {
+    const int exposure_idx  = 0;
     const int linewidth_idx = 1;
-    const int start_x_idx = 2;
-    const int start_y_idx = 3;
-    const int end_x_idx = 4;
-    const int end_y_idx = 5;
-    const int rotation_idx = 6;
-    const int nuf_points = 2;
-    GdkGC *local_gc = gdk_gc_new(pixmap);
-    GdkPoint points[nuf_points];
-    GdkColor color;
-    int i;
+    const int start_x_idx   = 2;
+    const int start_y_idx   = 3;
+    const int end_x_idx     = 4;
+    const int end_y_idx     = 5;
+    const int rotation_idx  = 6;
+    const int nuf_points    = 2;
+    GdkGC*    local_gc      = gdk_gc_new(pixmap);
+    GdkPoint  points[nuf_points];
+    GdkColor  color;
+    int       i;
 
     gdk_gc_copy(local_gc, gc);
 
     /* Exposure */
     if (s->parameter[exposure_idx] == 0.0) {
-	color.pixel = 0;
-	gdk_gc_set_foreground(local_gc, &color);
+        color.pixel = 0;
+        gdk_gc_set_foreground(local_gc, &color);
     }
 
-    gdk_gc_set_line_attributes(local_gc, 
-			       (int)round(scale * s->parameter[linewidth_idx]),
-			       GDK_LINE_SOLID, 
-			       GDK_CAP_BUTT, 
-			       GDK_JOIN_MITER);
+    gdk_gc_set_line_attributes(
+        local_gc, (int)round(scale * s->parameter[linewidth_idx]), GDK_LINE_SOLID, GDK_CAP_BUTT, GDK_JOIN_MITER
+    );
 
     points[0].x = (s->parameter[start_x_idx] * scale);
     points[0].y = (s->parameter[start_y_idx] * scale);
@@ -434,40 +394,35 @@ gerbv_gdk_draw_prim20(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s
     points[1].y = (s->parameter[end_y_idx] * scale);
 
     for (i = 0; i < nuf_points; i++) {
-	points[i] = rotate_point(points[i], -s->parameter[rotation_idx]);
-	points[i].x = x + points[i].x;
-	points[i].y = y - points[i].y;
+        points[i]   = rotate_point(points[i], -s->parameter[rotation_idx]);
+        points[i].x = x + points[i].x;
+        points[i].y = y - points[i].y;
     }
 
-    gdk_draw_line(pixmap, local_gc, 
-		  points[0].x, points[0].y, 
-		  points[1].x, points[1].y);
-    
+    gdk_draw_line(pixmap, local_gc, points[0].x, points[0].y, points[1].x, points[1].y);
+
     gdk_gc_unref(local_gc);
 
     return;
 } /* gerbv_gdk_draw_prim20 */
 
-
 static void
-gerbv_gdk_draw_prim21(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s, 
-		  double scale, gint x, gint y)
-{
+gerbv_gdk_draw_prim21(GdkPixmap* pixmap, GdkGC* gc, gerbv_simplified_amacro_t* s, double scale, gint x, gint y) {
     const int exposure_idx = 0;
-    const int width_idx = 1;
-    const int height_idx = 2;
-    const int exp_x_idx = 3;
-    const int exp_y_idx = 4;
+    const int width_idx    = 1;
+    const int height_idx   = 2;
+    const int exp_x_idx    = 3;
+    const int exp_y_idx    = 4;
     const int rotation_idx = 5;
-    const int nuf_points = 4;
-    GdkPoint points[nuf_points];
-    GdkColor color;
-    GdkGC *local_gc = gdk_gc_new(pixmap);
-    int half_width, half_height;
-    int i;
+    const int nuf_points   = 4;
+    GdkPoint  points[nuf_points];
+    GdkColor  color;
+    GdkGC*    local_gc = gdk_gc_new(pixmap);
+    int       half_width, half_height;
+    int       i;
 
-    half_width = (int)round(s->parameter[width_idx] * scale / 2.0);
-    half_height =(int)round(s->parameter[height_idx] * scale / 2.0);
+    half_width  = (int)round(s->parameter[width_idx] * scale / 2.0);
+    half_height = (int)round(s->parameter[height_idx] * scale / 2.0);
 
     points[0].x = half_width;
     points[0].y = half_height;
@@ -482,19 +437,19 @@ gerbv_gdk_draw_prim21(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s
     points[3].y = half_height;
 
     for (i = 0; i < nuf_points; i++) {
-	points[i].x += (int)(s->parameter[exp_x_idx] * scale);
-	points[i].y -= (int)(s->parameter[exp_y_idx] * scale);
-	points[i] = rotate_point(points[i], s->parameter[rotation_idx]);
-	points[i].x += x;
-	points[i].y += y;
+        points[i].x += (int)(s->parameter[exp_x_idx] * scale);
+        points[i].y -= (int)(s->parameter[exp_y_idx] * scale);
+        points[i] = rotate_point(points[i], s->parameter[rotation_idx]);
+        points[i].x += x;
+        points[i].y += y;
     }
 
     gdk_gc_copy(local_gc, gc);
 
     /* Exposure */
     if (s->parameter[exposure_idx] == 0.0) {
-	color.pixel = 0;
-	gdk_gc_set_foreground(local_gc, &color);
+        color.pixel = 0;
+        gdk_gc_set_foreground(local_gc, &color);
     }
 
     gdk_draw_polygon(pixmap, local_gc, 1, points, nuf_points);
@@ -504,54 +459,47 @@ gerbv_gdk_draw_prim21(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s
     return;
 } /* gerbv_gdk_draw_prim21 */
 
-
 /*
  * Doesn't handle explicit x,y yet
  */
 static void
-gerbv_gdk_draw_prim22(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s, 
-		  double scale, gint x, gint y)
-{
-    const int exposure_idx = 0;
-    const int width_idx = 1;
-    const int height_idx = 2;
+gerbv_gdk_draw_prim22(GdkPixmap* pixmap, GdkGC* gc, gerbv_simplified_amacro_t* s, double scale, gint x, gint y) {
+    const int exposure_idx     = 0;
+    const int width_idx        = 1;
+    const int height_idx       = 2;
     const int x_lower_left_idx = 3;
     const int y_lower_left_idx = 4;
-    const int rotation_idx = 5;
-    const int nuf_points = 4;
-    GdkPoint points[nuf_points];
-    GdkGC *local_gc = gdk_gc_new(pixmap);
-    GdkColor color;
-    int i;
+    const int rotation_idx     = 5;
+    const int nuf_points       = 4;
+    GdkPoint  points[nuf_points];
+    GdkGC*    local_gc = gdk_gc_new(pixmap);
+    GdkColor  color;
+    int       i;
 
     points[0].x = (int)round(s->parameter[x_lower_left_idx] * scale);
     points[0].y = (int)round(s->parameter[y_lower_left_idx] * scale);
 
-    points[1].x = (int)round((s->parameter[x_lower_left_idx] + s->parameter[width_idx])
-			     * scale);
+    points[1].x = (int)round((s->parameter[x_lower_left_idx] + s->parameter[width_idx]) * scale);
     points[1].y = (int)round(s->parameter[y_lower_left_idx] * scale);
 
-    points[2].x = (int)round((s->parameter[x_lower_left_idx]  + s->parameter[width_idx])
-			     * scale);
-    points[2].y = (int)round((s->parameter[y_lower_left_idx]  + s->parameter[height_idx])
-			     * scale);
+    points[2].x = (int)round((s->parameter[x_lower_left_idx] + s->parameter[width_idx]) * scale);
+    points[2].y = (int)round((s->parameter[y_lower_left_idx] + s->parameter[height_idx]) * scale);
 
     points[3].x = (int)round(s->parameter[x_lower_left_idx] * scale);
-    points[3].y = (int)round((s->parameter[y_lower_left_idx] + s->parameter[height_idx])
-			     * scale);
+    points[3].y = (int)round((s->parameter[y_lower_left_idx] + s->parameter[height_idx]) * scale);
 
     for (i = 0; i < nuf_points; i++) {
-	points[i] = rotate_point(points[i], -s->parameter[rotation_idx]);
-	points[i].x = x + points[i].x;
-	points[i].y = y - points[i].y;
+        points[i]   = rotate_point(points[i], -s->parameter[rotation_idx]);
+        points[i].x = x + points[i].x;
+        points[i].y = y - points[i].y;
     }
 
     gdk_gc_copy(local_gc, gc);
 
     /* Exposure */
     if (s->parameter[exposure_idx] == 0.0) {
-	color.pixel = 0;
-	gdk_gc_set_foreground(local_gc, &color);
+        color.pixel = 0;
+        gdk_gc_set_foreground(local_gc, &color);
     }
 
     gdk_draw_polygon(pixmap, local_gc, 1, points, nuf_points);
@@ -562,730 +510,695 @@ gerbv_gdk_draw_prim22(GdkPixmap *pixmap, GdkGC *gc, gerbv_simplified_amacro_t *s
 } /* gerbv_gdk_draw_prim22 */
 
 /* Keep this array in order and without holes */
-static void (*dgk_draw_amacro_funcs[])(GdkPixmap *, GdkGC *, gerbv_simplified_amacro_t *, 
-		     double, gint, gint) = {
-	[GERBV_APTYPE_MACRO_CIRCLE]  = &gerbv_gdk_draw_prim1,
-	[GERBV_APTYPE_MACRO_OUTLINE] = &gerbv_gdk_draw_prim4,
-	[GERBV_APTYPE_MACRO_POLYGON] = &gerbv_gdk_draw_prim5,
-	[GERBV_APTYPE_MACRO_MOIRE]   = &gerbv_gdk_draw_prim6,
-	[GERBV_APTYPE_MACRO_THERMAL] = &gerbv_gdk_draw_prim7,
-	[GERBV_APTYPE_MACRO_LINE20]  = &gerbv_gdk_draw_prim20,
-	[GERBV_APTYPE_MACRO_LINE21]  = &gerbv_gdk_draw_prim21,
-	[GERBV_APTYPE_MACRO_LINE22]  = &gerbv_gdk_draw_prim22,
+static void (*dgk_draw_amacro_funcs[])(GdkPixmap*, GdkGC*, gerbv_simplified_amacro_t*, double, gint, gint) = {
+    [GERBV_APTYPE_MACRO_CIRCLE] = &gerbv_gdk_draw_prim1,  [GERBV_APTYPE_MACRO_OUTLINE] = &gerbv_gdk_draw_prim4,
+    [GERBV_APTYPE_MACRO_POLYGON] = &gerbv_gdk_draw_prim5, [GERBV_APTYPE_MACRO_MOIRE] = &gerbv_gdk_draw_prim6,
+    [GERBV_APTYPE_MACRO_THERMAL] = &gerbv_gdk_draw_prim7, [GERBV_APTYPE_MACRO_LINE20] = &gerbv_gdk_draw_prim20,
+    [GERBV_APTYPE_MACRO_LINE21] = &gerbv_gdk_draw_prim21, [GERBV_APTYPE_MACRO_LINE22] = &gerbv_gdk_draw_prim22,
 };
 
-static inline void 
-gerbv_gdk_draw_amacro(GdkPixmap *pixmap, GdkGC *gc, 
-		      gerbv_simplified_amacro_t *s, double scale, 
-		      gint x, gint y)
-{
-	dprintf("%s(): drawing simplified aperture macros:\n", __func__);
-
-	while (s != NULL) {
-		if (s->type >= GERBV_APTYPE_MACRO_CIRCLE
-		 && s->type <= GERBV_APTYPE_MACRO_LINE22) {
-			dgk_draw_amacro_funcs[s->type](pixmap, gc,
-					s, scale, x, y);
-			dprintf("  %s\n", gerbv_aperture_type_name(s->type));
-		} else {
-			GERB_FATAL_ERROR(
-				_("Unknown simplified aperture macro type %d"),
-				s->type);
-		}
-
-		s = s->next;
-	}
-} /* gerbv_gdk_draw_amacro */
+static inline void
+gerbv_gdk_draw_amacro(GdkPixmap* pixmap, GdkGC* gc, gerbv_simplified_amacro_t* s, double scale, gint x, gint y) {
+    dprintf("%s(): drawing simplified aperture macros:\n", __func__);
+
+    while (s != NULL) {
+        if (s->type >= GERBV_APTYPE_MACRO_CIRCLE && s->type <= GERBV_APTYPE_MACRO_LINE22) {
+            dgk_draw_amacro_funcs[s->type](pixmap, gc, s, scale, x, y);
+            dprintf("  %s\n", gerbv_aperture_type_name(s->type));
+        } else {
+            GERB_FATAL_ERROR(_("Unknown simplified aperture macro type %d"), s->type);
+        }
 
+        s = s->next;
+    }
+} /* gerbv_gdk_draw_amacro */
 
 /*
  * Draws a circle _centered_ at x,y with diameter dia
  */
-static void 
-gerbv_gdk_draw_circle(GdkPixmap *pixmap, GdkGC *gc, 
-		  gint filled, gint x, gint y, gint dia)
-{
+static void
+gerbv_gdk_draw_circle(GdkPixmap* pixmap, GdkGC* gc, gint filled, gint x, gint y, gint dia) {
     static const gint full_circle = 23360;
-    gint real_x = x - dia / 2;
-    gint real_y = y - dia / 2;
-    
+    gint              real_x      = x - dia / 2;
+    gint              real_y      = y - dia / 2;
+
     gdk_draw_arc(pixmap, gc, filled, real_x, real_y, dia, dia, 0, full_circle);
-    
+
     return;
 } /* gerbv_gdk_draw_circle */
 
-
 /*
  * Draws a rectangle _centered_ at x,y with sides x_side, y_side
  */
 static void
-gerbv_gdk_draw_rectangle(GdkPixmap *pixmap, GdkGC *gc,
-		int filled, gint x, gint y, gint x_side, gint y_side,
-		double angle_deg)
-{
-	int i;
-	GdkPoint points[4];
-
-	points[0].x = -(x_side >> 1);
-	points[0].y = -(y_side >> 1);
-	points[1].x = x_side >> 1;
-	points[1].y = points[0].y;
-	points[2].x = points[1].x;
-	points[2].y = y_side >> 1;
-	points[3].x = points[0].x;
-	points[3].y = points[2].y;
-
-	for (i = 0; i < 4; i++) {
-		points[i] = rotate_point(points[i], angle_deg);
-		points[i].x += x;
-		points[i].y += y;
-	}
-
-	gdk_draw_polygon(pixmap, gc, filled, points, 4);
-
-	return;
-} /* gerbv_gdk_draw_rectangle */
+gerbv_gdk_draw_rectangle(
+    GdkPixmap* pixmap, GdkGC* gc, int filled, gint x, gint y, gint x_side, gint y_side, double angle_deg
+) {
+    int      i;
+    GdkPoint points[4];
+
+    points[0].x = -(x_side >> 1);
+    points[0].y = -(y_side >> 1);
+    points[1].x = x_side >> 1;
+    points[1].y = points[0].y;
+    points[2].x = points[1].x;
+    points[2].y = y_side >> 1;
+    points[3].x = points[0].x;
+    points[3].y = points[2].y;
+
+    for (i = 0; i < 4; i++) {
+        points[i] = rotate_point(points[i], angle_deg);
+        points[i].x += x;
+        points[i].y += y;
+    }
 
+    gdk_draw_polygon(pixmap, gc, filled, points, 4);
+
+    return;
+} /* gerbv_gdk_draw_rectangle */
 
 /*
  * Draws an oval _centered_ at x,y with x axis x_axis and y axis y_axis
- */ 
+ */
 static void
-gerbv_gdk_draw_oval(GdkPixmap *pixmap, GdkGC *gc,
-		int filled, gint x, gint y, gint x_axis, gint y_axis,
-		double angle_deg)
-{
-	gint width;
-	GdkPoint points[2];
-	GdkGC *local_gc = gdk_gc_new(pixmap);
-
-	gdk_gc_copy(local_gc, gc);
-
-	if (x_axis > y_axis) {
-		/* Draw in x axis */
-		width = y_axis;
-
-		points[0].x = -(x_axis >> 1) + (y_axis >> 1);
-		points[0].y = 0;
-		points[1].x =  (x_axis >> 1) - (y_axis >> 1);
-		points[1].y = 0;
-	} else {
-		/* Draw in y axis */
-		width = x_axis;
-
-		points[0].x = 0;
-		points[0].y = -(y_axis >> 1) + (x_axis >> 1);
-		points[1].x = 0;
-		points[1].y =  (y_axis >> 1) - (x_axis >> 1);
-	}
-
-	points[0] = rotate_point(points[0], angle_deg);
-	points[0].x += x;
-	points[0].y += y;
-	points[1] = rotate_point(points[1], angle_deg);
-	points[1].x += x;
-	points[1].y += y;
-
-	gdk_gc_set_line_attributes(local_gc, width,
-			GDK_LINE_SOLID, GDK_CAP_ROUND, GDK_JOIN_MITER);
-	gdk_draw_line(pixmap, local_gc,
-			points[0].x, points[0].y,
-			points[1].x, points[1].y);
+gerbv_gdk_draw_oval(
+    GdkPixmap* pixmap, GdkGC* gc, int filled, gint x, gint y, gint x_axis, gint y_axis, double angle_deg
+) {
+    gint     width;
+    GdkPoint points[2];
+    GdkGC*   local_gc = gdk_gc_new(pixmap);
+
+    gdk_gc_copy(local_gc, gc);
+
+    if (x_axis > y_axis) {
+        /* Draw in x axis */
+        width = y_axis;
+
+        points[0].x = -(x_axis >> 1) + (y_axis >> 1);
+        points[0].y = 0;
+        points[1].x = (x_axis >> 1) - (y_axis >> 1);
+        points[1].y = 0;
+    } else {
+        /* Draw in y axis */
+        width = x_axis;
+
+        points[0].x = 0;
+        points[0].y = -(y_axis >> 1) + (x_axis >> 1);
+        points[1].x = 0;
+        points[1].y = (y_axis >> 1) - (x_axis >> 1);
+    }
+
+    points[0] = rotate_point(points[0], angle_deg);
+    points[0].x += x;
+    points[0].y += y;
+    points[1] = rotate_point(points[1], angle_deg);
+    points[1].x += x;
+    points[1].y += y;
+
+    gdk_gc_set_line_attributes(local_gc, width, GDK_LINE_SOLID, GDK_CAP_ROUND, GDK_JOIN_MITER);
+    gdk_draw_line(pixmap, local_gc, points[0].x, points[0].y, points[1].x, points[1].y);
 
     gdk_gc_unref(local_gc);
 
     return;
 } /* gerbv_gdk_draw_oval */
 
-
 /*
- * Draws an arc 
+ * Draws an arc
  * Draws an arc _centered_ at x,y
  * direction:  0 counterclockwise, 1 clockwise
  */
 static void
-gerbv_gdk_draw_arc(GdkPixmap *pixmap, GdkGC *gc,
-	       int x, int y,
-	       gdouble width, gdouble height,
-	       double angle1, double angle2)
-{
+gerbv_gdk_draw_arc(
+    GdkPixmap* pixmap, GdkGC* gc, int x, int y, gdouble width, gdouble height, double angle1, double angle2
+) {
     gint real_x = round(x - width / 2);
     gint real_y = round(y - height / 2);
 
-    gdk_draw_arc(pixmap, gc, FALSE, real_x, real_y, width, height,
-		round(64*fmod(angle1, 360)), round(64*(angle2 - angle1)));
+    gdk_draw_arc(
+        pixmap, gc, FALSE, real_x, real_y, width, height, round(64 * fmod(angle1, 360)), round(64 * (angle2 - angle1))
+    );
 } /* gerbv_gdk_draw_arc */
 
 void
-draw_gdk_render_polygon_object (gerbv_net_t *oldNet, gerbv_image_t *image, double sr_x, double sr_y,
-			cairo_matrix_t *fullMatrix, cairo_matrix_t *scaleMatrix, GdkGC *gc, GdkGC *pgc,
-			GdkPixmap **pixmap) {
-	gerbv_net_t *currentNet;
-	gint x2,y2,cp_x=0,cp_y=0,cir_width=0;
-	GdkPoint *points = NULL;
-	unsigned int pointArraySize, curr_point_idx;
-	int steps,i;
-	gdouble angleDiff, tempX, tempY;
-
-	/* save the first net in the polygon as the "ID" net pointer
-	in case we are saving this net to the selection array */
-	curr_point_idx = 0;
-	pointArraySize = 0;
-
-	for (currentNet = oldNet->next; currentNet!=NULL; currentNet = currentNet->next){	
-		tempX = currentNet->stop_x + sr_x;
-		tempY = currentNet->stop_y + sr_y;
-		cairo_matrix_transform_point (fullMatrix, &tempX, &tempY);
-		x2 = (int)round(tempX);
-		y2 = (int)round(tempY);
-		
-		/* 
-		* If circle segment, scale and translate that one too
-		*/
-		if (currentNet->cirseg) {
-			tempX = currentNet->cirseg->width;
-			tempY = currentNet->cirseg->height;
-			cairo_matrix_transform_point (scaleMatrix, &tempX, &tempY);
-
-			/* Variables can be negative after transformation */
-			tempX = fabs(tempX);
-			cir_width = (int)round(tempX);
-
-			tempX = currentNet->cirseg->cp_x + sr_x;
-			tempY = currentNet->cirseg->cp_y + sr_y;
-			cairo_matrix_transform_point (fullMatrix, &tempX, &tempY);
-			cp_x = (int)round(tempX);
-			cp_y = (int)round(tempY);
-		}
-
-		switch (currentNet->interpolation) {
-			case GERBV_INTERPOLATION_LINEARx1 :
-			case GERBV_INTERPOLATION_LINEARx10 :
-			case GERBV_INTERPOLATION_LINEARx01 :
-			case GERBV_INTERPOLATION_LINEARx001 :
-				if (pointArraySize < (curr_point_idx + 1)) {
-					pointArraySize = curr_point_idx + 1;
-					points = (GdkPoint *)g_realloc(points,
-							pointArraySize*sizeof(GdkPoint));
-				}
-				points[curr_point_idx].x = x2;
-				points[curr_point_idx].y = y2;
-				curr_point_idx++;
-				break;
-			case GERBV_INTERPOLATION_CW_CIRCULAR :
-			case GERBV_INTERPOLATION_CCW_CIRCULAR :
-				/* we need to chop up the arc into small lines for rendering
-				with GDK */
-				angleDiff = currentNet->cirseg->angle2 - currentNet->cirseg->angle1;
-				steps = (int) abs(angleDiff);
-				if (pointArraySize < (curr_point_idx + steps)) {
-					pointArraySize = curr_point_idx + steps;
-					points = (GdkPoint *)g_realloc(points,
-							pointArraySize*sizeof(GdkPoint));
-				}
-				for (i=0; i<steps; i++){
-					points[curr_point_idx].x = cp_x + cir_width / 2.0 * cos (DEG2RAD(currentNet->cirseg->angle1 +
-									      (angleDiff * i) / steps));
-					points[curr_point_idx].y = cp_y - cir_width / 2.0 * sin (DEG2RAD(currentNet->cirseg->angle1 +
-									      (angleDiff * i) / steps));
-					curr_point_idx++;
-				}
-				break;
-			case GERBV_INTERPOLATION_PAREA_END :
-				gdk_gc_copy(pgc, gc); 
-				gdk_gc_set_line_attributes(pgc, 1, 
-				       GDK_LINE_SOLID, 
-				       GDK_CAP_PROJECTING, 
-				       GDK_JOIN_MITER);
-				gdk_draw_polygon(*pixmap, pgc, 1, points, curr_point_idx);
-				g_free(points);
-				points = NULL;
-				return;
-			default:
-				GERB_COMPILE_WARNING(
-					_("Skipped interpolation type %d"),
-					currentNet->interpolation);
-				break;
-		}
-	}
-	return;
+draw_gdk_render_polygon_object(
+    gerbv_net_t* oldNet, gerbv_image_t* image, double sr_x, double sr_y, cairo_matrix_t* fullMatrix,
+    cairo_matrix_t* scaleMatrix, GdkGC* gc, GdkGC* pgc, GdkPixmap** pixmap
+) {
+    gerbv_net_t* currentNet;
+    gint         x2, y2, cp_x = 0, cp_y = 0, cir_width = 0;
+    GdkPoint*    points = NULL;
+    unsigned int pointArraySize, curr_point_idx;
+    int          steps, i;
+    gdouble      angleDiff, tempX, tempY;
+
+    /* save the first net in the polygon as the "ID" net pointer
+    in case we are saving this net to the selection array */
+    curr_point_idx = 0;
+    pointArraySize = 0;
+
+    for (currentNet = oldNet->next; currentNet != NULL; currentNet = currentNet->next) {
+        tempX = currentNet->stop_x + sr_x;
+        tempY = currentNet->stop_y + sr_y;
+        cairo_matrix_transform_point(fullMatrix, &tempX, &tempY);
+        x2 = (int)round(tempX);
+        y2 = (int)round(tempY);
+
+        /*
+         * If circle segment, scale and translate that one too
+         */
+        if (currentNet->cirseg) {
+            tempX = currentNet->cirseg->width;
+            tempY = currentNet->cirseg->height;
+            cairo_matrix_transform_point(scaleMatrix, &tempX, &tempY);
+
+            /* Variables can be negative after transformation */
+            tempX     = fabs(tempX);
+            cir_width = (int)round(tempX);
+
+            tempX = currentNet->cirseg->cp_x + sr_x;
+            tempY = currentNet->cirseg->cp_y + sr_y;
+            cairo_matrix_transform_point(fullMatrix, &tempX, &tempY);
+            cp_x = (int)round(tempX);
+            cp_y = (int)round(tempY);
+        }
+
+        switch (currentNet->interpolation) {
+            case GERBV_INTERPOLATION_LINEARx1:
+            case GERBV_INTERPOLATION_LINEARx10:
+            case GERBV_INTERPOLATION_LINEARx01:
+            case GERBV_INTERPOLATION_LINEARx001:
+                if (pointArraySize < (curr_point_idx + 1)) {
+                    pointArraySize = curr_point_idx + 1;
+                    points         = (GdkPoint*)g_realloc(points, pointArraySize * sizeof(GdkPoint));
+                }
+                points[curr_point_idx].x = x2;
+                points[curr_point_idx].y = y2;
+                curr_point_idx++;
+                break;
+            case GERBV_INTERPOLATION_CW_CIRCULAR:
+            case GERBV_INTERPOLATION_CCW_CIRCULAR:
+                /* we need to chop up the arc into small lines for rendering
+                with GDK */
+                angleDiff = currentNet->cirseg->angle2 - currentNet->cirseg->angle1;
+                steps     = (int)abs(angleDiff);
+                if (pointArraySize < (curr_point_idx + steps)) {
+                    pointArraySize = curr_point_idx + steps;
+                    points         = (GdkPoint*)g_realloc(points, pointArraySize * sizeof(GdkPoint));
+                }
+                for (i = 0; i < steps; i++) {
+                    points[curr_point_idx].x =
+                        cp_x + cir_width / 2.0 * cos(DEG2RAD(currentNet->cirseg->angle1 + (angleDiff * i) / steps));
+                    points[curr_point_idx].y =
+                        cp_y - cir_width / 2.0 * sin(DEG2RAD(currentNet->cirseg->angle1 + (angleDiff * i) / steps));
+                    curr_point_idx++;
+                }
+                break;
+            case GERBV_INTERPOLATION_PAREA_END:
+                gdk_gc_copy(pgc, gc);
+                gdk_gc_set_line_attributes(pgc, 1, GDK_LINE_SOLID, GDK_CAP_PROJECTING, GDK_JOIN_MITER);
+                gdk_draw_polygon(*pixmap, pgc, 1, points, curr_point_idx);
+                g_free(points);
+                points = NULL;
+                return;
+            default: GERB_COMPILE_WARNING(_("Skipped interpolation type %d"), currentNet->interpolation); break;
+        }
+    }
+    return;
 }
 
 void
-draw_gdk_apply_netstate_transformation  (cairo_matrix_t *fullMatrix, cairo_matrix_t *scaleMatrix,
-	gerbv_netstate_t *state) {
-	/* apply scale factor */
-	cairo_matrix_scale (fullMatrix, state->scaleA, state->scaleB);
-	cairo_matrix_scale (scaleMatrix, state->scaleA, state->scaleB);
-	/* apply offset */
-	cairo_matrix_translate (fullMatrix, state->offsetA, state->offsetB);
-	/* apply mirror */
-	switch (state->mirrorState) {
-		case GERBV_MIRROR_STATE_FLIPA:
-			cairo_matrix_scale (fullMatrix, -1, 1);
-			cairo_matrix_scale (scaleMatrix, -1, 1);
-			break;
-		case GERBV_MIRROR_STATE_FLIPB:
-			cairo_matrix_scale (fullMatrix, 1, -1);
-			cairo_matrix_scale (scaleMatrix, -1, 1);
-			break;
-		case GERBV_MIRROR_STATE_FLIPAB:
-			cairo_matrix_scale (fullMatrix, -1, -1);
-			cairo_matrix_scale (scaleMatrix, -1, 1);
-			break;
-		default:
-			break;
-	}
-	/* finally, apply axis select */
-	if (state->axisSelect == GERBV_AXIS_SELECT_SWAPAB) {
-		/* we do this by rotating 270 (counterclockwise, then mirroring
-		   the Y axis */
-		cairo_matrix_rotate (fullMatrix, M_PI + M_PI_2);
-		cairo_matrix_scale (fullMatrix, 1, -1);
-	}
+draw_gdk_apply_netstate_transformation(
+    cairo_matrix_t* fullMatrix, cairo_matrix_t* scaleMatrix, gerbv_netstate_t* state
+) {
+    /* apply scale factor */
+    cairo_matrix_scale(fullMatrix, state->scaleA, state->scaleB);
+    cairo_matrix_scale(scaleMatrix, state->scaleA, state->scaleB);
+    /* apply offset */
+    cairo_matrix_translate(fullMatrix, state->offsetA, state->offsetB);
+    /* apply mirror */
+    switch (state->mirrorState) {
+        case GERBV_MIRROR_STATE_FLIPA:
+            cairo_matrix_scale(fullMatrix, -1, 1);
+            cairo_matrix_scale(scaleMatrix, -1, 1);
+            break;
+        case GERBV_MIRROR_STATE_FLIPB:
+            cairo_matrix_scale(fullMatrix, 1, -1);
+            cairo_matrix_scale(scaleMatrix, -1, 1);
+            break;
+        case GERBV_MIRROR_STATE_FLIPAB:
+            cairo_matrix_scale(fullMatrix, -1, -1);
+            cairo_matrix_scale(scaleMatrix, -1, 1);
+            break;
+        default: break;
+    }
+    /* finally, apply axis select */
+    if (state->axisSelect == GERBV_AXIS_SELECT_SWAPAB) {
+        /* we do this by rotating 270 (counterclockwise, then mirroring
+           the Y axis */
+        cairo_matrix_rotate(fullMatrix, M_PI + M_PI_2);
+        cairo_matrix_scale(fullMatrix, 1, -1);
+    }
 }
 
 static void
-draw_gdk_cross (GdkPixmap *pixmap, GdkGC *gc, gint xc, gint yc, gint r)
-{
-	gdk_gc_set_line_attributes (gc, 1, GDK_LINE_SOLID,
-			GDK_CAP_BUTT, GDK_JOIN_MITER);
-	gdk_draw_line (pixmap, gc, xc - r, yc, xc + r, yc);
-	gdk_draw_line (pixmap, gc, xc, yc - r, xc, yc + r);
+draw_gdk_cross(GdkPixmap* pixmap, GdkGC* gc, gint xc, gint yc, gint r) {
+    gdk_gc_set_line_attributes(gc, 1, GDK_LINE_SOLID, GDK_CAP_BUTT, GDK_JOIN_MITER);
+    gdk_draw_line(pixmap, gc, xc - r, yc, xc + r, yc);
+    gdk_draw_line(pixmap, gc, xc, yc - r, xc, yc + r);
 }
 
 /*
  * Convert a gerber image to a GDK clip mask to be used when creating pixmap
  */
 int
-draw_gdk_image_to_pixmap(GdkPixmap **pixmap, gerbv_image_t *image, 
-	     double scale, double trans_x, double trans_y,
-	     enum draw_mode drawMode,
-	     gerbv_selection_info_t *selectionInfo, gerbv_render_info_t *renderInfo,
-	     gerbv_user_transformation_t transform)
-{
-	const int hole_cross_inc_px = 8;
-	GdkGC *gc = gdk_gc_new(*pixmap);
-	GdkGC *pgc = gdk_gc_new(*pixmap);
-	GdkGCValues gc_values;
-	struct gerbv_net *net;
-	gerbv_netstate_t *oldState;
-	gerbv_layer_t *oldLayer;
-	gint x1, y1, x2, y2;
-	glong xlong1, ylong1, xlong2, ylong2;
-	int p1, p2;
-	double cir_width = 0, cir_height = 0;
-	int cp_x = 0, cp_y = 0;
-	GdkColor transparent, opaque;
-	gerbv_polarity_t polarity;
-	gdouble tempX, tempY, r;
-	gdouble minX=0,minY=0,maxX=0,maxY=0;
-
-	if (image == NULL || image->netlist == NULL) {
-		gdk_gc_unref(gc);
-		gdk_gc_unref(pgc);
-
-		return 0;
-	}
-
-	if (transform.inverted) {
-		if (image->info->polarity == GERBV_POLARITY_POSITIVE)
-			polarity = GERBV_POLARITY_NEGATIVE;
-		else
-			polarity = GERBV_POLARITY_POSITIVE;
-	} else {
-		polarity = image->info->polarity;
-	}
-	if (drawMode == DRAW_SELECTIONS)
-		polarity = GERBV_POLARITY_POSITIVE;
-
-	gboolean useOptimizations = TRUE;
-	// if the user is using any transformations for this layer, then don't bother using rendering
-	//   optimizations
-	if (fabs(transform.translateX) > GERBV_PRECISION_LINEAR_INCH
-	||  fabs(transform.translateY) > GERBV_PRECISION_LINEAR_INCH
-	||  fabs(transform.scaleX - 1) > GERBV_PRECISION_LINEAR_INCH 
-	||  fabs(transform.scaleY - 1) > GERBV_PRECISION_LINEAR_INCH
-	||  fabs(transform.rotation) > GERBV_PRECISION_ANGLE_RAD
-	||  transform.mirrorAroundX || transform.mirrorAroundY)
-		useOptimizations = FALSE;
-
-	// calculate the transformation matrix for the user_transformation options
-	cairo_matrix_t fullMatrix, scaleMatrix;
-	cairo_matrix_init (&fullMatrix, 1, 0, 0, 1, 0, 0);
-	cairo_matrix_init (&scaleMatrix, 1, 0, 0, 1, 0, 0);
-
-	cairo_matrix_translate (&fullMatrix, trans_x, trans_y);
-	cairo_matrix_scale (&fullMatrix, scale, scale);
-	cairo_matrix_scale (&scaleMatrix, scale, scale);
-	/* offset image */
-
-	cairo_matrix_translate (&fullMatrix, transform.translateX, -1*transform.translateY);
-	// don't use mirroring for the scale matrix
-	gdouble scaleX = transform.scaleX;
-	gdouble scaleY = -1*transform.scaleY;
-	cairo_matrix_scale (&scaleMatrix, scaleX, -1*scaleY);
-	if (transform.mirrorAroundX)
-		scaleY *= -1;
-	if (transform.mirrorAroundY)
-		scaleX *= -1;
-
-	cairo_matrix_scale (&fullMatrix, scaleX, scaleY);
-	/* do image rotation */
-	cairo_matrix_rotate (&fullMatrix, transform.rotation);
-	//cairo_matrix_rotate (&scaleMatrix, transform.rotation);
-
-	/* do image rotation */
-	cairo_matrix_rotate (&fullMatrix, image->info->imageRotation);
-
-	if (useOptimizations) {
-		minX = renderInfo->lowerLeftX;
-		minY = renderInfo->lowerLeftY;
-		maxX = renderInfo->lowerLeftX + (renderInfo->displayWidth /
-					renderInfo->scaleFactorX);
-		maxY = renderInfo->lowerLeftY + (renderInfo->displayHeight /
-					renderInfo->scaleFactorY);
-	}
-
-	/* Set up the two "colors" we have */
-	opaque.pixel = 0; /* opaque will not let color through */
-	transparent.pixel = 1; /* transparent will let color through */ 
-
-	/*
-	* Clear clipmask and set draw color depending image on image polarity
-	*/
-	if (polarity == GERBV_POLARITY_NEGATIVE) {
-		gdk_gc_set_foreground(gc, &transparent);
-		gdk_draw_rectangle(*pixmap, gc, TRUE, 0, 0, -1, -1);
-		gdk_gc_set_foreground(gc, &opaque);
-	} else {
-		gdk_gc_set_foreground(gc, &opaque);
-		gdk_draw_rectangle(*pixmap, gc, TRUE, 0, 0, -1, -1);
-		gdk_gc_set_foreground(gc, &transparent);
-	}
-	oldLayer = image->layers;
-	oldState = image->states;
-	for (net = image->netlist->next ; net != NULL; net = gerbv_image_return_next_renderable_object(net)) {
-		int repeat_X=1, repeat_Y=1;
-		double repeat_dist_X=0.0, repeat_dist_Y=0.0;
-		int repeat_i, repeat_j;
-
-		/*
-		 * If step_and_repeat (%SR%) used, repeat the drawing;
-		 */
-		repeat_X = net->layer->stepAndRepeat.X;
-		repeat_Y = net->layer->stepAndRepeat.Y;
-		repeat_dist_X = net->layer->stepAndRepeat.dist_X;
-		repeat_dist_Y = net->layer->stepAndRepeat.dist_Y;
-
-		/* check if this is a new netstate */
-		if (net->state != oldState){
-			/* it's a new state, so recalculate the new transformation matrix
-			   for it */
-			draw_gdk_apply_netstate_transformation (&fullMatrix, &scaleMatrix, net->state);
-			oldState = net->state;	
-		}
-		/* check if this is a new layer */
-		/* for now, only do layer rotations in GDK rendering */
-		if (net->layer != oldLayer){
-			cairo_matrix_rotate (&fullMatrix, net->layer->rotation);
-			oldLayer = net->layer;
-		}
-
-		if (drawMode == DRAW_SELECTIONS) {
-			gboolean foundNet = FALSE;
-			gerbv_selection_item_t sItem;
-			
-			for (guint i = 0; i < selectionInfo->selectedNodeArray->len; i++) {
-				sItem = g_array_index (selectionInfo->selectedNodeArray,
-						gerbv_selection_item_t, i);
-				if (sItem.net == net) {
-					foundNet = TRUE;
-					break;
-				}
-			}
-			if (!foundNet)
-				continue;
-		}
-
-		for(repeat_i = 0; repeat_i < repeat_X; repeat_i++) {
-		for(repeat_j = 0; repeat_j < repeat_Y; repeat_j++) {
-		  double sr_x = repeat_i * repeat_dist_X;
-		  double sr_y = repeat_j * repeat_dist_Y;
-			
-			if ((useOptimizations)&&((net->boundingBox.right+sr_x < minX)
-					|| (net->boundingBox.left+sr_x > maxX)
-					|| (net->boundingBox.top+sr_y < minY)
-					|| (net->boundingBox.bottom+sr_y > maxY))) {
-				continue;
-			}
-
-		/* 
-		 * If circle segment, scale and translate that one too
-		 */
-		if (net->cirseg) {
-		    tempX = net->cirseg->width;
-		    tempY = net->cirseg->height;
-		    cairo_matrix_transform_point (&scaleMatrix, &tempX, &tempY);
-
-		    /* Variables can be negative after transformation */
-		    tempX = fabs(tempX);
-		    tempY = fabs(tempY);
-		    cir_width =  tempX;
-		    cir_height = tempY;
-		    
-		    tempX = net->cirseg->cp_x;
-		    tempY = net->cirseg->cp_y;
-		    cairo_matrix_transform_point (&fullMatrix, &tempX, &tempY);
-		    cp_x = (int)round(tempX);
-		    cp_y = (int)round(tempY);
-		}
-
-		/*
-		 * Set GdkFunction depending on if this (gerber) layer is inverted
-		 * and allow for the photoplot being negative.
-		 */
-		gdk_gc_set_function(gc, GDK_COPY);
-		if ((net->layer->polarity == GERBV_POLARITY_CLEAR) != (polarity == GERBV_POLARITY_NEGATIVE))
-		    gdk_gc_set_foreground(gc, &opaque);
-		else
-		    gdk_gc_set_foreground(gc, &transparent);
-
-		/*
-		 * Polygon Area Fill routines
-		 */
-		switch (net->interpolation) {
-		case GERBV_INTERPOLATION_PAREA_START :
-		    draw_gdk_render_polygon_object (net,image,sr_x,sr_y,&fullMatrix,
-		    	&scaleMatrix,gc,pgc,pixmap);
-		    continue;
-		/* make sure we completely skip over any deleted nodes */
-		case GERBV_INTERPOLATION_DELETED:
-		    continue;
-		default :
-		    break;
-		}
-
-
-		/*
-		 * If aperture state is off we allow use of undefined apertures.
-		 * This happens when gerber files starts, but hasn't decided on 
-		 * which aperture to use.
-		 */
-		if (image->aperture[net->aperture] == NULL) {
-		  /* Commenting this out since it gets emitted every time you click on the screen 
-		     if (net->aperture_state != GERBV_APERTURE_STATE_OFF)
-		     GERB_MESSAGE("Aperture D%d is not defined", net->aperture);
-		  */
-		    continue;
-		}
-
-		/*
-		 * Scale points with window scaling and translate them
-		 */
-		tempX = net->start_x + sr_x;
-		tempY = net->start_y + sr_y;
-		cairo_matrix_transform_point (&fullMatrix, &tempX, &tempY);
-		xlong1 = (int)round(tempX);
-		ylong1 = (int)round(tempY);
-
-		tempX = net->stop_x + sr_x;
-		tempY = net->stop_y + sr_y;
-		cairo_matrix_transform_point (&fullMatrix, &tempX, &tempY);
-		xlong2 = (int)round(tempX);
-		ylong2 = (int)round(tempY);
-
-		/* if the object is way outside our view window, just skip over it in order
-		   to eliminate some GDK clipping problems at high zoom levels */
-		if ((xlong1 < -10000) && (xlong2 < -10000))
-			continue;
-		if ((ylong1 < -10000) && (ylong2 < -10000))
-			continue;
-		if ((xlong1 > 10000) && (xlong2 > 10000))
-			continue;
-		if ((ylong1 > 10000) && (ylong2 > 10000))
-			continue;
-
-		if (xlong1 > G_MAXINT) x1 = G_MAXINT;
-		else if (xlong1 < G_MININT) x1 = G_MININT;
-		else x1 = (int)xlong1;
-
-		if (xlong2 > G_MAXINT) x2 = G_MAXINT;
-		else if (xlong2 < G_MININT) x2 = G_MININT;
-		else x2 = (int)xlong2;
-
-		if (ylong1 > G_MAXINT) y1 = G_MAXINT;
-		else if (ylong1 < G_MININT) y1 = G_MININT;
-		else y1 = (int)ylong1;
-
-		if (ylong2 > G_MAXINT) y2 = G_MAXINT;
-		else if (ylong2 < G_MININT) y2 = G_MININT;
-		else y2 = (int)ylong2;
-
-		switch (net->aperture_state) {
-		case GERBV_APERTURE_STATE_ON :
-		    tempX = image->aperture[net->aperture]->parameter[0];
-		    cairo_matrix_transform_point (&scaleMatrix, &tempX, &tempY);
-
-		    /* Variables can be negative after transformation */
-		    tempX = fabs(tempX);
-		    p1 = (int)round(tempX);
-
-		    gdk_gc_set_line_attributes(gc, p1, GDK_LINE_SOLID,
-				    (image->aperture[net->aperture]->type == GERBV_APTYPE_RECTANGLE)?
-						GDK_CAP_PROJECTING: GDK_CAP_ROUND,
-				    GDK_JOIN_MITER);
-		    
-		    switch (net->interpolation) {
-		    case GERBV_INTERPOLATION_LINEARx10 :
-		    case GERBV_INTERPOLATION_LINEARx01 :
-		    case GERBV_INTERPOLATION_LINEARx001 :
-			GERB_MESSAGE(_("Linear != x1"));
-			gdk_gc_set_line_attributes(gc, p1, 
-						   GDK_LINE_ON_OFF_DASH, 
-						   GDK_CAP_ROUND, 
-						   GDK_JOIN_MITER);
-			gdk_draw_line(*pixmap, gc, x1, y1, x2, y2);
-			gdk_gc_set_line_attributes(gc, p1, 
-						   GDK_LINE_SOLID,
-						   GDK_CAP_ROUND, 
-						   GDK_JOIN_MITER);
-			break;
-		    case GERBV_INTERPOLATION_LINEARx1 :
-			if (image->aperture[net->aperture]->type != GERBV_APTYPE_RECTANGLE) {
-				gdk_draw_line(*pixmap, gc, x1, y1, x2, y2);
-
-				if (renderInfo->show_cross_on_drill_holes
-				&& image->layertype == GERBV_LAYERTYPE_DRILL) {
-					/* Draw crosses on drill slot start and end */
-					r = p1/2.0 + hole_cross_inc_px;
-					draw_gdk_cross(*pixmap, gc, x1, y1, r);
-					draw_gdk_cross(*pixmap, gc, x2, y2, r);
-				}
-			    break;
-			}
-
-			gint dx, dy;
-			GdkPoint poly[6];
-
-			tempX = image->aperture[net->aperture]->parameter[0]/2;
-			tempY = image->aperture[net->aperture]->parameter[1]/2;
-			cairo_matrix_transform_point (&scaleMatrix, &tempX, &tempY);
-			dx = (int)round(tempX);
-			dy = (int)round(tempY);
-
-			if(x1 > x2) dx = -dx;
-			if(y1 > y2) dy = -dy;
-			poly[0].x = x1 - dx; poly[0].y = y1 - dy;
-			poly[1].x = x1 - dx; poly[1].y = y1 + dy;
-			poly[2].x = x2 - dx; poly[2].y = y2 + dy;
-			poly[3].x = x2 + dx; poly[3].y = y2 + dy;
-			poly[4].x = x2 + dx; poly[4].y = y2 - dy;
-			poly[5].x = x1 + dx; poly[5].y = y1 - dy;
-			gdk_draw_polygon(*pixmap, gc, 1, poly, 6);
-			break;
-
-		    case GERBV_INTERPOLATION_CW_CIRCULAR :
-		    case GERBV_INTERPOLATION_CCW_CIRCULAR :
-			gerbv_gdk_draw_arc(*pixmap, gc, cp_x, cp_y,
-				cir_width, cir_height,
-				net->cirseg->angle1 +
-					RAD2DEG(transform.rotation),
-				net->cirseg->angle2 +
-					RAD2DEG(transform.rotation));
-			break;
-		    default :
-			GERB_COMPILE_WARNING(
-				_("Skipped interpolation type %d"),
-				net->interpolation);
-			break;
-		    }
-		    break;
-		case GERBV_APERTURE_STATE_OFF :
-		    break;
-		case GERBV_APERTURE_STATE_FLASH :
-		    tempX = image->aperture[net->aperture]->parameter[0];
-		    tempY = image->aperture[net->aperture]->parameter[1];
-		    cairo_matrix_transform_point (&scaleMatrix, &tempX, &tempY);
-
-		    /* Variables can be negative after transformation */
-		    tempX = fabs(tempX);
-		    tempY = fabs(tempY);
-		    p1 = (int)round(tempX);
-		    p2 = (int)round(tempY);
-		    
-		    switch (image->aperture[net->aperture]->type) {
-		    case GERBV_APTYPE_CIRCLE :
-			gerbv_gdk_draw_circle(*pixmap, gc, TRUE, x2, y2, p1);
-
-			if (renderInfo->show_cross_on_drill_holes
-			&& image->layertype == GERBV_LAYERTYPE_DRILL) {
-				r = p1/2.0 + hole_cross_inc_px;
-				draw_gdk_cross(*pixmap, gc, x2, y2, r);
-			}
-
-			/*
-			 * If circle has an inner diameter we must remove
-			 * that part of the circle to make a hole in it.
-			 * We should actually support square holes too,
-			 * but due to laziness I don't.
-			 */
-			if (p2) {
-			    gdk_gc_get_values(gc, &gc_values);
-			    if (gc_values.foreground.pixel == opaque.pixel) {
-				gdk_gc_set_foreground(gc, &transparent);
-				gerbv_gdk_draw_circle(*pixmap, gc, TRUE, x2, y2, p2);
-				gdk_gc_set_foreground(gc, &opaque);
-			    } else {
-				gdk_gc_set_foreground(gc, &opaque);
-				gerbv_gdk_draw_circle(*pixmap, gc, TRUE, x2, y2, p2);
-				gdk_gc_set_foreground(gc, &transparent);
-			    }
-			}
-
-			break;
-		    case GERBV_APTYPE_RECTANGLE:
-			gerbv_gdk_draw_rectangle(*pixmap, gc, TRUE,
-				x2, y2, p1, p2, RAD2DEG(transform.rotation +
-					image->info->imageRotation));
-			break;
-		    case GERBV_APTYPE_OVAL :
-			gerbv_gdk_draw_oval(*pixmap, gc, TRUE,
-				x2, y2, p1, p2, RAD2DEG(transform.rotation +
-					image->info->imageRotation));
-			break;
-		    case GERBV_APTYPE_POLYGON :
-			/* TODO: gdk_draw_polygon() */
-			gerbv_gdk_draw_circle(*pixmap, gc, TRUE, x2, y2, p1);
-			break;
-		    case GERBV_APTYPE_MACRO :
-			/* TODO: check line22 and others */
-			gerbv_gdk_draw_amacro(*pixmap, gc, 
-					      image->aperture[net->aperture]->simplified,
-					      scale, x2, y2);
-			break;
-		    default :
-			GERB_MESSAGE(_("Unknown aperture type %d"),
-					image->aperture[net->aperture]->type);
-			return 0;
-		    }
-		    break;
-		default :
-		    GERB_MESSAGE(_("Unknown aperture state %d"),
-				net->aperture_state);
-		    return 0;
-		}
-		}
-		}
-	}
-	/*
-	* Destroy GCs before exiting
-	*/
-	gdk_gc_unref(gc);
-	gdk_gc_unref(pgc);
-
-	return 1;
+draw_gdk_image_to_pixmap(
+    GdkPixmap** pixmap, gerbv_image_t* image, double scale, double trans_x, double trans_y, enum draw_mode drawMode,
+    gerbv_selection_info_t* selectionInfo, gerbv_render_info_t* renderInfo, gerbv_user_transformation_t transform
+) {
+    const int         hole_cross_inc_px = 8;
+    GdkGC*            gc                = gdk_gc_new(*pixmap);
+    GdkGC*            pgc               = gdk_gc_new(*pixmap);
+    GdkGCValues       gc_values;
+    struct gerbv_net* net;
+    gerbv_netstate_t* oldState;
+    gerbv_layer_t*    oldLayer;
+    gint              x1, y1, x2, y2;
+    glong             xlong1, ylong1, xlong2, ylong2;
+    int               p1, p2;
+    double            cir_width = 0, cir_height = 0;
+    int               cp_x = 0, cp_y = 0;
+    GdkColor          transparent, opaque;
+    gerbv_polarity_t  polarity;
+    gdouble           tempX, tempY, r;
+    gdouble           minX = 0, minY = 0, maxX = 0, maxY = 0;
+
+    if (image == NULL || image->netlist == NULL) {
+        gdk_gc_unref(gc);
+        gdk_gc_unref(pgc);
+
+        return 0;
+    }
 
-} /* image2pixmap */
+    if (transform.inverted) {
+        if (image->info->polarity == GERBV_POLARITY_POSITIVE)
+            polarity = GERBV_POLARITY_NEGATIVE;
+        else
+            polarity = GERBV_POLARITY_POSITIVE;
+    } else {
+        polarity = image->info->polarity;
+    }
+    if (drawMode == DRAW_SELECTIONS)
+        polarity = GERBV_POLARITY_POSITIVE;
+
+    gboolean useOptimizations = TRUE;
+    // if the user is using any transformations for this layer, then don't bother using rendering
+    //   optimizations
+    if (fabs(transform.translateX) > GERBV_PRECISION_LINEAR_INCH
+        || fabs(transform.translateY) > GERBV_PRECISION_LINEAR_INCH
+        || fabs(transform.scaleX - 1) > GERBV_PRECISION_LINEAR_INCH
+        || fabs(transform.scaleY - 1) > GERBV_PRECISION_LINEAR_INCH
+        || fabs(transform.rotation) > GERBV_PRECISION_ANGLE_RAD || transform.mirrorAroundX || transform.mirrorAroundY)
+        useOptimizations = FALSE;
+
+    // calculate the transformation matrix for the user_transformation options
+    cairo_matrix_t fullMatrix, scaleMatrix;
+    cairo_matrix_init(&fullMatrix, 1, 0, 0, 1, 0, 0);
+    cairo_matrix_init(&scaleMatrix, 1, 0, 0, 1, 0, 0);
+
+    cairo_matrix_translate(&fullMatrix, trans_x, trans_y);
+    cairo_matrix_scale(&fullMatrix, scale, scale);
+    cairo_matrix_scale(&scaleMatrix, scale, scale);
+    /* offset image */
+
+    cairo_matrix_translate(&fullMatrix, transform.translateX, -1 * transform.translateY);
+    // don't use mirroring for the scale matrix
+    gdouble scaleX = transform.scaleX;
+    gdouble scaleY = -1 * transform.scaleY;
+    cairo_matrix_scale(&scaleMatrix, scaleX, -1 * scaleY);
+    if (transform.mirrorAroundX)
+        scaleY *= -1;
+    if (transform.mirrorAroundY)
+        scaleX *= -1;
+
+    cairo_matrix_scale(&fullMatrix, scaleX, scaleY);
+    /* do image rotation */
+    cairo_matrix_rotate(&fullMatrix, transform.rotation);
+    // cairo_matrix_rotate (&scaleMatrix, transform.rotation);
+
+    /* do image rotation */
+    cairo_matrix_rotate(&fullMatrix, image->info->imageRotation);
+
+    if (useOptimizations) {
+        minX = renderInfo->lowerLeftX;
+        minY = renderInfo->lowerLeftY;
+        maxX = renderInfo->lowerLeftX + (renderInfo->displayWidth / renderInfo->scaleFactorX);
+        maxY = renderInfo->lowerLeftY + (renderInfo->displayHeight / renderInfo->scaleFactorY);
+    }
+
+    /* Set up the two "colors" we have */
+    opaque.pixel      = 0; /* opaque will not let color through */
+    transparent.pixel = 1; /* transparent will let color through */
 
+    /*
+     * Clear clipmask and set draw color depending image on image polarity
+     */
+    if (polarity == GERBV_POLARITY_NEGATIVE) {
+        gdk_gc_set_foreground(gc, &transparent);
+        gdk_draw_rectangle(*pixmap, gc, TRUE, 0, 0, -1, -1);
+        gdk_gc_set_foreground(gc, &opaque);
+    } else {
+        gdk_gc_set_foreground(gc, &opaque);
+        gdk_draw_rectangle(*pixmap, gc, TRUE, 0, 0, -1, -1);
+        gdk_gc_set_foreground(gc, &transparent);
+    }
+    oldLayer = image->layers;
+    oldState = image->states;
+    for (net = image->netlist->next; net != NULL; net = gerbv_image_return_next_renderable_object(net)) {
+        int    repeat_X = 1, repeat_Y = 1;
+        double repeat_dist_X = 0.0, repeat_dist_Y = 0.0;
+        int    repeat_i, repeat_j;
+
+        /*
+         * If step_and_repeat (%SR%) used, repeat the drawing;
+         */
+        repeat_X      = net->layer->stepAndRepeat.X;
+        repeat_Y      = net->layer->stepAndRepeat.Y;
+        repeat_dist_X = net->layer->stepAndRepeat.dist_X;
+        repeat_dist_Y = net->layer->stepAndRepeat.dist_Y;
+
+        /* check if this is a new netstate */
+        if (net->state != oldState) {
+            /* it's a new state, so recalculate the new transformation matrix
+               for it */
+            draw_gdk_apply_netstate_transformation(&fullMatrix, &scaleMatrix, net->state);
+            oldState = net->state;
+        }
+        /* check if this is a new layer */
+        /* for now, only do layer rotations in GDK rendering */
+        if (net->layer != oldLayer) {
+            cairo_matrix_rotate(&fullMatrix, net->layer->rotation);
+            oldLayer = net->layer;
+        }
+
+        if (drawMode == DRAW_SELECTIONS) {
+            gboolean               foundNet = FALSE;
+            gerbv_selection_item_t sItem;
+
+            for (guint i = 0; i < selectionInfo->selectedNodeArray->len; i++) {
+                sItem = g_array_index(selectionInfo->selectedNodeArray, gerbv_selection_item_t, i);
+                if (sItem.net == net) {
+                    foundNet = TRUE;
+                    break;
+                }
+            }
+            if (!foundNet)
+                continue;
+        }
+
+        for (repeat_i = 0; repeat_i < repeat_X; repeat_i++) {
+            for (repeat_j = 0; repeat_j < repeat_Y; repeat_j++) {
+                double sr_x = repeat_i * repeat_dist_X;
+                double sr_y = repeat_j * repeat_dist_Y;
+
+                if ((useOptimizations)
+                    && ((net->boundingBox.right + sr_x < minX) || (net->boundingBox.left + sr_x > maxX)
+                        || (net->boundingBox.top + sr_y < minY) || (net->boundingBox.bottom + sr_y > maxY))) {
+                    continue;
+                }
+
+                /*
+                 * If circle segment, scale and translate that one too
+                 */
+                if (net->cirseg) {
+                    tempX = net->cirseg->width;
+                    tempY = net->cirseg->height;
+                    cairo_matrix_transform_point(&scaleMatrix, &tempX, &tempY);
+
+                    /* Variables can be negative after transformation */
+                    tempX      = fabs(tempX);
+                    tempY      = fabs(tempY);
+                    cir_width  = tempX;
+                    cir_height = tempY;
+
+                    tempX = net->cirseg->cp_x;
+                    tempY = net->cirseg->cp_y;
+                    cairo_matrix_transform_point(&fullMatrix, &tempX, &tempY);
+                    cp_x = (int)round(tempX);
+                    cp_y = (int)round(tempY);
+                }
+
+                /*
+                 * Set GdkFunction depending on if this (gerber) layer is inverted
+                 * and allow for the photoplot being negative.
+                 */
+                gdk_gc_set_function(gc, GDK_COPY);
+                if ((net->layer->polarity == GERBV_POLARITY_CLEAR) != (polarity == GERBV_POLARITY_NEGATIVE))
+                    gdk_gc_set_foreground(gc, &opaque);
+                else
+                    gdk_gc_set_foreground(gc, &transparent);
+
+                /*
+                 * Polygon Area Fill routines
+                 */
+                switch (net->interpolation) {
+                    case GERBV_INTERPOLATION_PAREA_START:
+                        draw_gdk_render_polygon_object(
+                            net, image, sr_x, sr_y, &fullMatrix, &scaleMatrix, gc, pgc, pixmap
+                        );
+                        continue;
+                    /* make sure we completely skip over any deleted nodes */
+                    case GERBV_INTERPOLATION_DELETED: continue;
+                    default: break;
+                }
+
+                /*
+                 * If aperture state is off we allow use of undefined apertures.
+                 * This happens when gerber files starts, but hasn't decided on
+                 * which aperture to use.
+                 */
+                if (image->aperture[net->aperture] == NULL) {
+                    /* Commenting this out since it gets emitted every time you click on the screen
+                       if (net->aperture_state != GERBV_APERTURE_STATE_OFF)
+                       GERB_MESSAGE("Aperture D%d is not defined", net->aperture);
+                    */
+                    continue;
+                }
+
+                /*
+                 * Scale points with window scaling and translate them
+                 */
+                tempX = net->start_x + sr_x;
+                tempY = net->start_y + sr_y;
+                cairo_matrix_transform_point(&fullMatrix, &tempX, &tempY);
+                xlong1 = (int)round(tempX);
+                ylong1 = (int)round(tempY);
+
+                tempX = net->stop_x + sr_x;
+                tempY = net->stop_y + sr_y;
+                cairo_matrix_transform_point(&fullMatrix, &tempX, &tempY);
+                xlong2 = (int)round(tempX);
+                ylong2 = (int)round(tempY);
+
+                /* if the object is way outside our view window, just skip over it in order
+                   to eliminate some GDK clipping problems at high zoom levels */
+                if ((xlong1 < -10000) && (xlong2 < -10000))
+                    continue;
+                if ((ylong1 < -10000) && (ylong2 < -10000))
+                    continue;
+                if ((xlong1 > 10000) && (xlong2 > 10000))
+                    continue;
+                if ((ylong1 > 10000) && (ylong2 > 10000))
+                    continue;
+
+                if (xlong1 > G_MAXINT)
+                    x1 = G_MAXINT;
+                else if (xlong1 < G_MININT)
+                    x1 = G_MININT;
+                else
+                    x1 = (int)xlong1;
+
+                if (xlong2 > G_MAXINT)
+                    x2 = G_MAXINT;
+                else if (xlong2 < G_MININT)
+                    x2 = G_MININT;
+                else
+                    x2 = (int)xlong2;
+
+                if (ylong1 > G_MAXINT)
+                    y1 = G_MAXINT;
+                else if (ylong1 < G_MININT)
+                    y1 = G_MININT;
+                else
+                    y1 = (int)ylong1;
+
+                if (ylong2 > G_MAXINT)
+                    y2 = G_MAXINT;
+                else if (ylong2 < G_MININT)
+                    y2 = G_MININT;
+                else
+                    y2 = (int)ylong2;
+
+                switch (net->aperture_state) {
+                    case GERBV_APERTURE_STATE_ON:
+                        tempX = image->aperture[net->aperture]->parameter[0];
+                        cairo_matrix_transform_point(&scaleMatrix, &tempX, &tempY);
+
+                        /* Variables can be negative after transformation */
+                        tempX = fabs(tempX);
+                        p1    = (int)round(tempX);
+
+                        gdk_gc_set_line_attributes(
+                            gc, p1, GDK_LINE_SOLID,
+                            (image->aperture[net->aperture]->type == GERBV_APTYPE_RECTANGLE) ? GDK_CAP_PROJECTING
+                                                                                             : GDK_CAP_ROUND,
+                            GDK_JOIN_MITER
+                        );
+
+                        switch (net->interpolation) {
+                            case GERBV_INTERPOLATION_LINEARx10:
+                            case GERBV_INTERPOLATION_LINEARx01:
+                            case GERBV_INTERPOLATION_LINEARx001:
+                                GERB_MESSAGE(_("Linear != x1"));
+                                gdk_gc_set_line_attributes(gc, p1, GDK_LINE_ON_OFF_DASH, GDK_CAP_ROUND, GDK_JOIN_MITER);
+                                gdk_draw_line(*pixmap, gc, x1, y1, x2, y2);
+                                gdk_gc_set_line_attributes(gc, p1, GDK_LINE_SOLID, GDK_CAP_ROUND, GDK_JOIN_MITER);
+                                break;
+                            case GERBV_INTERPOLATION_LINEARx1:
+                                if (image->aperture[net->aperture]->type != GERBV_APTYPE_RECTANGLE) {
+                                    gdk_draw_line(*pixmap, gc, x1, y1, x2, y2);
+
+                                    if (renderInfo->show_cross_on_drill_holes
+                                        && image->layertype == GERBV_LAYERTYPE_DRILL) {
+                                        /* Draw crosses on drill slot start and end */
+                                        r = p1 / 2.0 + hole_cross_inc_px;
+                                        draw_gdk_cross(*pixmap, gc, x1, y1, r);
+                                        draw_gdk_cross(*pixmap, gc, x2, y2, r);
+                                    }
+                                    break;
+                                }
+
+                                gint     dx, dy;
+                                GdkPoint poly[6];
+
+                                tempX = image->aperture[net->aperture]->parameter[0] / 2;
+                                tempY = image->aperture[net->aperture]->parameter[1] / 2;
+                                cairo_matrix_transform_point(&scaleMatrix, &tempX, &tempY);
+                                dx = (int)round(tempX);
+                                dy = (int)round(tempY);
+
+                                if (x1 > x2)
+                                    dx = -dx;
+                                if (y1 > y2)
+                                    dy = -dy;
+                                poly[0].x = x1 - dx;
+                                poly[0].y = y1 - dy;
+                                poly[1].x = x1 - dx;
+                                poly[1].y = y1 + dy;
+                                poly[2].x = x2 - dx;
+                                poly[2].y = y2 + dy;
+                                poly[3].x = x2 + dx;
+                                poly[3].y = y2 + dy;
+                                poly[4].x = x2 + dx;
+                                poly[4].y = y2 - dy;
+                                poly[5].x = x1 + dx;
+                                poly[5].y = y1 - dy;
+                                gdk_draw_polygon(*pixmap, gc, 1, poly, 6);
+                                break;
+
+                            case GERBV_INTERPOLATION_CW_CIRCULAR:
+                            case GERBV_INTERPOLATION_CCW_CIRCULAR:
+                                gerbv_gdk_draw_arc(
+                                    *pixmap, gc, cp_x, cp_y, cir_width, cir_height,
+                                    net->cirseg->angle1 + RAD2DEG(transform.rotation),
+                                    net->cirseg->angle2 + RAD2DEG(transform.rotation)
+                                );
+                                break;
+                            default:
+                                GERB_COMPILE_WARNING(_("Skipped interpolation type %d"), net->interpolation);
+                                break;
+                        }
+                        break;
+                    case GERBV_APERTURE_STATE_OFF: break;
+                    case GERBV_APERTURE_STATE_FLASH:
+                        tempX = image->aperture[net->aperture]->parameter[0];
+                        tempY = image->aperture[net->aperture]->parameter[1];
+                        cairo_matrix_transform_point(&scaleMatrix, &tempX, &tempY);
+
+                        /* Variables can be negative after transformation */
+                        tempX = fabs(tempX);
+                        tempY = fabs(tempY);
+                        p1    = (int)round(tempX);
+                        p2    = (int)round(tempY);
+
+                        switch (image->aperture[net->aperture]->type) {
+                            case GERBV_APTYPE_CIRCLE:
+                                gerbv_gdk_draw_circle(*pixmap, gc, TRUE, x2, y2, p1);
+
+                                if (renderInfo->show_cross_on_drill_holes
+                                    && image->layertype == GERBV_LAYERTYPE_DRILL) {
+                                    r = p1 / 2.0 + hole_cross_inc_px;
+                                    draw_gdk_cross(*pixmap, gc, x2, y2, r);
+                                }
+
+                                /*
+                                 * If circle has an inner diameter we must remove
+                                 * that part of the circle to make a hole in it.
+                                 * We should actually support square holes too,
+                                 * but due to laziness I don't.
+                                 */
+                                if (p2) {
+                                    gdk_gc_get_values(gc, &gc_values);
+                                    if (gc_values.foreground.pixel == opaque.pixel) {
+                                        gdk_gc_set_foreground(gc, &transparent);
+                                        gerbv_gdk_draw_circle(*pixmap, gc, TRUE, x2, y2, p2);
+                                        gdk_gc_set_foreground(gc, &opaque);
+                                    } else {
+                                        gdk_gc_set_foreground(gc, &opaque);
+                                        gerbv_gdk_draw_circle(*pixmap, gc, TRUE, x2, y2, p2);
+                                        gdk_gc_set_foreground(gc, &transparent);
+                                    }
+                                }
+
+                                break;
+                            case GERBV_APTYPE_RECTANGLE:
+                                gerbv_gdk_draw_rectangle(
+                                    *pixmap, gc, TRUE, x2, y2, p1, p2,
+                                    RAD2DEG(transform.rotation + image->info->imageRotation)
+                                );
+                                break;
+                            case GERBV_APTYPE_OVAL:
+                                gerbv_gdk_draw_oval(
+                                    *pixmap, gc, TRUE, x2, y2, p1, p2,
+                                    RAD2DEG(transform.rotation + image->info->imageRotation)
+                                );
+                                break;
+                            case GERBV_APTYPE_POLYGON:
+                                /* TODO: gdk_draw_polygon() */
+                                gerbv_gdk_draw_circle(*pixmap, gc, TRUE, x2, y2, p1);
+                                break;
+                            case GERBV_APTYPE_MACRO:
+                                /* TODO: check line22 and others */
+                                gerbv_gdk_draw_amacro(
+                                    *pixmap, gc, image->aperture[net->aperture]->simplified, scale, x2, y2
+                                );
+                                break;
+                            default:
+                                GERB_MESSAGE(_("Unknown aperture type %d"), image->aperture[net->aperture]->type);
+                                return 0;
+                        }
+                        break;
+                    default: GERB_MESSAGE(_("Unknown aperture state %d"), net->aperture_state); return 0;
+                }
+            }
+        }
+    }
+    /*
+     * Destroy GCs before exiting
+     */
+    gdk_gc_unref(gc);
+    gdk_gc_unref(pgc);
 
+    return 1;
+
+} /* image2pixmap */
diff --git a/src/draw-gdk.h b/src/draw-gdk.h
index a6a5f3a..1109021 100644
--- a/src/draw-gdk.h
+++ b/src/draw-gdk.h
@@ -32,17 +32,14 @@
 #include <gdk/gdk.h>
 
 /* Default mouse cursor. Perhaps redefine this to a variable later? */
-#define GERBV_DEF_CURSOR	NULL
+#define GERBV_DEF_CURSOR NULL
 
 /*
  * Convert a gerber image to a GDK clip mask to be used when creating pixmap
  */
-int draw_gdk_image_to_pixmap(GdkPixmap **pixmap, gerbv_image_t *image,
-		double scale, double trans_x, double trans_y,
-		enum draw_mode drawMode,
-		gerbv_selection_info_t *selectionInfo,
-		gerbv_render_info_t *renderInfo,
-		gerbv_user_transformation_t transform);
+int draw_gdk_image_to_pixmap(
+    GdkPixmap** pixmap, gerbv_image_t* image, double scale, double trans_x, double trans_y, enum draw_mode drawMode,
+    gerbv_selection_info_t* selectionInfo, gerbv_render_info_t* renderInfo, gerbv_user_transformation_t transform
+);
 
 #endif /* DRAW_GDK_H */
-
diff --git a/src/draw.c b/src/draw.c
index fd5d9ac..ae8e613 100644
--- a/src/draw.c
+++ b/src/draw.c
@@ -28,10 +28,10 @@
 
 #include <stdio.h>
 #include <stdlib.h>
-#include <math.h>  /* ceil(), atan2() */
+#include <math.h> /* ceil(), atan2() */
 
 #ifdef HAVE_STRING_H
-# include <string.h>
+#include <string.h>
 #endif
 
 #include "gerbv.h"
@@ -39,10 +39,11 @@
 #include "common.h"
 #include "selection.h"
 
-#define dprintf if(DEBUG) printf
+#define dprintf \
+    if (DEBUG)  \
+    printf
 
-static gboolean draw_do_vector_export_fix(cairo_t *cairoTarget,
-		double *bg_red, double *bg_green, double *bg_blue);
+static gboolean draw_do_vector_export_fix(cairo_t* cairoTarget, double* bg_red, double* bg_green, double* bg_blue);
 
 /** Draw Cairo line from current coordinates.
   @param x	End of line x coordinate.
@@ -51,20 +52,18 @@ static gboolean draw_do_vector_export_fix(cairo_t *cairoTarget,
   @param pixelOutput	Round x and y coordinates to pixels.
 */
 void
-draw_cairo_line_to (cairo_t *cairoTarget, gdouble x, gdouble y,
-			gboolean adjustByHalf, gboolean pixelOutput)
-{
-	if (pixelOutput) {
-		cairo_user_to_device (cairoTarget, &x, &y);
-		x = round(x);
-		y = round(y);
-		if (adjustByHalf) {
-			x += 0.5;
-			y += 0.5;
-		}
-		cairo_device_to_user (cairoTarget, &x, &y);
-	}
-	cairo_line_to (cairoTarget, x, y);
+draw_cairo_line_to(cairo_t* cairoTarget, gdouble x, gdouble y, gboolean adjustByHalf, gboolean pixelOutput) {
+    if (pixelOutput) {
+        cairo_user_to_device(cairoTarget, &x, &y);
+        x = round(x);
+        y = round(y);
+        if (adjustByHalf) {
+            x += 0.5;
+            y += 0.5;
+        }
+        cairo_device_to_user(cairoTarget, &x, &y);
+    }
+    cairo_line_to(cairoTarget, x, y);
 }
 
 /** Move Cairo coordinates.
@@ -74,20 +73,18 @@ draw_cairo_line_to (cairo_t *cairoTarget, gdouble x, gdouble y,
   @param pixelOutput	Round x and y coordinates to pixels.
 */
 void
-draw_cairo_move_to (cairo_t *cairoTarget, gdouble x, gdouble y,
-			gboolean oddWidth, gboolean pixelOutput)
-{
-	if (pixelOutput) {
-		cairo_user_to_device (cairoTarget, &x, &y);
-		x = round(x);
-		y = round(y);
-		if (oddWidth) {
-			x += 0.5;
-			y += 0.5;
-		}
-		cairo_device_to_user (cairoTarget, &x, &y);
-	}
-	cairo_move_to (cairoTarget, x, y);
+draw_cairo_move_to(cairo_t* cairoTarget, gdouble x, gdouble y, gboolean oddWidth, gboolean pixelOutput) {
+    if (pixelOutput) {
+        cairo_user_to_device(cairoTarget, &x, &y);
+        x = round(x);
+        y = round(y);
+        if (oddWidth) {
+            x += 0.5;
+            y += 0.5;
+        }
+        cairo_device_to_user(cairoTarget, &x, &y);
+    }
+    cairo_move_to(cairoTarget, x, y);
 }
 
 /** Cairo translate user-space origin.
@@ -96,17 +93,15 @@ draw_cairo_move_to (cairo_t *cairoTarget, gdouble x, gdouble y,
   @param pixelOutput	Round x and y coordinates to pixels.
 */
 void
-draw_cairo_translate_adjust (cairo_t *cairoTarget, gdouble x, gdouble y,
-				gboolean pixelOutput)
-{
-	if (pixelOutput) {
-		cairo_user_to_device (cairoTarget, &x, &y);
-		x = round(x);
-		y = round(y);
-		cairo_device_to_user (cairoTarget, &x, &y);
-	}
-
-	cairo_translate (cairoTarget, x, y);
+draw_cairo_translate_adjust(cairo_t* cairoTarget, gdouble x, gdouble y, gboolean pixelOutput) {
+    if (pixelOutput) {
+        cairo_user_to_device(cairoTarget, &x, &y);
+        x = round(x);
+        y = round(y);
+        cairo_device_to_user(cairoTarget, &x, &y);
+    }
+
+    cairo_translate(cairoTarget, x, y);
 }
 
 /** Check if net is in selection buffer and possibly deselect it.
@@ -116,122 +111,111 @@ draw_cairo_translate_adjust (cairo_t *cairoTarget, gdouble x, gdouble y,
   @param remove		TRUE for deselect net.
  */
 static gboolean
-draw_net_is_in_selection_buffer_remove (gerbv_net_t *net,
-		gerbv_selection_info_t *selectionInfo, gboolean remove)
-{
-	gerbv_selection_item_t sItem;
-
-	for (guint i = 0; i < selection_length (selectionInfo); i++) {
-		sItem = selection_get_item_by_index (selectionInfo, i);
-		if (sItem.net == net) {
-			if (remove)
-				selection_clear_item_by_index (selectionInfo, i);
-
-			return TRUE;
-		}
-	}
-
-	return FALSE;
+draw_net_is_in_selection_buffer_remove(gerbv_net_t* net, gerbv_selection_info_t* selectionInfo, gboolean remove) {
+    gerbv_selection_item_t sItem;
+
+    for (guint i = 0; i < selection_length(selectionInfo); i++) {
+        sItem = selection_get_item_by_index(selectionInfo, i);
+        if (sItem.net == net) {
+            if (remove)
+                selection_clear_item_by_index(selectionInfo, i);
+
+            return TRUE;
+        }
+    }
+
+    return FALSE;
 }
 
 static void
-draw_check_if_object_is_in_selected_area (cairo_t *cairoTarget,
-		gboolean isStroke, gerbv_selection_info_t *selectionInfo,
-		gerbv_image_t *image, struct gerbv_net *net,
-		enum draw_mode drawMode)
-{
-	gerbv_selection_item_t sItem = {image, net};
-	gdouble corner1X, corner1Y, corner2X, corner2Y;
-	gdouble x1, x2, y1, y2;
-	gdouble minX, minY, maxX, maxY;
-
-	corner1X = selectionInfo->lowerLeftX;
-	corner1Y = selectionInfo->lowerLeftY;
-	corner2X = selectionInfo->upperRightX;
-	corner2Y = selectionInfo->upperRightY;
-
-	/* calculate the coordinate of the user's click in the current
-	   transformation matrix */
-	cairo_device_to_user (cairoTarget, &corner1X, &corner1Y);
-	cairo_device_to_user (cairoTarget, &corner2X, &corner2Y);
-
-	switch (selectionInfo->type) {
-	case GERBV_SELECTION_POINT_CLICK:
-		/* use the cairo in_fill routine to see if the point is within the
-		   drawn area */
-		if ((isStroke && cairo_in_stroke (cairoTarget, corner1X, corner1Y)) ||
-			(!isStroke && cairo_in_fill (cairoTarget, corner1X, corner1Y))) {
-
-			if (!draw_net_is_in_selection_buffer_remove (net,
-					selectionInfo,
-					(drawMode == FIND_SELECTIONS_TOGGLE))) {
-				selection_add_item (selectionInfo, &sItem);
-			}
-		}
-		break;
-
-	case GERBV_SELECTION_DRAG_BOX:
-		/* we can't assume the "lowerleft" corner is actually in the lower left,
-		   since the cairo transformation matrix may be mirrored,etc */
-		minX = MIN(corner1X,corner2X);
-		maxX = MAX(corner1X,corner2X);
-		minY = MIN(corner1Y,corner2Y);
-		maxY = MAX(corner1Y,corner2Y);
-
-		if (isStroke)
-			cairo_stroke_extents (cairoTarget, &x1, &y1, &x2, &y2);
-		else
-			cairo_fill_extents (cairoTarget, &x1, &y1, &x2, &y2);
-
-		if ((minX < x1) && (minY < y1) && (maxX > x2) && (maxY > y2)) {
-			if (!draw_net_is_in_selection_buffer_remove (net,
-					selectionInfo,
-					(drawMode == FIND_SELECTIONS_TOGGLE))) {
-				selection_add_item (selectionInfo, &sItem);
-			}
-		}
-		break;
-	default:
-		break;
-	}
-	/* clear the path, since we didn't actually draw it and cairo
-		 doesn't reset it after the previous calls */
-	cairo_new_path (cairoTarget);
+draw_check_if_object_is_in_selected_area(
+    cairo_t* cairoTarget, gboolean isStroke, gerbv_selection_info_t* selectionInfo, gerbv_image_t* image,
+    struct gerbv_net* net, enum draw_mode drawMode
+) {
+    gerbv_selection_item_t sItem = { image, net };
+    gdouble                corner1X, corner1Y, corner2X, corner2Y;
+    gdouble                x1, x2, y1, y2;
+    gdouble                minX, minY, maxX, maxY;
+
+    corner1X = selectionInfo->lowerLeftX;
+    corner1Y = selectionInfo->lowerLeftY;
+    corner2X = selectionInfo->upperRightX;
+    corner2Y = selectionInfo->upperRightY;
+
+    /* calculate the coordinate of the user's click in the current
+       transformation matrix */
+    cairo_device_to_user(cairoTarget, &corner1X, &corner1Y);
+    cairo_device_to_user(cairoTarget, &corner2X, &corner2Y);
+
+    switch (selectionInfo->type) {
+        case GERBV_SELECTION_POINT_CLICK:
+            /* use the cairo in_fill routine to see if the point is within the
+               drawn area */
+            if ((isStroke && cairo_in_stroke(cairoTarget, corner1X, corner1Y))
+                || (!isStroke && cairo_in_fill(cairoTarget, corner1X, corner1Y))) {
+
+                if (!draw_net_is_in_selection_buffer_remove(net, selectionInfo, (drawMode == FIND_SELECTIONS_TOGGLE))) {
+                    selection_add_item(selectionInfo, &sItem);
+                }
+            }
+            break;
+
+        case GERBV_SELECTION_DRAG_BOX:
+            /* we can't assume the "lowerleft" corner is actually in the lower left,
+               since the cairo transformation matrix may be mirrored,etc */
+            minX = MIN(corner1X, corner2X);
+            maxX = MAX(corner1X, corner2X);
+            minY = MIN(corner1Y, corner2Y);
+            maxY = MAX(corner1Y, corner2Y);
+
+            if (isStroke)
+                cairo_stroke_extents(cairoTarget, &x1, &y1, &x2, &y2);
+            else
+                cairo_fill_extents(cairoTarget, &x1, &y1, &x2, &y2);
+
+            if ((minX < x1) && (minY < y1) && (maxX > x2) && (maxY > y2)) {
+                if (!draw_net_is_in_selection_buffer_remove(net, selectionInfo, (drawMode == FIND_SELECTIONS_TOGGLE))) {
+                    selection_add_item(selectionInfo, &sItem);
+                }
+            }
+            break;
+        default: break;
+    }
+    /* clear the path, since we didn't actually draw it and cairo
+         doesn't reset it after the previous calls */
+    cairo_new_path(cairoTarget);
 }
 
 static void
-draw_fill (cairo_t *cairoTarget, enum draw_mode drawMode,
-		gerbv_selection_info_t *selectionInfo,
-		gerbv_image_t *image, struct gerbv_net *net)
-{
-	if ((drawMode == DRAW_IMAGE) || (drawMode == DRAW_SELECTIONS))
-		cairo_fill (cairoTarget);
-	else
-		draw_check_if_object_is_in_selected_area (cairoTarget, FALSE,
-			selectionInfo, image, net, drawMode);
+draw_fill(
+    cairo_t* cairoTarget, enum draw_mode drawMode, gerbv_selection_info_t* selectionInfo, gerbv_image_t* image,
+    struct gerbv_net* net
+) {
+    if ((drawMode == DRAW_IMAGE) || (drawMode == DRAW_SELECTIONS))
+        cairo_fill(cairoTarget);
+    else
+        draw_check_if_object_is_in_selected_area(cairoTarget, FALSE, selectionInfo, image, net, drawMode);
 }
 
 static void
-draw_stroke (cairo_t *cairoTarget, enum draw_mode drawMode,
-		gerbv_selection_info_t *selectionInfo,
-		gerbv_image_t *image, struct gerbv_net *net)
-{
-	if ((drawMode == DRAW_IMAGE) || (drawMode == DRAW_SELECTIONS))
-		cairo_stroke (cairoTarget);
-	else
-		draw_check_if_object_is_in_selected_area (cairoTarget, TRUE,
-			selectionInfo, image, net, drawMode);
+draw_stroke(
+    cairo_t* cairoTarget, enum draw_mode drawMode, gerbv_selection_info_t* selectionInfo, gerbv_image_t* image,
+    struct gerbv_net* net
+) {
+    if ((drawMode == DRAW_IMAGE) || (drawMode == DRAW_SELECTIONS))
+        cairo_stroke(cairoTarget);
+    else
+        draw_check_if_object_is_in_selected_area(cairoTarget, TRUE, selectionInfo, image, net, drawMode);
 }
 
 /** Draw the circle _centered_ at current Cairo coordinates.
   @param diameter	Circle diameter.
  */
 static void
-gerbv_draw_circle(cairo_t *cairoTarget, gdouble diameter)
-{
-	cairo_arc (cairoTarget, 0.0, 0.0, diameter/2.0, 0, 2.0*M_PI);
+gerbv_draw_circle(cairo_t* cairoTarget, gdouble diameter) {
+    cairo_arc(cairoTarget, 0.0, 0.0, diameter / 2.0, 0, 2.0 * M_PI);
 
-	return;
+    return;
 }
 
 /** Draw the rectangle _centered_ at current Cairo coordinates.
@@ -240,19 +224,17 @@ gerbv_draw_circle(cairo_t *cairoTarget, gdouble diameter)
   @param pixelOutput	Round width and height to pixels.
  */
 static void
-gerbv_draw_rectangle(cairo_t *cairoTarget, gdouble width, gdouble height,
-			gboolean pixelOutput)
-{
-	if (pixelOutput) {
-		cairo_user_to_device_distance (cairoTarget, &width, &height);
-		width  -= (int)round(width)  % 2;
-		height -= (int)round(height) % 2;
-		cairo_device_to_user_distance (cairoTarget, &width, &height);
-	}
-
-	cairo_rectangle (cairoTarget, -width/2.0, -height/2.0, width, height);
-
-	return;
+gerbv_draw_rectangle(cairo_t* cairoTarget, gdouble width, gdouble height, gboolean pixelOutput) {
+    if (pixelOutput) {
+        cairo_user_to_device_distance(cairoTarget, &width, &height);
+        width -= (int)round(width) % 2;
+        height -= (int)round(height) % 2;
+        cairo_device_to_user_distance(cairoTarget, &width, &height);
+    }
+
+    cairo_rectangle(cairoTarget, -width / 2.0, -height / 2.0, width, height);
+
+    return;
 }
 
 /** Draw the oblong _centered_ at current Cairo coordinates.
@@ -260,31 +242,26 @@ gerbv_draw_rectangle(cairo_t *cairoTarget, gdouble width, gdouble height,
   @param height	Height of the oblong.
  */
 static void
-gerbv_draw_oblong(cairo_t *cairoTarget, gdouble width, gdouble height)
-{
-	/* --- This stuff produces a line + rounded ends --- */
-	gdouble circleDiameter, strokeDistance;
-
-	cairo_new_path (cairoTarget);
-	if (width < height) {
-		circleDiameter = width;
-		strokeDistance = (height - width)/2.0;
-		cairo_arc (cairoTarget, 0.0, strokeDistance, circleDiameter/2.0, 0, -M_PI);
-		cairo_line_to (cairoTarget, -circleDiameter/2.0, -strokeDistance);
-		cairo_arc (cairoTarget, 0.0, -strokeDistance, circleDiameter/2.0, -M_PI, 0);
-		cairo_line_to (cairoTarget, circleDiameter/2.0, strokeDistance);
-	} else {
-		circleDiameter = height;
-		strokeDistance = (width - height)/2.0;
-		cairo_arc (cairoTarget, -strokeDistance, 0.0,
-				circleDiameter/2.0, M_PI_2, -M_PI_2);
-		cairo_line_to (cairoTarget, strokeDistance,
-				-circleDiameter/2.0);
-		cairo_arc (cairoTarget, strokeDistance, 0.0,
-				circleDiameter/2.0, -M_PI_2, M_PI_2);
-		cairo_line_to (cairoTarget, -strokeDistance,
-				circleDiameter/2.0);
-	}
+gerbv_draw_oblong(cairo_t* cairoTarget, gdouble width, gdouble height) {
+    /* --- This stuff produces a line + rounded ends --- */
+    gdouble circleDiameter, strokeDistance;
+
+    cairo_new_path(cairoTarget);
+    if (width < height) {
+        circleDiameter = width;
+        strokeDistance = (height - width) / 2.0;
+        cairo_arc(cairoTarget, 0.0, strokeDistance, circleDiameter / 2.0, 0, -M_PI);
+        cairo_line_to(cairoTarget, -circleDiameter / 2.0, -strokeDistance);
+        cairo_arc(cairoTarget, 0.0, -strokeDistance, circleDiameter / 2.0, -M_PI, 0);
+        cairo_line_to(cairoTarget, circleDiameter / 2.0, strokeDistance);
+    } else {
+        circleDiameter = height;
+        strokeDistance = (width - height) / 2.0;
+        cairo_arc(cairoTarget, -strokeDistance, 0.0, circleDiameter / 2.0, M_PI_2, -M_PI_2);
+        cairo_line_to(cairoTarget, strokeDistance, -circleDiameter / 2.0);
+        cairo_arc(cairoTarget, strokeDistance, 0.0, circleDiameter / 2.0, -M_PI_2, M_PI_2);
+        cairo_line_to(cairoTarget, -strokeDistance, circleDiameter / 2.0);
+    }
 
 #if 0
 	/*  --- This stuff produces an oval pad --- */
@@ -295,564 +272,432 @@ gerbv_draw_oblong(cairo_t *cairoTarget, gdouble width, gdouble height)
 	gerbv_draw_circle (cairoTarget, 1);
 	cairo_restore (cairoTarget);
 #endif
-	return;
+    return;
 }
 
 static void
-gerbv_draw_polygon(cairo_t *cairoTarget, gdouble outsideDiameter,
-		gdouble numberOfSides, gdouble degreesOfRotation)
-{
-	int i, numberOfSidesInteger = (int) numberOfSides;
-
-	cairo_rotate(cairoTarget, DEG2RAD(degreesOfRotation));
-	cairo_move_to(cairoTarget, outsideDiameter / 2.0, 0);
-
-	/* skip first point, since we've moved there already */
-	/* include last point, since we may be drawing an aperture hole next
-	   and cairo may not correctly close the path itself */
-	for (i = 1; i <= (int)numberOfSidesInteger; i++){
-	    gdouble angle = ((double)i)*M_PI*2.0 / numberOfSidesInteger;
-	    cairo_line_to (cairoTarget, cos(angle) * outsideDiameter / 2.0,
-		       sin(angle) * outsideDiameter / 2.0);
-	}
-
-	return;
-}
+gerbv_draw_polygon(cairo_t* cairoTarget, gdouble outsideDiameter, gdouble numberOfSides, gdouble degreesOfRotation) {
+    int i, numberOfSidesInteger = (int)numberOfSides;
 
+    cairo_rotate(cairoTarget, DEG2RAD(degreesOfRotation));
+    cairo_move_to(cairoTarget, outsideDiameter / 2.0, 0);
 
-static void
-gerbv_draw_aperture_hole(cairo_t *cairoTarget,
-		gdouble dimensionX, gdouble dimensionY, gboolean pixelOutput)
-{
-	if (dimensionX) {
-		if (dimensionY)
-			gerbv_draw_rectangle (cairoTarget,
-					dimensionX, dimensionY, pixelOutput);
-		else
-			gerbv_draw_circle (cairoTarget, dimensionX);
-	}
-
-	return;
+    /* skip first point, since we've moved there already */
+    /* include last point, since we may be drawing an aperture hole next
+       and cairo may not correctly close the path itself */
+    for (i = 1; i <= (int)numberOfSidesInteger; i++) {
+        gdouble angle = ((double)i) * M_PI * 2.0 / numberOfSidesInteger;
+        cairo_line_to(cairoTarget, cos(angle) * outsideDiameter / 2.0, sin(angle) * outsideDiameter / 2.0);
+    }
+
+    return;
 }
 
 static void
-draw_update_macro_exposure (cairo_t *cairoTarget, cairo_operator_t clearOperator,
-		cairo_operator_t darkOperator, gdouble exposureSetting){
-
-	if (exposureSetting == 0.0) {
-		cairo_set_operator (cairoTarget, clearOperator);
-	} else if (exposureSetting == 1.0) {
-		cairo_set_operator (cairoTarget, darkOperator);
-	} else if (exposureSetting == 2.0) {
-		/* reverse current exposure setting */
-		cairo_operator_t currentOperator = cairo_get_operator (cairoTarget);
-		if (currentOperator == clearOperator) {
-			cairo_set_operator (cairoTarget, darkOperator);
-		} else {
-			cairo_set_operator (cairoTarget, clearOperator);
-		}
-	}
+gerbv_draw_aperture_hole(cairo_t* cairoTarget, gdouble dimensionX, gdouble dimensionY, gboolean pixelOutput) {
+    if (dimensionX) {
+        if (dimensionY)
+            gerbv_draw_rectangle(cairoTarget, dimensionX, dimensionY, pixelOutput);
+        else
+            gerbv_draw_circle(cairoTarget, dimensionX);
+    }
+
+    return;
 }
 
+static void
+draw_update_macro_exposure(
+    cairo_t* cairoTarget, cairo_operator_t clearOperator, cairo_operator_t darkOperator, gdouble exposureSetting
+) {
+
+    if (exposureSetting == 0.0) {
+        cairo_set_operator(cairoTarget, clearOperator);
+    } else if (exposureSetting == 1.0) {
+        cairo_set_operator(cairoTarget, darkOperator);
+    } else if (exposureSetting == 2.0) {
+        /* reverse current exposure setting */
+        cairo_operator_t currentOperator = cairo_get_operator(cairoTarget);
+        if (currentOperator == clearOperator) {
+            cairo_set_operator(cairoTarget, darkOperator);
+        } else {
+            cairo_set_operator(cairoTarget, clearOperator);
+        }
+    }
+}
 
 static int
-gerbv_draw_amacro(cairo_t *cairoTarget, cairo_operator_t clearOperator,
-	cairo_operator_t darkOperator, gerbv_simplified_amacro_t *s,
-	gint usesClearPrimitive, gdouble pixelWidth, enum draw_mode drawMode,
-	gerbv_selection_info_t *selectionInfo,
-	gerbv_image_t *image, struct gerbv_net *net)
-{
-	gerbv_simplified_amacro_t *ls = s;
-	gboolean doVectorExportFix;
-	double bg_r, bg_g, bg_b; /* Background color */
-	int ret = 1;
-
-	dprintf("Drawing simplified aperture macros:\n");
-
-	doVectorExportFix =
-		draw_do_vector_export_fix (cairoTarget, &bg_r, &bg_g, &bg_b);
-
-	switch (cairo_surface_get_type (cairo_get_target (cairoTarget))) {
-
-	case CAIRO_SURFACE_TYPE_PDF:
-	case CAIRO_SURFACE_TYPE_PS:
-	case CAIRO_SURFACE_TYPE_SVG:
-
-		/* Don't limit "pixel width" in vector export */
-		pixelWidth = DBL_MIN;
-
-		break;
-
-	default:
-		break;
-	}
-
-	if (usesClearPrimitive)
-		cairo_push_group (cairoTarget);
-
-	while (ls != NULL) {
-		/* 
-		 * This handles the exposure thing in the aperture macro
-		 * The exposure is always the first element on stack independent
-		 * of aperture macro.
-		 */
-		cairo_save (cairoTarget);
-		cairo_new_path(cairoTarget);
-
-		dprintf("\t%s(): drawing %s\n", __FUNCTION__,
-				gerbv_aperture_type_name(ls->type));
-
-		switch (ls->type) {
-
-		case GERBV_APTYPE_MACRO_CIRCLE:
-			draw_update_macro_exposure (cairoTarget,
-					clearOperator, darkOperator,
-					ls->parameter[CIRCLE_EXPOSURE]);
-			cairo_translate (cairoTarget,
-					ls->parameter[CIRCLE_CENTER_X],
-					ls->parameter[CIRCLE_CENTER_Y]);
-			gerbv_draw_circle (cairoTarget,
-					ls->parameter[CIRCLE_DIAMETER]);
-
-			if (doVectorExportFix
-			&& CAIRO_OPERATOR_CLEAR ==
-					cairo_get_operator (cairoTarget)) {
-				cairo_save (cairoTarget);
-				cairo_set_source_rgba (cairoTarget,
-						bg_r, bg_g, bg_b, 1.0);
-				cairo_set_operator (cairoTarget,
-						CAIRO_OPERATOR_OVER);
-
-				draw_fill (cairoTarget, drawMode,
-						selectionInfo, image, net);
-
-				cairo_restore (cairoTarget);
-
-				break;
-			}
-
-			draw_fill (cairoTarget, drawMode,
-					selectionInfo, image, net);
-			break;
-
-		case GERBV_APTYPE_MACRO_OUTLINE:
-			draw_update_macro_exposure (cairoTarget,
-					clearOperator, darkOperator,
-					ls->parameter[OUTLINE_EXPOSURE]);
-			cairo_rotate (cairoTarget, DEG2RAD(ls->parameter[
-					OUTLINE_ROTATION_IDX(ls->parameter)]));
-			cairo_move_to (cairoTarget,
-					ls->parameter[OUTLINE_FIRST_X],
-					ls->parameter[OUTLINE_FIRST_Y]);
-
-			for (int point = 1; point < 
-					1 + (int)ls->parameter[
-						OUTLINE_NUMBER_OF_POINTS];
-								point++) {
-				cairo_line_to (cairoTarget,
-					ls->parameter[OUTLINE_X_IDX_OF_POINT(
-								point)],
-					ls->parameter[OUTLINE_Y_IDX_OF_POINT(
-								point)]);
-			}
-
-			if (doVectorExportFix
-			&& CAIRO_OPERATOR_CLEAR ==
-					cairo_get_operator (cairoTarget)) {
-				cairo_save (cairoTarget);
-				cairo_set_source_rgba (cairoTarget,
-						bg_r, bg_g, bg_b, 1.0);
-				cairo_set_operator (cairoTarget,
-						CAIRO_OPERATOR_OVER);
-
-				draw_fill (cairoTarget, drawMode,
-						selectionInfo, image, net);
-
-				cairo_restore (cairoTarget);
-
-				break;
-			}
-
-			/* Although the gerber specs allow for an open outline,
-			 * I interpret it to mean the outline should be closed
-			 * by the rendering softare automatically, since there
-			 * is no dimension for line thickness. */
-			draw_fill (cairoTarget, drawMode,
-					selectionInfo, image, net);
-			break;
-
-		case GERBV_APTYPE_MACRO_POLYGON:
-			draw_update_macro_exposure (cairoTarget,
-					clearOperator, darkOperator,
-					ls->parameter[POLYGON_EXPOSURE]);
-			cairo_translate (cairoTarget,
-					ls->parameter[POLYGON_CENTER_X],
-					ls->parameter[POLYGON_CENTER_Y]);
-			gerbv_draw_polygon(cairoTarget,
-					ls->parameter[POLYGON_DIAMETER],
-					ls->parameter[POLYGON_NUMBER_OF_POINTS],
-					ls->parameter[POLYGON_ROTATION]);
-
-			if (doVectorExportFix
-			&& CAIRO_OPERATOR_CLEAR ==
-					cairo_get_operator (cairoTarget)) {
-				cairo_save (cairoTarget);
-				cairo_set_source_rgba (cairoTarget,
-						bg_r, bg_g, bg_b, 1.0);
-				cairo_set_operator (cairoTarget,
-						CAIRO_OPERATOR_OVER);
-
-				draw_fill (cairoTarget, drawMode,
-						selectionInfo, image, net);
-
-				cairo_restore (cairoTarget);
-
-				break;
-			}
-
-			draw_fill (cairoTarget, drawMode,
-					selectionInfo, image, net);
-			break;
-
-		case GERBV_APTYPE_MACRO_MOIRE: {
-			gdouble diameter, diameterDifference, crosshairRadius;
-
-			cairo_translate (cairoTarget,
-					ls->parameter[MOIRE_CENTER_X],
-					ls->parameter[MOIRE_CENTER_Y]);
-			cairo_rotate (cairoTarget,
-					DEG2RAD(ls->parameter[MOIRE_ROTATION]));
-			diameter = ls->parameter[MOIRE_OUTSIDE_DIAMETER]
-				 - ls->parameter[MOIRE_CIRCLE_THICKNESS];
-			diameterDifference = 2*(ls->parameter[MOIRE_GAP_WIDTH]
-				+ ls->parameter[MOIRE_CIRCLE_THICKNESS]);
-			cairo_set_line_width (cairoTarget,
-					ls->parameter[MOIRE_CIRCLE_THICKNESS]);
-
-			if (doVectorExportFix
-			&& CAIRO_OPERATOR_CLEAR ==
-					cairo_get_operator (cairoTarget)) {
-				cairo_save (cairoTarget);
-				cairo_set_source_rgba (cairoTarget,
-						bg_r, bg_g, bg_b, 1.0);
-				cairo_set_operator (cairoTarget,
-						CAIRO_OPERATOR_OVER);
-			}
-
-			for (int circle = 0; circle < (int)ls->parameter[
-					MOIRE_NUMBER_OF_CIRCLES]; circle++) {
-				gdouble dia =
-					diameter - diameterDifference * circle;
-
-				if (dia <= 0) {
-					GERB_COMPILE_WARNING (_("Ignoring %s "
-						"with non positive diameter"),
-						gerbv_aperture_type_name (
-								ls->type));
-					continue;
-				}
-
-				gerbv_draw_circle (cairoTarget, dia);
-				draw_stroke (cairoTarget, drawMode,
-						selectionInfo, image, net);
-			}
-
-
-			cairo_set_line_width (cairoTarget,
-				ls->parameter[MOIRE_CROSSHAIR_THICKNESS]);
-			crosshairRadius =
-				ls->parameter[MOIRE_CROSSHAIR_LENGTH] / 2.0;
-			cairo_move_to (cairoTarget, -crosshairRadius, 0);
-			cairo_line_to (cairoTarget, crosshairRadius, 0);
-			cairo_move_to (cairoTarget, 0, -crosshairRadius);
-			cairo_line_to (cairoTarget, 0, crosshairRadius);
-
-			draw_stroke (cairoTarget, drawMode,
-					selectionInfo, image, net);
-
-			if (doVectorExportFix
-			&& CAIRO_OPERATOR_CLEAR ==
-					cairo_get_operator (cairoTarget)) {
-				cairo_restore (cairoTarget);
-			}
-
-			break;
-		}
-		case GERBV_APTYPE_MACRO_THERMAL: {
-			gdouble startAngle1, startAngle2, endAngle1, endAngle2;
-
-			cairo_translate (cairoTarget,
-					ls->parameter[THERMAL_CENTER_X],
-					ls->parameter[THERMAL_CENTER_Y]);
-			cairo_rotate (cairoTarget,
-				DEG2RAD(ls->parameter[THERMAL_ROTATION]));
-			startAngle1 = asin (
-				ls->parameter[THERMAL_CROSSHAIR_THICKNESS]/
-				ls->parameter[THERMAL_INSIDE_DIAMETER]);
-			endAngle1 = M_PI_2 - startAngle1;
-			endAngle2 = asin (
-				ls->parameter[THERMAL_CROSSHAIR_THICKNESS]/
-				ls->parameter[THERMAL_OUTSIDE_DIAMETER]);
-			startAngle2 = M_PI_2 - endAngle2;
-
-			if (doVectorExportFix
-			&& CAIRO_OPERATOR_CLEAR ==
-					cairo_get_operator (cairoTarget)) {
-				cairo_save (cairoTarget);
-				cairo_set_source_rgba (cairoTarget,
-						bg_r, bg_g, bg_b, 1.0);
-				cairo_set_operator (cairoTarget,
-						CAIRO_OPERATOR_OVER);
-
-				/* */
-
-				cairo_restore (cairoTarget);
-
-				break;
-			}
-
-			for (gint i = 0; i < 4; i++) {
-				cairo_arc (cairoTarget, 0, 0,
-						ls->parameter[
-						THERMAL_INSIDE_DIAMETER]/2.0,
-						startAngle1, endAngle1);
-				cairo_arc_negative (cairoTarget, 0, 0,
-						ls->parameter[
-						THERMAL_OUTSIDE_DIAMETER]/2.0,
-						startAngle2, endAngle2);
-				draw_fill (cairoTarget,
-						drawMode, selectionInfo,
-						image, net);
-				cairo_rotate (cairoTarget, M_PI_2);
-			}
-
-			break;
-		}
-		case GERBV_APTYPE_MACRO_LINE20:
-			draw_update_macro_exposure (cairoTarget,
-					clearOperator, darkOperator,
-					ls->parameter[LINE20_EXPOSURE]);
-			cairo_set_line_width (cairoTarget,
-					MAX(ls->parameter[LINE20_LINE_WIDTH],
-						pixelWidth));
-			cairo_set_line_cap (cairoTarget, CAIRO_LINE_CAP_BUTT);
-			cairo_rotate (cairoTarget, DEG2RAD(
-					ls->parameter[LINE20_ROTATION]));
-			cairo_move_to (cairoTarget,
-					ls->parameter[LINE20_START_X],
-					ls->parameter[LINE20_START_Y]);
-			cairo_line_to (cairoTarget,
-					ls->parameter[LINE20_END_X],
-					ls->parameter[LINE20_END_Y]);
-
-			if (doVectorExportFix
-			&& CAIRO_OPERATOR_CLEAR ==
-					cairo_get_operator (cairoTarget)) {
-				cairo_save (cairoTarget);
-				cairo_set_source_rgba (cairoTarget,
-						bg_r, bg_g, bg_b, 1.0);
-				cairo_set_operator (cairoTarget,
-						CAIRO_OPERATOR_OVER);
-
-				draw_stroke (cairoTarget, drawMode,
-						selectionInfo, image, net);
-
-				cairo_restore (cairoTarget);
-
-				break;
-			}
-
-			draw_stroke (cairoTarget, drawMode,
-					selectionInfo, image, net);
-			break;
-
-		case GERBV_APTYPE_MACRO_LINE21:
-			draw_update_macro_exposure (cairoTarget,
-					clearOperator, darkOperator,
-					ls->parameter[LINE21_EXPOSURE]);
-			cairo_rotate (cairoTarget, DEG2RAD(
-					ls->parameter[LINE21_ROTATION]));
-			cairo_translate (cairoTarget,
-					ls->parameter[LINE21_CENTER_X],
-					ls->parameter[LINE21_CENTER_Y]);
-			cairo_rectangle (cairoTarget,
-					-MAX(ls->parameter[LINE21_WIDTH]/2.0,
-						pixelWidth),
-					-MAX(ls->parameter[LINE21_HEIGHT]/2.0,
-						pixelWidth),
-					MAX(ls->parameter[LINE21_WIDTH],
-						pixelWidth),
-					MAX(ls->parameter[LINE21_HEIGHT],
-						pixelWidth));
-			if (doVectorExportFix
-			&& CAIRO_OPERATOR_CLEAR ==
-					cairo_get_operator (cairoTarget)) {
-				cairo_save (cairoTarget);
-				cairo_set_source_rgba (cairoTarget,
-						bg_r, bg_g, bg_b, 1.0);
-				cairo_set_operator (cairoTarget,
-						CAIRO_OPERATOR_OVER);
-
-				draw_fill (cairoTarget, drawMode,
-						selectionInfo, image, net);
-
-				cairo_restore (cairoTarget);
-
-				break;
-			}
-
-			draw_fill (cairoTarget, drawMode,
-					selectionInfo, image, net);
-			break;
-
-		case GERBV_APTYPE_MACRO_LINE22:
-			draw_update_macro_exposure (cairoTarget,
-					clearOperator, darkOperator,
-					ls->parameter[LINE22_EXPOSURE]);
-			cairo_rotate (cairoTarget, DEG2RAD(
-					ls->parameter[LINE22_ROTATION]));
-			cairo_translate (cairoTarget,
-					ls->parameter[LINE22_LOWER_LEFT_X],
-					ls->parameter[LINE22_LOWER_LEFT_Y]);
-			cairo_rectangle (cairoTarget, 0, 0,
-					MAX(ls->parameter[LINE22_WIDTH],
-						pixelWidth),
-					MAX(ls->parameter[LINE22_HEIGHT],
-						pixelWidth));
-
-			if (doVectorExportFix
-			&& CAIRO_OPERATOR_CLEAR ==
-					cairo_get_operator (cairoTarget)) {
-				cairo_save (cairoTarget);
-				cairo_set_source_rgba (cairoTarget,
-						bg_r, bg_g, bg_b, 1.0);
-				cairo_set_operator (cairoTarget,
-						CAIRO_OPERATOR_OVER);
-
-				draw_fill (cairoTarget, drawMode,
-						selectionInfo, image, net);
-
-				cairo_restore (cairoTarget);
-
-				break;
-			}
-
-			draw_fill (cairoTarget, drawMode,
-					selectionInfo, image, net);
-			break;
-
-		default:
-			GERB_COMPILE_WARNING(_("Unknown macro type: %s"),
-					gerbv_aperture_type_name(ls->type));
-			ret = 0;
-		}
-
-		cairo_restore (cairoTarget);
-		ls = ls->next;
-	}
-
-	if (usesClearPrimitive) {
-		cairo_pop_group_to_source (cairoTarget);
-		cairo_paint (cairoTarget);
-	}
-
-	return ret;
+gerbv_draw_amacro(
+    cairo_t* cairoTarget, cairo_operator_t clearOperator, cairo_operator_t darkOperator, gerbv_simplified_amacro_t* s,
+    gint usesClearPrimitive, gdouble pixelWidth, enum draw_mode drawMode, gerbv_selection_info_t* selectionInfo,
+    gerbv_image_t* image, struct gerbv_net* net
+) {
+    gerbv_simplified_amacro_t* ls = s;
+    gboolean                   doVectorExportFix;
+    double                     bg_r, bg_g, bg_b; /* Background color */
+    int                        ret = 1;
+
+    dprintf("Drawing simplified aperture macros:\n");
+
+    doVectorExportFix = draw_do_vector_export_fix(cairoTarget, &bg_r, &bg_g, &bg_b);
+
+    switch (cairo_surface_get_type(cairo_get_target(cairoTarget))) {
+
+        case CAIRO_SURFACE_TYPE_PDF:
+        case CAIRO_SURFACE_TYPE_PS:
+        case CAIRO_SURFACE_TYPE_SVG:
+
+            /* Don't limit "pixel width" in vector export */
+            pixelWidth = DBL_MIN;
+
+            break;
+
+        default: break;
+    }
+
+    if (usesClearPrimitive)
+        cairo_push_group(cairoTarget);
+
+    while (ls != NULL) {
+        /*
+         * This handles the exposure thing in the aperture macro
+         * The exposure is always the first element on stack independent
+         * of aperture macro.
+         */
+        cairo_save(cairoTarget);
+        cairo_new_path(cairoTarget);
+
+        dprintf("\t%s(): drawing %s\n", __FUNCTION__, gerbv_aperture_type_name(ls->type));
+
+        switch (ls->type) {
+
+            case GERBV_APTYPE_MACRO_CIRCLE:
+                draw_update_macro_exposure(cairoTarget, clearOperator, darkOperator, ls->parameter[CIRCLE_EXPOSURE]);
+                cairo_translate(cairoTarget, ls->parameter[CIRCLE_CENTER_X], ls->parameter[CIRCLE_CENTER_Y]);
+                gerbv_draw_circle(cairoTarget, ls->parameter[CIRCLE_DIAMETER]);
+
+                if (doVectorExportFix && CAIRO_OPERATOR_CLEAR == cairo_get_operator(cairoTarget)) {
+                    cairo_save(cairoTarget);
+                    cairo_set_source_rgba(cairoTarget, bg_r, bg_g, bg_b, 1.0);
+                    cairo_set_operator(cairoTarget, CAIRO_OPERATOR_OVER);
+
+                    draw_fill(cairoTarget, drawMode, selectionInfo, image, net);
+
+                    cairo_restore(cairoTarget);
+
+                    break;
+                }
+
+                draw_fill(cairoTarget, drawMode, selectionInfo, image, net);
+                break;
+
+            case GERBV_APTYPE_MACRO_OUTLINE:
+                draw_update_macro_exposure(cairoTarget, clearOperator, darkOperator, ls->parameter[OUTLINE_EXPOSURE]);
+                cairo_rotate(cairoTarget, DEG2RAD(ls->parameter[OUTLINE_ROTATION_IDX(ls->parameter)]));
+                cairo_move_to(cairoTarget, ls->parameter[OUTLINE_FIRST_X], ls->parameter[OUTLINE_FIRST_Y]);
+
+                for (int point = 1; point < 1 + (int)ls->parameter[OUTLINE_NUMBER_OF_POINTS]; point++) {
+                    cairo_line_to(
+                        cairoTarget, ls->parameter[OUTLINE_X_IDX_OF_POINT(point)],
+                        ls->parameter[OUTLINE_Y_IDX_OF_POINT(point)]
+                    );
+                }
+
+                if (doVectorExportFix && CAIRO_OPERATOR_CLEAR == cairo_get_operator(cairoTarget)) {
+                    cairo_save(cairoTarget);
+                    cairo_set_source_rgba(cairoTarget, bg_r, bg_g, bg_b, 1.0);
+                    cairo_set_operator(cairoTarget, CAIRO_OPERATOR_OVER);
+
+                    draw_fill(cairoTarget, drawMode, selectionInfo, image, net);
+
+                    cairo_restore(cairoTarget);
+
+                    break;
+                }
+
+                /* Although the gerber specs allow for an open outline,
+                 * I interpret it to mean the outline should be closed
+                 * by the rendering softare automatically, since there
+                 * is no dimension for line thickness. */
+                draw_fill(cairoTarget, drawMode, selectionInfo, image, net);
+                break;
+
+            case GERBV_APTYPE_MACRO_POLYGON:
+                draw_update_macro_exposure(cairoTarget, clearOperator, darkOperator, ls->parameter[POLYGON_EXPOSURE]);
+                cairo_translate(cairoTarget, ls->parameter[POLYGON_CENTER_X], ls->parameter[POLYGON_CENTER_Y]);
+                gerbv_draw_polygon(
+                    cairoTarget, ls->parameter[POLYGON_DIAMETER], ls->parameter[POLYGON_NUMBER_OF_POINTS],
+                    ls->parameter[POLYGON_ROTATION]
+                );
+
+                if (doVectorExportFix && CAIRO_OPERATOR_CLEAR == cairo_get_operator(cairoTarget)) {
+                    cairo_save(cairoTarget);
+                    cairo_set_source_rgba(cairoTarget, bg_r, bg_g, bg_b, 1.0);
+                    cairo_set_operator(cairoTarget, CAIRO_OPERATOR_OVER);
+
+                    draw_fill(cairoTarget, drawMode, selectionInfo, image, net);
+
+                    cairo_restore(cairoTarget);
+
+                    break;
+                }
+
+                draw_fill(cairoTarget, drawMode, selectionInfo, image, net);
+                break;
+
+            case GERBV_APTYPE_MACRO_MOIRE:
+                {
+                    gdouble diameter, diameterDifference, crosshairRadius;
+
+                    cairo_translate(cairoTarget, ls->parameter[MOIRE_CENTER_X], ls->parameter[MOIRE_CENTER_Y]);
+                    cairo_rotate(cairoTarget, DEG2RAD(ls->parameter[MOIRE_ROTATION]));
+                    diameter           = ls->parameter[MOIRE_OUTSIDE_DIAMETER] - ls->parameter[MOIRE_CIRCLE_THICKNESS];
+                    diameterDifference = 2 * (ls->parameter[MOIRE_GAP_WIDTH] + ls->parameter[MOIRE_CIRCLE_THICKNESS]);
+                    cairo_set_line_width(cairoTarget, ls->parameter[MOIRE_CIRCLE_THICKNESS]);
+
+                    if (doVectorExportFix && CAIRO_OPERATOR_CLEAR == cairo_get_operator(cairoTarget)) {
+                        cairo_save(cairoTarget);
+                        cairo_set_source_rgba(cairoTarget, bg_r, bg_g, bg_b, 1.0);
+                        cairo_set_operator(cairoTarget, CAIRO_OPERATOR_OVER);
+                    }
+
+                    for (int circle = 0; circle < (int)ls->parameter[MOIRE_NUMBER_OF_CIRCLES]; circle++) {
+                        gdouble dia = diameter - diameterDifference * circle;
+
+                        if (dia <= 0) {
+                            GERB_COMPILE_WARNING(
+                                _("Ignoring %s "
+                                  "with non positive diameter"),
+                                gerbv_aperture_type_name(ls->type)
+                            );
+                            continue;
+                        }
+
+                        gerbv_draw_circle(cairoTarget, dia);
+                        draw_stroke(cairoTarget, drawMode, selectionInfo, image, net);
+                    }
+
+                    cairo_set_line_width(cairoTarget, ls->parameter[MOIRE_CROSSHAIR_THICKNESS]);
+                    crosshairRadius = ls->parameter[MOIRE_CROSSHAIR_LENGTH] / 2.0;
+                    cairo_move_to(cairoTarget, -crosshairRadius, 0);
+                    cairo_line_to(cairoTarget, crosshairRadius, 0);
+                    cairo_move_to(cairoTarget, 0, -crosshairRadius);
+                    cairo_line_to(cairoTarget, 0, crosshairRadius);
+
+                    draw_stroke(cairoTarget, drawMode, selectionInfo, image, net);
+
+                    if (doVectorExportFix && CAIRO_OPERATOR_CLEAR == cairo_get_operator(cairoTarget)) {
+                        cairo_restore(cairoTarget);
+                    }
+
+                    break;
+                }
+            case GERBV_APTYPE_MACRO_THERMAL:
+                {
+                    gdouble startAngle1, startAngle2, endAngle1, endAngle2;
+
+                    cairo_translate(cairoTarget, ls->parameter[THERMAL_CENTER_X], ls->parameter[THERMAL_CENTER_Y]);
+                    cairo_rotate(cairoTarget, DEG2RAD(ls->parameter[THERMAL_ROTATION]));
+                    startAngle1 =
+                        asin(ls->parameter[THERMAL_CROSSHAIR_THICKNESS] / ls->parameter[THERMAL_INSIDE_DIAMETER]);
+                    endAngle1 = M_PI_2 - startAngle1;
+                    endAngle2 =
+                        asin(ls->parameter[THERMAL_CROSSHAIR_THICKNESS] / ls->parameter[THERMAL_OUTSIDE_DIAMETER]);
+                    startAngle2 = M_PI_2 - endAngle2;
+
+                    if (doVectorExportFix && CAIRO_OPERATOR_CLEAR == cairo_get_operator(cairoTarget)) {
+                        cairo_save(cairoTarget);
+                        cairo_set_source_rgba(cairoTarget, bg_r, bg_g, bg_b, 1.0);
+                        cairo_set_operator(cairoTarget, CAIRO_OPERATOR_OVER);
+
+                        /* */
+
+                        cairo_restore(cairoTarget);
+
+                        break;
+                    }
+
+                    for (gint i = 0; i < 4; i++) {
+                        cairo_arc(
+                            cairoTarget, 0, 0, ls->parameter[THERMAL_INSIDE_DIAMETER] / 2.0, startAngle1, endAngle1
+                        );
+                        cairo_arc_negative(
+                            cairoTarget, 0, 0, ls->parameter[THERMAL_OUTSIDE_DIAMETER] / 2.0, startAngle2, endAngle2
+                        );
+                        draw_fill(cairoTarget, drawMode, selectionInfo, image, net);
+                        cairo_rotate(cairoTarget, M_PI_2);
+                    }
+
+                    break;
+                }
+            case GERBV_APTYPE_MACRO_LINE20:
+                draw_update_macro_exposure(cairoTarget, clearOperator, darkOperator, ls->parameter[LINE20_EXPOSURE]);
+                cairo_set_line_width(cairoTarget, MAX(ls->parameter[LINE20_LINE_WIDTH], pixelWidth));
+                cairo_set_line_cap(cairoTarget, CAIRO_LINE_CAP_BUTT);
+                cairo_rotate(cairoTarget, DEG2RAD(ls->parameter[LINE20_ROTATION]));
+                cairo_move_to(cairoTarget, ls->parameter[LINE20_START_X], ls->parameter[LINE20_START_Y]);
+                cairo_line_to(cairoTarget, ls->parameter[LINE20_END_X], ls->parameter[LINE20_END_Y]);
+
+                if (doVectorExportFix && CAIRO_OPERATOR_CLEAR == cairo_get_operator(cairoTarget)) {
+                    cairo_save(cairoTarget);
+                    cairo_set_source_rgba(cairoTarget, bg_r, bg_g, bg_b, 1.0);
+                    cairo_set_operator(cairoTarget, CAIRO_OPERATOR_OVER);
+
+                    draw_stroke(cairoTarget, drawMode, selectionInfo, image, net);
+
+                    cairo_restore(cairoTarget);
+
+                    break;
+                }
+
+                draw_stroke(cairoTarget, drawMode, selectionInfo, image, net);
+                break;
+
+            case GERBV_APTYPE_MACRO_LINE21:
+                draw_update_macro_exposure(cairoTarget, clearOperator, darkOperator, ls->parameter[LINE21_EXPOSURE]);
+                cairo_rotate(cairoTarget, DEG2RAD(ls->parameter[LINE21_ROTATION]));
+                cairo_translate(cairoTarget, ls->parameter[LINE21_CENTER_X], ls->parameter[LINE21_CENTER_Y]);
+                cairo_rectangle(
+                    cairoTarget, -MAX(ls->parameter[LINE21_WIDTH] / 2.0, pixelWidth),
+                    -MAX(ls->parameter[LINE21_HEIGHT] / 2.0, pixelWidth), MAX(ls->parameter[LINE21_WIDTH], pixelWidth),
+                    MAX(ls->parameter[LINE21_HEIGHT], pixelWidth)
+                );
+                if (doVectorExportFix && CAIRO_OPERATOR_CLEAR == cairo_get_operator(cairoTarget)) {
+                    cairo_save(cairoTarget);
+                    cairo_set_source_rgba(cairoTarget, bg_r, bg_g, bg_b, 1.0);
+                    cairo_set_operator(cairoTarget, CAIRO_OPERATOR_OVER);
+
+                    draw_fill(cairoTarget, drawMode, selectionInfo, image, net);
+
+                    cairo_restore(cairoTarget);
+
+                    break;
+                }
+
+                draw_fill(cairoTarget, drawMode, selectionInfo, image, net);
+                break;
+
+            case GERBV_APTYPE_MACRO_LINE22:
+                draw_update_macro_exposure(cairoTarget, clearOperator, darkOperator, ls->parameter[LINE22_EXPOSURE]);
+                cairo_rotate(cairoTarget, DEG2RAD(ls->parameter[LINE22_ROTATION]));
+                cairo_translate(cairoTarget, ls->parameter[LINE22_LOWER_LEFT_X], ls->parameter[LINE22_LOWER_LEFT_Y]);
+                cairo_rectangle(
+                    cairoTarget, 0, 0, MAX(ls->parameter[LINE22_WIDTH], pixelWidth),
+                    MAX(ls->parameter[LINE22_HEIGHT], pixelWidth)
+                );
+
+                if (doVectorExportFix && CAIRO_OPERATOR_CLEAR == cairo_get_operator(cairoTarget)) {
+                    cairo_save(cairoTarget);
+                    cairo_set_source_rgba(cairoTarget, bg_r, bg_g, bg_b, 1.0);
+                    cairo_set_operator(cairoTarget, CAIRO_OPERATOR_OVER);
+
+                    draw_fill(cairoTarget, drawMode, selectionInfo, image, net);
+
+                    cairo_restore(cairoTarget);
+
+                    break;
+                }
+
+                draw_fill(cairoTarget, drawMode, selectionInfo, image, net);
+                break;
+
+            default: GERB_COMPILE_WARNING(_("Unknown macro type: %s"), gerbv_aperture_type_name(ls->type)); ret = 0;
+        }
+
+        cairo_restore(cairoTarget);
+        ls = ls->next;
+    }
+
+    if (usesClearPrimitive) {
+        cairo_pop_group_to_source(cairoTarget);
+        cairo_paint(cairoTarget);
+    }
+
+    return ret;
 }
 
 void
-draw_apply_netstate_transformation (cairo_t *cairoTarget, gerbv_netstate_t *state)
-{
-	/* apply scale factor */
-	cairo_scale (cairoTarget, state->scaleA, state->scaleB);
-	/* apply offset */
-	cairo_translate (cairoTarget, state->offsetA, state->offsetB);
-	/* apply mirror */
-	switch (state->mirrorState) {
-	case GERBV_MIRROR_STATE_FLIPA:
-		cairo_scale (cairoTarget, -1, 1);
-		break;
-	case GERBV_MIRROR_STATE_FLIPB:
-		cairo_scale (cairoTarget, 1, -1);
-		break;
-	case GERBV_MIRROR_STATE_FLIPAB:
-		cairo_scale (cairoTarget, -1, -1);
-		break;
-	default:
-		break;
-	}
-	/* finally, apply axis select */
-	if (state->axisSelect == GERBV_AXIS_SELECT_SWAPAB) {
-		/* we do this by rotating 270 (counterclockwise, then mirroring
-		   the Y axis */
-		cairo_rotate (cairoTarget, M_PI + M_PI_2);
-		cairo_scale (cairoTarget, 1, -1);
-	}
+draw_apply_netstate_transformation(cairo_t* cairoTarget, gerbv_netstate_t* state) {
+    /* apply scale factor */
+    cairo_scale(cairoTarget, state->scaleA, state->scaleB);
+    /* apply offset */
+    cairo_translate(cairoTarget, state->offsetA, state->offsetB);
+    /* apply mirror */
+    switch (state->mirrorState) {
+        case GERBV_MIRROR_STATE_FLIPA: cairo_scale(cairoTarget, -1, 1); break;
+        case GERBV_MIRROR_STATE_FLIPB: cairo_scale(cairoTarget, 1, -1); break;
+        case GERBV_MIRROR_STATE_FLIPAB: cairo_scale(cairoTarget, -1, -1); break;
+        default: break;
+    }
+    /* finally, apply axis select */
+    if (state->axisSelect == GERBV_AXIS_SELECT_SWAPAB) {
+        /* we do this by rotating 270 (counterclockwise, then mirroring
+           the Y axis */
+        cairo_rotate(cairoTarget, M_PI + M_PI_2);
+        cairo_scale(cairoTarget, 1, -1);
+    }
 }
 
 void
-draw_render_polygon_object (gerbv_net_t *oldNet, cairo_t *cairoTarget,
-		gdouble sr_x, gdouble sr_y, gerbv_image_t *image,
-		enum draw_mode drawMode, gerbv_selection_info_t *selectionInfo,
-		gboolean pixelOutput)
-{
-	gerbv_net_t *currentNet, *polygonStartNet;
-	int haveDrawnFirstFillPoint = 0;
-	gdouble x2,y2,cp_x=0,cp_y=0;
-
-	haveDrawnFirstFillPoint = FALSE;
-	/* save the first net in the polygon as the "ID" net pointer
-	   in case we are saving this net to the selection array */
-	polygonStartNet = oldNet;
-	cairo_new_path(cairoTarget);
-
-	for (currentNet = oldNet->next; currentNet!=NULL;
-			currentNet = currentNet->next) {
-		x2 = currentNet->stop_x + sr_x;
-		y2 = currentNet->stop_y + sr_y;
-
-		/* translate circular x,y data as well */
-		if (currentNet->cirseg) {
-			cp_x = currentNet->cirseg->cp_x + sr_x;
-			cp_y = currentNet->cirseg->cp_y + sr_y;
-		}
-		if (!haveDrawnFirstFillPoint) {
-			draw_cairo_move_to (cairoTarget, x2, y2, FALSE, pixelOutput);
-			haveDrawnFirstFillPoint=TRUE;
-			continue;
-		}
-
-		switch (currentNet->interpolation) {
-		case GERBV_INTERPOLATION_LINEARx1 :
-		case GERBV_INTERPOLATION_LINEARx10 :
-		case GERBV_INTERPOLATION_LINEARx01 :
-		case GERBV_INTERPOLATION_LINEARx001 :
-			draw_cairo_line_to (cairoTarget, x2, y2, FALSE, pixelOutput);
-			break;
-		case GERBV_INTERPOLATION_CW_CIRCULAR :
-		case GERBV_INTERPOLATION_CCW_CIRCULAR :
-			if (currentNet->cirseg->angle2 > currentNet->cirseg->angle1) {
-				cairo_arc (cairoTarget, cp_x, cp_y, currentNet->cirseg->width/2.0,
-					DEG2RAD(currentNet->cirseg->angle1),
-					DEG2RAD(currentNet->cirseg->angle2));
-			} else {
-				cairo_arc_negative (cairoTarget, cp_x, cp_y, currentNet->cirseg->width/2.0,
-					DEG2RAD(currentNet->cirseg->angle1),
-					DEG2RAD(currentNet->cirseg->angle2));
-			}
-			break;
-		case GERBV_INTERPOLATION_PAREA_END :
-			cairo_close_path(cairoTarget);
-			/* turn off anti-aliasing for polygons, since it shows seams
-			   with adjacent polygons (usually on PCB ground planes) */
-			cairo_antialias_t oldAlias = cairo_get_antialias (cairoTarget);
-			cairo_set_antialias (cairoTarget, CAIRO_ANTIALIAS_NONE);
-			draw_fill (cairoTarget, drawMode, selectionInfo, image, polygonStartNet);
-			cairo_set_antialias (cairoTarget, oldAlias);
-			return;
-		default :
-			break;
-		}
-	}
+draw_render_polygon_object(
+    gerbv_net_t* oldNet, cairo_t* cairoTarget, gdouble sr_x, gdouble sr_y, gerbv_image_t* image,
+    enum draw_mode drawMode, gerbv_selection_info_t* selectionInfo, gboolean pixelOutput
+) {
+    gerbv_net_t *currentNet, *polygonStartNet;
+    int          haveDrawnFirstFillPoint = 0;
+    gdouble      x2, y2, cp_x = 0, cp_y = 0;
+
+    haveDrawnFirstFillPoint = FALSE;
+    /* save the first net in the polygon as the "ID" net pointer
+       in case we are saving this net to the selection array */
+    polygonStartNet = oldNet;
+    cairo_new_path(cairoTarget);
+
+    for (currentNet = oldNet->next; currentNet != NULL; currentNet = currentNet->next) {
+        x2 = currentNet->stop_x + sr_x;
+        y2 = currentNet->stop_y + sr_y;
+
+        /* translate circular x,y data as well */
+        if (currentNet->cirseg) {
+            cp_x = currentNet->cirseg->cp_x + sr_x;
+            cp_y = currentNet->cirseg->cp_y + sr_y;
+        }
+        if (!haveDrawnFirstFillPoint) {
+            draw_cairo_move_to(cairoTarget, x2, y2, FALSE, pixelOutput);
+            haveDrawnFirstFillPoint = TRUE;
+            continue;
+        }
+
+        switch (currentNet->interpolation) {
+            case GERBV_INTERPOLATION_LINEARx1:
+            case GERBV_INTERPOLATION_LINEARx10:
+            case GERBV_INTERPOLATION_LINEARx01:
+            case GERBV_INTERPOLATION_LINEARx001: draw_cairo_line_to(cairoTarget, x2, y2, FALSE, pixelOutput); break;
+            case GERBV_INTERPOLATION_CW_CIRCULAR:
+            case GERBV_INTERPOLATION_CCW_CIRCULAR:
+                if (currentNet->cirseg->angle2 > currentNet->cirseg->angle1) {
+                    cairo_arc(
+                        cairoTarget, cp_x, cp_y, currentNet->cirseg->width / 2.0, DEG2RAD(currentNet->cirseg->angle1),
+                        DEG2RAD(currentNet->cirseg->angle2)
+                    );
+                } else {
+                    cairo_arc_negative(
+                        cairoTarget, cp_x, cp_y, currentNet->cirseg->width / 2.0, DEG2RAD(currentNet->cirseg->angle1),
+                        DEG2RAD(currentNet->cirseg->angle2)
+                    );
+                }
+                break;
+            case GERBV_INTERPOLATION_PAREA_END:
+                cairo_close_path(cairoTarget);
+                /* turn off anti-aliasing for polygons, since it shows seams
+                   with adjacent polygons (usually on PCB ground planes) */
+                cairo_antialias_t oldAlias = cairo_get_antialias(cairoTarget);
+                cairo_set_antialias(cairoTarget, CAIRO_ANTIALIAS_NONE);
+                draw_fill(cairoTarget, drawMode, selectionInfo, image, polygonStartNet);
+                cairo_set_antialias(cairoTarget, oldAlias);
+                return;
+            default: break;
+        }
+    }
 }
 
 /** Draw Cairo cross.
@@ -861,650 +706,586 @@ draw_render_polygon_object (gerbv_net_t *oldNet, cairo_t *cairoTarget,
   @param r	Cross half size.
 */
 static void
-draw_cairo_cross (cairo_t *cairoTarget, gdouble xc, gdouble yc, gdouble r)
-{
-	cairo_move_to (cairoTarget, xc, yc - r);
-	cairo_rel_line_to (cairoTarget,  0, 2*r);
-	cairo_move_to (cairoTarget, xc - r, yc);
-	cairo_rel_line_to (cairoTarget, 2*r, 0);
-	cairo_stroke (cairoTarget);
+draw_cairo_cross(cairo_t* cairoTarget, gdouble xc, gdouble yc, gdouble r) {
+    cairo_move_to(cairoTarget, xc, yc - r);
+    cairo_rel_line_to(cairoTarget, 0, 2 * r);
+    cairo_move_to(cairoTarget, xc - r, yc);
+    cairo_rel_line_to(cairoTarget, 2 * r, 0);
+    cairo_stroke(cairoTarget);
 }
 
 static int
-draw_calc_pnp_mark_coords(struct gerbv_net *start_net,
-		double *label_x, double *label_y)
-{
-	double x, y;
-	struct gerbv_net *net = start_net;
-	const char *label = NULL;
-	
-	if (net && net->label)
-		label = net->label->str;
-
-	if (label == NULL)
-		return 0;
-
-	x = HUGE_VAL; y = -HUGE_VAL;
-	do {
-		if (!net->label
-		||  0 != g_strcmp0 (net->label->str, label))
-			break;
-
-		/* Search top left corner */
-		if (net->boundingBox.top != HUGE_VAL) {
-			/* Bounding box not calculated */
-			x = MIN(x, net->boundingBox.left);
-			y = MAX(y, net->boundingBox.top);
-		} else {
-			x = MIN(x, net->stop_x);
-			y = MAX(y, net->stop_y + 0.01/2);
-						/* 0.01 default line width */
-		}
-	} while (NULL !=
-			(net = gerbv_image_return_next_renderable_object(net)));
-
-	*label_x = x;
-	*label_y = y;
-
-	return 1;
+draw_calc_pnp_mark_coords(struct gerbv_net* start_net, double* label_x, double* label_y) {
+    double            x, y;
+    struct gerbv_net* net   = start_net;
+    const char*       label = NULL;
+
+    if (net && net->label)
+        label = net->label->str;
+
+    if (label == NULL)
+        return 0;
+
+    x = HUGE_VAL;
+    y = -HUGE_VAL;
+    do {
+        if (!net->label || 0 != g_strcmp0(net->label->str, label))
+            break;
+
+        /* Search top left corner */
+        if (net->boundingBox.top != HUGE_VAL) {
+            /* Bounding box not calculated */
+            x = MIN(x, net->boundingBox.left);
+            y = MAX(y, net->boundingBox.top);
+        } else {
+            x = MIN(x, net->stop_x);
+            y = MAX(y, net->stop_y + 0.01 / 2);
+            /* 0.01 default line width */
+        }
+    } while (NULL != (net = gerbv_image_return_next_renderable_object(net)));
+
+    *label_x = x;
+    *label_y = y;
+
+    return 1;
 }
 
 int
-draw_image_to_cairo_target (cairo_t *cairoTarget, gerbv_image_t *image,
-		gdouble pixelWidth, enum draw_mode drawMode,
-		gerbv_selection_info_t *selectionInfo,
-		gerbv_render_info_t *renderInfo, gboolean allowOptimization,
-		gerbv_user_transformation_t transform, gboolean pixelOutput)
-{
-	const int hole_cross_inc_px = 8;
-	struct gerbv_net *net, *polygonStartNet=NULL;
-	double x1, y1, x2, y2, cp_x=0, cp_y=0;
-	gdouble *p, p0, p1, dx, dy, lineWidth, r;
-	gerbv_netstate_t *oldState;
-	gerbv_layer_t *oldLayer;
-	cairo_operator_t drawOperatorClear, drawOperatorDark;
-	gboolean invertPolarity = FALSE, oddWidth = FALSE;
-	gdouble minX=0, minY=0, maxX=0, maxY=0;
-	gdouble criticalRadius;
-	gdouble scaleX = transform.scaleX;
-	gdouble scaleY = transform.scaleY;
-					/* Keep PNP label not mirrored */
-	gdouble pnp_label_scale_x = 1, pnp_label_scale_y= -1;
-	gboolean limitLineWidth = TRUE;
-	gboolean displayPixel = TRUE;
-	gboolean doVectorExportFix;
-	double bg_r, bg_g, bg_b; /* Background color */
-
-	doVectorExportFix =
-		draw_do_vector_export_fix (cairoTarget, &bg_r, &bg_g, &bg_b);
-
-	/* If we are scaling the image at all, ignore the line width checks
-	 * since scaled up lines can still be visible */
-	if ((scaleX != 1)||(scaleY != 1)){
-		limitLineWidth = FALSE;
-	}
-
-	if (transform.mirrorAroundX) {
-		scaleY *= -1;
-		pnp_label_scale_y = 1;
-	}
-
-	if (transform.mirrorAroundY) {
-		scaleX *= -1;
-		pnp_label_scale_x= -1;
-	}
-
-	cairo_translate (cairoTarget, transform.translateX, transform.translateY);
-	cairo_scale (cairoTarget, scaleX, scaleY);
-	cairo_rotate (cairoTarget, transform.rotation);
-
-	gboolean useOptimizations = allowOptimization;
-
-	/* If the user is using any transformations for this layer, then don't
-	 * bother using rendering optimizations */
-	if (fabs(transform.translateX) > GERBV_PRECISION_LINEAR_INCH
-	||  fabs(transform.translateY) > GERBV_PRECISION_LINEAR_INCH
-	||  fabs(transform.scaleX - 1) > GERBV_PRECISION_LINEAR_INCH
-	||  fabs(transform.scaleY - 1) > GERBV_PRECISION_LINEAR_INCH
-	||  fabs(transform.rotation) > GERBV_PRECISION_ANGLE_RAD
-	||  transform.mirrorAroundX || transform.mirrorAroundY)
-		useOptimizations = FALSE;
-
-	if (useOptimizations && pixelOutput) {
-		minX = renderInfo->lowerLeftX;
-		minY = renderInfo->lowerLeftY;
-		maxX = renderInfo->lowerLeftX + (renderInfo->displayWidth /
-					renderInfo->scaleFactorX);
-		maxY = renderInfo->lowerLeftY + (renderInfo->displayHeight /
-					renderInfo->scaleFactorY);
-	}
-
-	/* do initial justify */
-	cairo_translate (cairoTarget, image->info->imageJustifyOffsetActualA,
-		 image->info->imageJustifyOffsetActualB);
-
-	/* set the fill rule so aperture holes are cleared correctly */
-	cairo_set_fill_rule (cairoTarget, CAIRO_FILL_RULE_EVEN_ODD);
-	/* offset image */
-	cairo_translate (cairoTarget, image->info->offsetA, image->info->offsetB);
-	/* do image rotation */
-	cairo_rotate (cairoTarget, image->info->imageRotation);
-
-	/* load in polarity operators depending on the image polarity */
-	invertPolarity = transform.inverted;
-	if (image->info->polarity == GERBV_POLARITY_NEGATIVE)
-		invertPolarity = !invertPolarity;
-	if (drawMode == DRAW_SELECTIONS)
-		invertPolarity = FALSE;
-
-	if (invertPolarity) {
-		drawOperatorClear = CAIRO_OPERATOR_OVER;
-		drawOperatorDark = CAIRO_OPERATOR_CLEAR;
-		cairo_set_operator (cairoTarget, CAIRO_OPERATOR_OVER);
-		cairo_paint (cairoTarget);
-		cairo_set_operator (cairoTarget, CAIRO_OPERATOR_CLEAR);
-	} else {
-		drawOperatorClear = CAIRO_OPERATOR_CLEAR;
-		drawOperatorDark = CAIRO_OPERATOR_OVER;
-	}
-
-	/* next, push two cairo states to simulate the first layer and netstate
-	   translations (these will be popped when another layer or netstate is
-	   started */
-	cairo_save (cairoTarget);
-	cairo_save (cairoTarget);
-
-	/* store the current layer and netstate so we know when they change */
-	oldLayer = image->layers;
-	oldState = image->states;
-
-	const char *pnp_net_label_str_prev = NULL;
-
-	for (net = image->netlist->next; net != NULL;
-			net = gerbv_image_return_next_renderable_object(net)) {
-
-		/* check if this is a new layer */
-		if (net->layer != oldLayer){
-			/* it's a new layer, so recalculate the new transformation matrix
-			   for it */
-			cairo_restore (cairoTarget);
-			cairo_restore (cairoTarget);
-			cairo_save (cairoTarget);
-			/* do any rotations */
-			cairo_rotate (cairoTarget, net->layer->rotation);
-			/* handle the layer polarity */
-			if ((net->layer->polarity == GERBV_POLARITY_CLEAR)^invertPolarity) {
-				cairo_set_operator (cairoTarget, CAIRO_OPERATOR_CLEAR);
-				drawOperatorClear = CAIRO_OPERATOR_OVER;
-				drawOperatorDark = CAIRO_OPERATOR_CLEAR;
-			}
-			else {
-				cairo_set_operator (cairoTarget, CAIRO_OPERATOR_OVER);
-				drawOperatorClear = CAIRO_OPERATOR_CLEAR;
-				drawOperatorDark = CAIRO_OPERATOR_OVER;
-			}
-
-			/* Draw any knockout areas */
-			gerbv_knockout_t *ko = &net->layer->knockout;
-			if (ko->firstInstance == TRUE) {
-				cairo_save (cairoTarget);
-
-				if (ko->polarity == GERBV_POLARITY_CLEAR) {
-					cairo_set_operator (cairoTarget, drawOperatorClear);
-				} else {
-					cairo_set_operator (cairoTarget, drawOperatorDark);
-				}
-
-				if (doVectorExportFix
-				&& CAIRO_OPERATOR_CLEAR ==
-					cairo_get_operator (cairoTarget)) {
-
-					cairo_set_operator (cairoTarget,
-							CAIRO_OPERATOR_OVER);
-					cairo_set_source_rgba (
-							cairoTarget, bg_r,
-							bg_g, bg_b, 1.0);
-				}
-
-				cairo_new_path (cairoTarget);
-				cairo_rectangle (cairoTarget,
-						ko->lowerLeftX - ko->border,
-						ko->lowerLeftY - ko->border,
-						ko->width + 2*ko->border,
-						ko->height + 2*ko->border);
-				draw_fill (cairoTarget, drawMode, selectionInfo, image, net);
-
-				cairo_restore (cairoTarget);
-			}
-
-			/* Finally, reapply old netstate transformation */
-			cairo_save (cairoTarget);
-			draw_apply_netstate_transformation (cairoTarget, net->state);
-			oldLayer = net->layer;
-		}
-
-		/* check if this is a new netstate */
-		if (net->state != oldState){
-			/* pop the transformation matrix back to the "pre-state" state and
-			   resave it */
-			cairo_restore (cairoTarget);
-			cairo_save (cairoTarget);
-			/* it's a new state, so recalculate the new transformation matrix
-			   for it */
-			draw_apply_netstate_transformation (cairoTarget, net->state);
-			oldState = net->state;
-		}
-
-		/* if we are only drawing from the selection buffer, search if this net is
-		   in the buffer */
-		if (drawMode == DRAW_SELECTIONS) {
-			/* this flag makes sure we don't draw any unintentional polygons...
-			   if we've successfully entered a polygon (the first net matches, and
-			   we don't want to check the nets inside the polygon) then
-			   polygonStartNet will be set */
-			if (!polygonStartNet) {
-				if (!draw_net_is_in_selection_buffer_remove (net,
-							selectionInfo, FALSE))
-					continue;
-			}
-		}
-
-		/* Render any labels attached to this net */
-		/* NOTE: this is currently only used on PNP files, so we may
-		   make some assumptions here... */
-		if (drawMode != DRAW_SELECTIONS &&  net->label
-		&& (image->layertype == GERBV_LAYERTYPE_PICKANDPLACE_TOP
-		 || image->layertype == GERBV_LAYERTYPE_PICKANDPLACE_BOT)
-		&&  g_strcmp0 (net->label->str, pnp_net_label_str_prev)) {
-
-			double mark_x, mark_y;
-
-			/* Add PNP text label only one time per
-			 * net and if it is not selected. */
-			pnp_net_label_str_prev =
-				net->label->str; 
-
-			if (draw_calc_pnp_mark_coords(net, &mark_x, &mark_y)) {
-				cairo_save (cairoTarget);
-
-				cairo_set_font_size (cairoTarget, 0.05);
-				cairo_move_to (cairoTarget, mark_x, mark_y);
-				cairo_scale (cairoTarget, pnp_label_scale_x,
-							pnp_label_scale_y);
-				cairo_show_text (cairoTarget, net->label->str);
-
-				cairo_restore (cairoTarget);
-			}
-		}
-
-		/* step and repeat */
-		gerbv_step_and_repeat_t *sr = &net->layer->stepAndRepeat;
-		int ix, iy;
-		for (ix = 0; ix < sr->X; ix++) {
-			for (iy = 0; iy < sr->Y; iy++) {
-				double sr_x = ix * sr->dist_X;
-				double sr_y = iy * sr->dist_Y;
-
-				if (useOptimizations && pixelOutput
-				&& ((net->boundingBox.right+sr_x < minX)
-				 || (net->boundingBox.left+sr_x > maxX)
-				 || (net->boundingBox.top+sr_y < minY)
-				 || (net->boundingBox.bottom+sr_y > maxY))) {
-					continue;
-				}
-
-				x1 = net->start_x + sr_x;
-				y1 = net->start_y + sr_y;
-				x2 = net->stop_x + sr_x;
-				y2 = net->stop_y + sr_y;
-
-				/* translate circular x,y data as well */
-				if (net->cirseg) {
-					cp_x = net->cirseg->cp_x + sr_x;
-					cp_y = net->cirseg->cp_y + sr_y;
-				}
-
-				/* Polygon area fill routines */
-				switch (net->interpolation) {
-				case GERBV_INTERPOLATION_PAREA_START :
-
-					if (doVectorExportFix
-					&& CAIRO_OPERATOR_CLEAR ==
-					cairo_get_operator (cairoTarget)) {
-
-						cairo_save (cairoTarget);
-
-						cairo_set_operator (cairoTarget,
-							CAIRO_OPERATOR_OVER);
-						cairo_set_source_rgba (
-							cairoTarget, bg_r,
-							bg_g, bg_b, 1.0);
-
-						draw_render_polygon_object (net,
-							cairoTarget,
-							sr_x, sr_y, image,
-							drawMode, selectionInfo,
-							pixelOutput);
-
-						cairo_restore (cairoTarget);
-					} else {
-						draw_render_polygon_object (net,
-							cairoTarget,
-							sr_x, sr_y, image,
-							drawMode, selectionInfo,
-							pixelOutput);
-					}
-
-					continue;
-				case GERBV_INTERPOLATION_DELETED:
-					continue;
-				default :
-					break;
-				}
-
-				/*
-				 * If aperture state is off we allow use of undefined apertures.
-				 * This happens when gerber files starts, but hasn't decided on 
-				 * which aperture to use.
-				 */
-				if (image->aperture[net->aperture] == NULL)
-					continue;
-
-				switch (net->aperture_state) {
-				case GERBV_APERTURE_STATE_ON :
-					/* if the aperture width is truly 0, then render as a 1 pixel width
-					   line.  0 diameter apertures are used by some programs to draw labels,
-					   etc, and they are rendered by other programs as 1 pixel wide */
-					/* NOTE: also, make sure all lines are at least 1 pixel wide, so they
-					   always show up at low zoom levels */
-
-					if (limitLineWidth&&((image->aperture[net->aperture]->parameter[0] < pixelWidth)&&
-							(pixelOutput)))
-						criticalRadius = pixelWidth/2.0;
-					else
-						criticalRadius = image->aperture[net->aperture]->parameter[0]/2.0;
-					lineWidth = criticalRadius*2.0;
-					// convert to a pixel integer
-					cairo_user_to_device_distance (cairoTarget, &lineWidth, &x1);
-					if (pixelOutput) {
-						lineWidth = round(lineWidth);
-						if ((int)lineWidth % 2) {
-							oddWidth = TRUE;
-						}
-						else {
-							oddWidth = FALSE;
-						}
-					}
-					cairo_device_to_user_distance (cairoTarget, &lineWidth, &x1);
-					cairo_set_line_width (cairoTarget, lineWidth);
-
-					switch (net->interpolation) {
-					case GERBV_INTERPOLATION_LINEARx1 :
-					case GERBV_INTERPOLATION_LINEARx10 :
-					case GERBV_INTERPOLATION_LINEARx01 :
-					case GERBV_INTERPOLATION_LINEARx001 :
-						cairo_set_line_cap (cairoTarget, CAIRO_LINE_CAP_ROUND);
-
-						/* weed out any lines that are
-						 * obviously not going to
-						 * render on the visible screen */
-						switch (image->aperture[net->aperture]->type) {
-						case GERBV_APTYPE_CIRCLE :
-							if (renderInfo->show_cross_on_drill_holes
-							&&  image->layertype == GERBV_LAYERTYPE_DRILL) {
-								/* Draw center crosses on slot hole */
-								cairo_set_line_width (cairoTarget, pixelWidth);
-								cairo_set_line_cap (cairoTarget, CAIRO_LINE_CAP_SQUARE);
-								r = image->aperture[net->aperture]->parameter[0]/2.0 +
-									hole_cross_inc_px*pixelWidth;
-								draw_cairo_cross (cairoTarget, x1, y1, r);
-								draw_cairo_cross (cairoTarget, x2, y2, r);
-								cairo_set_line_cap (cairoTarget, CAIRO_LINE_CAP_ROUND);
-								cairo_set_line_width (cairoTarget, lineWidth);
-							}
-
-							draw_cairo_move_to (cairoTarget, x1, y1, oddWidth, pixelOutput);
-							draw_cairo_line_to (cairoTarget, x2, y2, oddWidth, pixelOutput);
-
-							if (doVectorExportFix
-							&& CAIRO_OPERATOR_CLEAR ==
-							cairo_get_operator (cairoTarget)) {
-								cairo_save (cairoTarget);
-								cairo_set_source_rgba (
-									cairoTarget,
-									bg_r,
-									bg_g,
-									bg_b,
-									1.0);
-								cairo_set_operator (
-									cairoTarget,
-									CAIRO_OPERATOR_OVER);
-
-								draw_stroke (
-									cairoTarget,
-									drawMode,
-									selectionInfo,
-									image, net);
-
-								cairo_restore (
-									cairoTarget);
-							} else {
-								draw_stroke (
-									cairoTarget,
-									drawMode,
-									selectionInfo,
-									image, net);
-							}
-
-							break;
-						case GERBV_APTYPE_RECTANGLE :
-							dx = image->aperture[net->aperture]->parameter[0]/2;
-							dy = image->aperture[net->aperture]->parameter[1]/2;
-							if(x1 > x2)
-								dx = -dx;
-							if(y1 > y2)
-								dy = -dy;
-							cairo_new_path(cairoTarget);
-							draw_cairo_move_to (cairoTarget, x1 - dx, y1 - dy, FALSE, pixelOutput);
-							draw_cairo_line_to (cairoTarget, x1 - dx, y1 + dy, FALSE, pixelOutput);
-							draw_cairo_line_to (cairoTarget, x2 - dx, y2 + dy, FALSE, pixelOutput);
-							draw_cairo_line_to (cairoTarget, x2 + dx, y2 + dy, FALSE, pixelOutput);
-							draw_cairo_line_to (cairoTarget, x2 + dx, y2 - dy, FALSE, pixelOutput);
-							draw_cairo_line_to (cairoTarget, x1 + dx, y1 - dy, FALSE, pixelOutput);
-							draw_fill (cairoTarget, drawMode, selectionInfo, image, net);
-							break;
-						/* TODO: for now, just render ovals or polygons like a circle */
-						case GERBV_APTYPE_OVAL :
-						case GERBV_APTYPE_POLYGON :
-							draw_cairo_move_to (cairoTarget, x1,y1, oddWidth, pixelOutput);
-							draw_cairo_line_to (cairoTarget, x2,y2, oddWidth, pixelOutput);
-							draw_stroke (cairoTarget, drawMode, selectionInfo, image, net);
-							break;
-						/* macros can only be flashed, so ignore any that might be here */
-						default:
-							GERB_COMPILE_WARNING(
-								_("Unknown aperture type: %s"),
-								_(gerbv_aperture_type_name(
-									image->aperture[net->aperture]->type)));
-							break;
-						}
-						break;
-					case GERBV_INTERPOLATION_CW_CIRCULAR :
-					case GERBV_INTERPOLATION_CCW_CIRCULAR :
-						/* cairo doesn't have a function to draw oval arcs, so we must
-						 * draw an arc and stretch it by scaling different x and y values
-						 */
-						cairo_new_path(cairoTarget);
-						if (image->aperture[net->aperture]->type == GERBV_APTYPE_RECTANGLE) {
-							cairo_set_line_cap (cairoTarget, CAIRO_LINE_CAP_SQUARE);
-						}
-						else {
-							cairo_set_line_cap (cairoTarget, CAIRO_LINE_CAP_ROUND);
-						}
-						cairo_save (cairoTarget);
-						cairo_translate(cairoTarget, cp_x, cp_y);
-						cairo_scale (cairoTarget, net->cirseg->width, net->cirseg->height);
-						if (net->cirseg->angle2 > net->cirseg->angle1) {
-							cairo_arc (cairoTarget, 0.0, 0.0, 0.5,
-								DEG2RAD(net->cirseg->angle1),
-								DEG2RAD(net->cirseg->angle2));
-						}
-						else {
-							cairo_arc_negative (cairoTarget, 0.0, 0.0, 0.5,
-								DEG2RAD(net->cirseg->angle1),
-								DEG2RAD(net->cirseg->angle2));
-						}
-						cairo_restore (cairoTarget);
-						draw_stroke (cairoTarget, drawMode, selectionInfo, image, net);
-						break;
-					default :
-						GERB_COMPILE_WARNING(
-							_("Unknown interpolation type: %s"),
-							_(gerbv_interpolation_name(net->interpolation)));
-						break;
-					}
-					break;
-				case GERBV_APERTURE_STATE_OFF :
-					break;
-				case GERBV_APERTURE_STATE_FLASH :
-					p = image->aperture[net->aperture]->parameter;
-
-					cairo_save (cairoTarget);
-					draw_cairo_translate_adjust(cairoTarget, x2, y2, pixelOutput);
-
-					switch (image->aperture[net->aperture]->type) {
-					case GERBV_APTYPE_CIRCLE :
-						if (renderInfo->show_cross_on_drill_holes
-						&& image->layertype == GERBV_LAYERTYPE_DRILL) {
-							/* Draw center cross on drill hole */
-							cairo_set_line_width (cairoTarget, pixelWidth);
-							cairo_set_line_cap (cairoTarget, CAIRO_LINE_CAP_SQUARE);
-							r = p[0]/2.0 + hole_cross_inc_px*pixelWidth;
-							draw_cairo_cross (cairoTarget, 0, 0, r);
-							cairo_set_line_width (cairoTarget, lineWidth);
-							cairo_set_line_cap (cairoTarget, CAIRO_LINE_CAP_ROUND);
-						}
-
-						gerbv_draw_circle(cairoTarget, p[0]);
-						gerbv_draw_aperture_hole (cairoTarget, p[1], p[2], pixelOutput);
-						break;
-					case GERBV_APTYPE_RECTANGLE :
-						// some CAD programs use very thin flashed rectangles to compose
-						//	logos/images, so we must make sure those display here
-						displayPixel = pixelOutput;
-						p0 = p[0];
-						p1 = p[1];
-						if (limitLineWidth && (p[0] < pixelWidth) && pixelOutput) {
-							p0 = pixelWidth;
-							displayPixel = FALSE;
-						}
-						if (limitLineWidth && (p[1] < pixelWidth) && pixelOutput) {
-							p1 = pixelWidth;
-							displayPixel = FALSE;
-						}
-						gerbv_draw_rectangle(cairoTarget, p0, p1, displayPixel);
-						gerbv_draw_aperture_hole (cairoTarget, p[2], p[3], displayPixel);
-						break;
-					case GERBV_APTYPE_OVAL :
-						gerbv_draw_oblong(cairoTarget, p[0], p[1]);
-						gerbv_draw_aperture_hole (cairoTarget, p[2], p[3], pixelOutput);
-						break;
-					case GERBV_APTYPE_POLYGON :
-						gerbv_draw_polygon(cairoTarget, p[0], p[1], p[2]);
-						gerbv_draw_aperture_hole (cairoTarget, p[3], p[4], pixelOutput);
-						break;
-					case GERBV_APTYPE_MACRO :
-/* TODO: to do it properly for vector export (doVectorExportFix) draw all
- * macros with some vector library with logical operators */
-						gerbv_draw_amacro(cairoTarget, drawOperatorClear, drawOperatorDark,
-							image->aperture[net->aperture]->simplified,
-							(gint)p[0], pixelWidth,
-							drawMode, selectionInfo, image, net);
-						break;
-					default :
-						GERB_COMPILE_WARNING(
-							_("Unknown aperture type: %s"),
-							_(gerbv_aperture_type_name(
-								image->aperture[net->aperture]->type)));
-						return 0;
-					}
-
-					/* And finally fill the path */
-					if (doVectorExportFix
-					&& CAIRO_OPERATOR_CLEAR ==
-					cairo_get_operator (cairoTarget)) {
-						cairo_set_source_rgba (
-								cairoTarget,
-								bg_r, bg_g,
-								bg_b, 1.0);
-						cairo_set_operator (cairoTarget,
-							CAIRO_OPERATOR_OVER);
-					}
-
-					draw_fill (cairoTarget, drawMode, selectionInfo, image, net);
-					cairo_restore (cairoTarget);
-					break;
-				default:
-					GERB_COMPILE_WARNING(
-						_("Unknown aperture state: %s"),
-						_(gerbv_aperture_type_name(
-							net->aperture_state)));
-
-					return 0;
-				}
-			}
-		}
-	}
-
-	/* restore the initial two state saves (one for layer, one for netstate)*/
-	cairo_restore (cairoTarget);
-	cairo_restore (cairoTarget);
-
-	return 1;
+draw_image_to_cairo_target(
+    cairo_t* cairoTarget, gerbv_image_t* image, gdouble pixelWidth, enum draw_mode drawMode,
+    gerbv_selection_info_t* selectionInfo, gerbv_render_info_t* renderInfo, gboolean allowOptimization,
+    gerbv_user_transformation_t transform, gboolean pixelOutput
+) {
+    const int         hole_cross_inc_px = 8;
+    struct gerbv_net *net, *polygonStartNet = NULL;
+    double            x1, y1, x2, y2, cp_x = 0, cp_y = 0;
+    gdouble *         p, p0, p1, dx, dy, lineWidth, r;
+    gerbv_netstate_t* oldState;
+    gerbv_layer_t*    oldLayer;
+    cairo_operator_t  drawOperatorClear, drawOperatorDark;
+    gboolean          invertPolarity = FALSE, oddWidth = FALSE;
+    gdouble           minX = 0, minY = 0, maxX = 0, maxY = 0;
+    gdouble           criticalRadius;
+    gdouble           scaleX = transform.scaleX;
+    gdouble           scaleY = transform.scaleY;
+    /* Keep PNP label not mirrored */
+    gdouble  pnp_label_scale_x = 1, pnp_label_scale_y = -1;
+    gboolean limitLineWidth = TRUE;
+    gboolean displayPixel   = TRUE;
+    gboolean doVectorExportFix;
+    double   bg_r, bg_g, bg_b; /* Background color */
+
+    doVectorExportFix = draw_do_vector_export_fix(cairoTarget, &bg_r, &bg_g, &bg_b);
+
+    /* If we are scaling the image at all, ignore the line width checks
+     * since scaled up lines can still be visible */
+    if ((scaleX != 1) || (scaleY != 1)) {
+        limitLineWidth = FALSE;
+    }
+
+    if (transform.mirrorAroundX) {
+        scaleY *= -1;
+        pnp_label_scale_y = 1;
+    }
+
+    if (transform.mirrorAroundY) {
+        scaleX *= -1;
+        pnp_label_scale_x = -1;
+    }
+
+    cairo_translate(cairoTarget, transform.translateX, transform.translateY);
+    cairo_scale(cairoTarget, scaleX, scaleY);
+    cairo_rotate(cairoTarget, transform.rotation);
+
+    gboolean useOptimizations = allowOptimization;
+
+    /* If the user is using any transformations for this layer, then don't
+     * bother using rendering optimizations */
+    if (fabs(transform.translateX) > GERBV_PRECISION_LINEAR_INCH
+        || fabs(transform.translateY) > GERBV_PRECISION_LINEAR_INCH
+        || fabs(transform.scaleX - 1) > GERBV_PRECISION_LINEAR_INCH
+        || fabs(transform.scaleY - 1) > GERBV_PRECISION_LINEAR_INCH
+        || fabs(transform.rotation) > GERBV_PRECISION_ANGLE_RAD || transform.mirrorAroundX || transform.mirrorAroundY)
+        useOptimizations = FALSE;
+
+    if (useOptimizations && pixelOutput) {
+        minX = renderInfo->lowerLeftX;
+        minY = renderInfo->lowerLeftY;
+        maxX = renderInfo->lowerLeftX + (renderInfo->displayWidth / renderInfo->scaleFactorX);
+        maxY = renderInfo->lowerLeftY + (renderInfo->displayHeight / renderInfo->scaleFactorY);
+    }
+
+    /* do initial justify */
+    cairo_translate(cairoTarget, image->info->imageJustifyOffsetActualA, image->info->imageJustifyOffsetActualB);
+
+    /* set the fill rule so aperture holes are cleared correctly */
+    cairo_set_fill_rule(cairoTarget, CAIRO_FILL_RULE_EVEN_ODD);
+    /* offset image */
+    cairo_translate(cairoTarget, image->info->offsetA, image->info->offsetB);
+    /* do image rotation */
+    cairo_rotate(cairoTarget, image->info->imageRotation);
+
+    /* load in polarity operators depending on the image polarity */
+    invertPolarity = transform.inverted;
+    if (image->info->polarity == GERBV_POLARITY_NEGATIVE)
+        invertPolarity = !invertPolarity;
+    if (drawMode == DRAW_SELECTIONS)
+        invertPolarity = FALSE;
+
+    if (invertPolarity) {
+        drawOperatorClear = CAIRO_OPERATOR_OVER;
+        drawOperatorDark  = CAIRO_OPERATOR_CLEAR;
+        cairo_set_operator(cairoTarget, CAIRO_OPERATOR_OVER);
+        cairo_paint(cairoTarget);
+        cairo_set_operator(cairoTarget, CAIRO_OPERATOR_CLEAR);
+    } else {
+        drawOperatorClear = CAIRO_OPERATOR_CLEAR;
+        drawOperatorDark  = CAIRO_OPERATOR_OVER;
+    }
+
+    /* next, push two cairo states to simulate the first layer and netstate
+       translations (these will be popped when another layer or netstate is
+       started */
+    cairo_save(cairoTarget);
+    cairo_save(cairoTarget);
+
+    /* store the current layer and netstate so we know when they change */
+    oldLayer = image->layers;
+    oldState = image->states;
+
+    const char* pnp_net_label_str_prev = NULL;
+
+    for (net = image->netlist->next; net != NULL; net = gerbv_image_return_next_renderable_object(net)) {
+
+        /* check if this is a new layer */
+        if (net->layer != oldLayer) {
+            /* it's a new layer, so recalculate the new transformation matrix
+               for it */
+            cairo_restore(cairoTarget);
+            cairo_restore(cairoTarget);
+            cairo_save(cairoTarget);
+            /* do any rotations */
+            cairo_rotate(cairoTarget, net->layer->rotation);
+            /* handle the layer polarity */
+            if ((net->layer->polarity == GERBV_POLARITY_CLEAR) ^ invertPolarity) {
+                cairo_set_operator(cairoTarget, CAIRO_OPERATOR_CLEAR);
+                drawOperatorClear = CAIRO_OPERATOR_OVER;
+                drawOperatorDark  = CAIRO_OPERATOR_CLEAR;
+            } else {
+                cairo_set_operator(cairoTarget, CAIRO_OPERATOR_OVER);
+                drawOperatorClear = CAIRO_OPERATOR_CLEAR;
+                drawOperatorDark  = CAIRO_OPERATOR_OVER;
+            }
+
+            /* Draw any knockout areas */
+            gerbv_knockout_t* ko = &net->layer->knockout;
+            if (ko->firstInstance == TRUE) {
+                cairo_save(cairoTarget);
+
+                if (ko->polarity == GERBV_POLARITY_CLEAR) {
+                    cairo_set_operator(cairoTarget, drawOperatorClear);
+                } else {
+                    cairo_set_operator(cairoTarget, drawOperatorDark);
+                }
+
+                if (doVectorExportFix && CAIRO_OPERATOR_CLEAR == cairo_get_operator(cairoTarget)) {
+
+                    cairo_set_operator(cairoTarget, CAIRO_OPERATOR_OVER);
+                    cairo_set_source_rgba(cairoTarget, bg_r, bg_g, bg_b, 1.0);
+                }
+
+                cairo_new_path(cairoTarget);
+                cairo_rectangle(
+                    cairoTarget, ko->lowerLeftX - ko->border, ko->lowerLeftY - ko->border, ko->width + 2 * ko->border,
+                    ko->height + 2 * ko->border
+                );
+                draw_fill(cairoTarget, drawMode, selectionInfo, image, net);
+
+                cairo_restore(cairoTarget);
+            }
+
+            /* Finally, reapply old netstate transformation */
+            cairo_save(cairoTarget);
+            draw_apply_netstate_transformation(cairoTarget, net->state);
+            oldLayer = net->layer;
+        }
+
+        /* check if this is a new netstate */
+        if (net->state != oldState) {
+            /* pop the transformation matrix back to the "pre-state" state and
+               resave it */
+            cairo_restore(cairoTarget);
+            cairo_save(cairoTarget);
+            /* it's a new state, so recalculate the new transformation matrix
+               for it */
+            draw_apply_netstate_transformation(cairoTarget, net->state);
+            oldState = net->state;
+        }
+
+        /* if we are only drawing from the selection buffer, search if this net is
+           in the buffer */
+        if (drawMode == DRAW_SELECTIONS) {
+            /* this flag makes sure we don't draw any unintentional polygons...
+               if we've successfully entered a polygon (the first net matches, and
+               we don't want to check the nets inside the polygon) then
+               polygonStartNet will be set */
+            if (!polygonStartNet) {
+                if (!draw_net_is_in_selection_buffer_remove(net, selectionInfo, FALSE))
+                    continue;
+            }
+        }
+
+        /* Render any labels attached to this net */
+        /* NOTE: this is currently only used on PNP files, so we may
+           make some assumptions here... */
+        if (drawMode != DRAW_SELECTIONS && net->label
+            && (image->layertype == GERBV_LAYERTYPE_PICKANDPLACE_TOP
+                || image->layertype == GERBV_LAYERTYPE_PICKANDPLACE_BOT)
+            && g_strcmp0(net->label->str, pnp_net_label_str_prev)) {
+
+            double mark_x, mark_y;
+
+            /* Add PNP text label only one time per
+             * net and if it is not selected. */
+            pnp_net_label_str_prev = net->label->str;
+
+            if (draw_calc_pnp_mark_coords(net, &mark_x, &mark_y)) {
+                cairo_save(cairoTarget);
+
+                cairo_set_font_size(cairoTarget, 0.05);
+                cairo_move_to(cairoTarget, mark_x, mark_y);
+                cairo_scale(cairoTarget, pnp_label_scale_x, pnp_label_scale_y);
+                cairo_show_text(cairoTarget, net->label->str);
+
+                cairo_restore(cairoTarget);
+            }
+        }
+
+        /* step and repeat */
+        gerbv_step_and_repeat_t* sr = &net->layer->stepAndRepeat;
+        int                      ix, iy;
+        for (ix = 0; ix < sr->X; ix++) {
+            for (iy = 0; iy < sr->Y; iy++) {
+                double sr_x = ix * sr->dist_X;
+                double sr_y = iy * sr->dist_Y;
+
+                if (useOptimizations && pixelOutput
+                    && ((net->boundingBox.right + sr_x < minX) || (net->boundingBox.left + sr_x > maxX)
+                        || (net->boundingBox.top + sr_y < minY) || (net->boundingBox.bottom + sr_y > maxY))) {
+                    continue;
+                }
+
+                x1 = net->start_x + sr_x;
+                y1 = net->start_y + sr_y;
+                x2 = net->stop_x + sr_x;
+                y2 = net->stop_y + sr_y;
+
+                /* translate circular x,y data as well */
+                if (net->cirseg) {
+                    cp_x = net->cirseg->cp_x + sr_x;
+                    cp_y = net->cirseg->cp_y + sr_y;
+                }
+
+                /* Polygon area fill routines */
+                switch (net->interpolation) {
+                    case GERBV_INTERPOLATION_PAREA_START:
+
+                        if (doVectorExportFix && CAIRO_OPERATOR_CLEAR == cairo_get_operator(cairoTarget)) {
+
+                            cairo_save(cairoTarget);
+
+                            cairo_set_operator(cairoTarget, CAIRO_OPERATOR_OVER);
+                            cairo_set_source_rgba(cairoTarget, bg_r, bg_g, bg_b, 1.0);
+
+                            draw_render_polygon_object(
+                                net, cairoTarget, sr_x, sr_y, image, drawMode, selectionInfo, pixelOutput
+                            );
+
+                            cairo_restore(cairoTarget);
+                        } else {
+                            draw_render_polygon_object(
+                                net, cairoTarget, sr_x, sr_y, image, drawMode, selectionInfo, pixelOutput
+                            );
+                        }
+
+                        continue;
+                    case GERBV_INTERPOLATION_DELETED: continue;
+                    default: break;
+                }
+
+                /*
+                 * If aperture state is off we allow use of undefined apertures.
+                 * This happens when gerber files starts, but hasn't decided on
+                 * which aperture to use.
+                 */
+                if (image->aperture[net->aperture] == NULL)
+                    continue;
+
+                switch (net->aperture_state) {
+                    case GERBV_APERTURE_STATE_ON:
+                        /* if the aperture width is truly 0, then render as a 1 pixel width
+                           line.  0 diameter apertures are used by some programs to draw labels,
+                           etc, and they are rendered by other programs as 1 pixel wide */
+                        /* NOTE: also, make sure all lines are at least 1 pixel wide, so they
+                           always show up at low zoom levels */
+
+                        if (limitLineWidth
+                            && ((image->aperture[net->aperture]->parameter[0] < pixelWidth) && (pixelOutput)))
+                            criticalRadius = pixelWidth / 2.0;
+                        else
+                            criticalRadius = image->aperture[net->aperture]->parameter[0] / 2.0;
+                        lineWidth = criticalRadius * 2.0;
+                        // convert to a pixel integer
+                        cairo_user_to_device_distance(cairoTarget, &lineWidth, &x1);
+                        if (pixelOutput) {
+                            lineWidth = round(lineWidth);
+                            if ((int)lineWidth % 2) {
+                                oddWidth = TRUE;
+                            } else {
+                                oddWidth = FALSE;
+                            }
+                        }
+                        cairo_device_to_user_distance(cairoTarget, &lineWidth, &x1);
+                        cairo_set_line_width(cairoTarget, lineWidth);
+
+                        switch (net->interpolation) {
+                            case GERBV_INTERPOLATION_LINEARx1:
+                            case GERBV_INTERPOLATION_LINEARx10:
+                            case GERBV_INTERPOLATION_LINEARx01:
+                            case GERBV_INTERPOLATION_LINEARx001:
+                                cairo_set_line_cap(cairoTarget, CAIRO_LINE_CAP_ROUND);
+
+                                /* weed out any lines that are
+                                 * obviously not going to
+                                 * render on the visible screen */
+                                switch (image->aperture[net->aperture]->type) {
+                                    case GERBV_APTYPE_CIRCLE:
+                                        if (renderInfo->show_cross_on_drill_holes
+                                            && image->layertype == GERBV_LAYERTYPE_DRILL) {
+                                            /* Draw center crosses on slot hole */
+                                            cairo_set_line_width(cairoTarget, pixelWidth);
+                                            cairo_set_line_cap(cairoTarget, CAIRO_LINE_CAP_SQUARE);
+                                            r = image->aperture[net->aperture]->parameter[0] / 2.0
+                                              + hole_cross_inc_px * pixelWidth;
+                                            draw_cairo_cross(cairoTarget, x1, y1, r);
+                                            draw_cairo_cross(cairoTarget, x2, y2, r);
+                                            cairo_set_line_cap(cairoTarget, CAIRO_LINE_CAP_ROUND);
+                                            cairo_set_line_width(cairoTarget, lineWidth);
+                                        }
+
+                                        draw_cairo_move_to(cairoTarget, x1, y1, oddWidth, pixelOutput);
+                                        draw_cairo_line_to(cairoTarget, x2, y2, oddWidth, pixelOutput);
+
+                                        if (doVectorExportFix
+                                            && CAIRO_OPERATOR_CLEAR == cairo_get_operator(cairoTarget)) {
+                                            cairo_save(cairoTarget);
+                                            cairo_set_source_rgba(cairoTarget, bg_r, bg_g, bg_b, 1.0);
+                                            cairo_set_operator(cairoTarget, CAIRO_OPERATOR_OVER);
+
+                                            draw_stroke(cairoTarget, drawMode, selectionInfo, image, net);
+
+                                            cairo_restore(cairoTarget);
+                                        } else {
+                                            draw_stroke(cairoTarget, drawMode, selectionInfo, image, net);
+                                        }
+
+                                        break;
+                                    case GERBV_APTYPE_RECTANGLE:
+                                        dx = image->aperture[net->aperture]->parameter[0] / 2;
+                                        dy = image->aperture[net->aperture]->parameter[1] / 2;
+                                        if (x1 > x2)
+                                            dx = -dx;
+                                        if (y1 > y2)
+                                            dy = -dy;
+                                        cairo_new_path(cairoTarget);
+                                        draw_cairo_move_to(cairoTarget, x1 - dx, y1 - dy, FALSE, pixelOutput);
+                                        draw_cairo_line_to(cairoTarget, x1 - dx, y1 + dy, FALSE, pixelOutput);
+                                        draw_cairo_line_to(cairoTarget, x2 - dx, y2 + dy, FALSE, pixelOutput);
+                                        draw_cairo_line_to(cairoTarget, x2 + dx, y2 + dy, FALSE, pixelOutput);
+                                        draw_cairo_line_to(cairoTarget, x2 + dx, y2 - dy, FALSE, pixelOutput);
+                                        draw_cairo_line_to(cairoTarget, x1 + dx, y1 - dy, FALSE, pixelOutput);
+                                        draw_fill(cairoTarget, drawMode, selectionInfo, image, net);
+                                        break;
+                                    /* TODO: for now, just render ovals or polygons like a circle */
+                                    case GERBV_APTYPE_OVAL:
+                                    case GERBV_APTYPE_POLYGON:
+                                        draw_cairo_move_to(cairoTarget, x1, y1, oddWidth, pixelOutput);
+                                        draw_cairo_line_to(cairoTarget, x2, y2, oddWidth, pixelOutput);
+                                        draw_stroke(cairoTarget, drawMode, selectionInfo, image, net);
+                                        break;
+                                    /* macros can only be flashed, so ignore any that might be here */
+                                    default:
+                                        GERB_COMPILE_WARNING(
+                                            _("Unknown aperture type: %s"),
+                                            _(gerbv_aperture_type_name(image->aperture[net->aperture]->type))
+                                        );
+                                        break;
+                                }
+                                break;
+                            case GERBV_INTERPOLATION_CW_CIRCULAR:
+                            case GERBV_INTERPOLATION_CCW_CIRCULAR:
+                                /* cairo doesn't have a function to draw oval arcs, so we must
+                                 * draw an arc and stretch it by scaling different x and y values
+                                 */
+                                cairo_new_path(cairoTarget);
+                                if (image->aperture[net->aperture]->type == GERBV_APTYPE_RECTANGLE) {
+                                    cairo_set_line_cap(cairoTarget, CAIRO_LINE_CAP_SQUARE);
+                                } else {
+                                    cairo_set_line_cap(cairoTarget, CAIRO_LINE_CAP_ROUND);
+                                }
+                                cairo_save(cairoTarget);
+                                cairo_translate(cairoTarget, cp_x, cp_y);
+                                cairo_scale(cairoTarget, net->cirseg->width, net->cirseg->height);
+                                if (net->cirseg->angle2 > net->cirseg->angle1) {
+                                    cairo_arc(
+                                        cairoTarget, 0.0, 0.0, 0.5, DEG2RAD(net->cirseg->angle1),
+                                        DEG2RAD(net->cirseg->angle2)
+                                    );
+                                } else {
+                                    cairo_arc_negative(
+                                        cairoTarget, 0.0, 0.0, 0.5, DEG2RAD(net->cirseg->angle1),
+                                        DEG2RAD(net->cirseg->angle2)
+                                    );
+                                }
+                                cairo_restore(cairoTarget);
+                                draw_stroke(cairoTarget, drawMode, selectionInfo, image, net);
+                                break;
+                            default:
+                                GERB_COMPILE_WARNING(
+                                    _("Unknown interpolation type: %s"), _(gerbv_interpolation_name(net->interpolation))
+                                );
+                                break;
+                        }
+                        break;
+                    case GERBV_APERTURE_STATE_OFF: break;
+                    case GERBV_APERTURE_STATE_FLASH:
+                        p = image->aperture[net->aperture]->parameter;
+
+                        cairo_save(cairoTarget);
+                        draw_cairo_translate_adjust(cairoTarget, x2, y2, pixelOutput);
+
+                        switch (image->aperture[net->aperture]->type) {
+                            case GERBV_APTYPE_CIRCLE:
+                                if (renderInfo->show_cross_on_drill_holes
+                                    && image->layertype == GERBV_LAYERTYPE_DRILL) {
+                                    /* Draw center cross on drill hole */
+                                    cairo_set_line_width(cairoTarget, pixelWidth);
+                                    cairo_set_line_cap(cairoTarget, CAIRO_LINE_CAP_SQUARE);
+                                    r = p[0] / 2.0 + hole_cross_inc_px * pixelWidth;
+                                    draw_cairo_cross(cairoTarget, 0, 0, r);
+                                    cairo_set_line_width(cairoTarget, lineWidth);
+                                    cairo_set_line_cap(cairoTarget, CAIRO_LINE_CAP_ROUND);
+                                }
+
+                                gerbv_draw_circle(cairoTarget, p[0]);
+                                gerbv_draw_aperture_hole(cairoTarget, p[1], p[2], pixelOutput);
+                                break;
+                            case GERBV_APTYPE_RECTANGLE:
+                                // some CAD programs use very thin flashed rectangles to compose
+                                //	logos/images, so we must make sure those display here
+                                displayPixel = pixelOutput;
+                                p0           = p[0];
+                                p1           = p[1];
+                                if (limitLineWidth && (p[0] < pixelWidth) && pixelOutput) {
+                                    p0           = pixelWidth;
+                                    displayPixel = FALSE;
+                                }
+                                if (limitLineWidth && (p[1] < pixelWidth) && pixelOutput) {
+                                    p1           = pixelWidth;
+                                    displayPixel = FALSE;
+                                }
+                                gerbv_draw_rectangle(cairoTarget, p0, p1, displayPixel);
+                                gerbv_draw_aperture_hole(cairoTarget, p[2], p[3], displayPixel);
+                                break;
+                            case GERBV_APTYPE_OVAL:
+                                gerbv_draw_oblong(cairoTarget, p[0], p[1]);
+                                gerbv_draw_aperture_hole(cairoTarget, p[2], p[3], pixelOutput);
+                                break;
+                            case GERBV_APTYPE_POLYGON:
+                                gerbv_draw_polygon(cairoTarget, p[0], p[1], p[2]);
+                                gerbv_draw_aperture_hole(cairoTarget, p[3], p[4], pixelOutput);
+                                break;
+                            case GERBV_APTYPE_MACRO:
+                                /* TODO: to do it properly for vector export (doVectorExportFix) draw all
+                                 * macros with some vector library with logical operators */
+                                gerbv_draw_amacro(
+                                    cairoTarget, drawOperatorClear, drawOperatorDark,
+                                    image->aperture[net->aperture]->simplified, (gint)p[0], pixelWidth, drawMode,
+                                    selectionInfo, image, net
+                                );
+                                break;
+                            default:
+                                GERB_COMPILE_WARNING(
+                                    _("Unknown aperture type: %s"),
+                                    _(gerbv_aperture_type_name(image->aperture[net->aperture]->type))
+                                );
+                                return 0;
+                        }
+
+                        /* And finally fill the path */
+                        if (doVectorExportFix && CAIRO_OPERATOR_CLEAR == cairo_get_operator(cairoTarget)) {
+                            cairo_set_source_rgba(cairoTarget, bg_r, bg_g, bg_b, 1.0);
+                            cairo_set_operator(cairoTarget, CAIRO_OPERATOR_OVER);
+                        }
+
+                        draw_fill(cairoTarget, drawMode, selectionInfo, image, net);
+                        cairo_restore(cairoTarget);
+                        break;
+                    default:
+                        GERB_COMPILE_WARNING(
+                            _("Unknown aperture state: %s"), _(gerbv_aperture_type_name(net->aperture_state))
+                        );
+
+                        return 0;
+                }
+            }
+        }
+    }
+
+    /* restore the initial two state saves (one for layer, one for netstate)*/
+    cairo_restore(cairoTarget);
+    cairo_restore(cairoTarget);
+
+    return 1;
 }
 
 /* Check if Cairo target require the vector export fix to be done and if so try
  * to retrieve background color. */
 static gboolean
-draw_do_vector_export_fix(cairo_t *cairoTarget,
-		double *bg_red, double *bg_green, double *bg_blue)
-{
-	/* Cairo library produce _raster_ output if polygon is cleared by
-	 * negative aperture or other polygon. A workaround is to draw over
-	 * with background color instead of clearing. Drawback is: there won't
-	 * be any see thru negative opening if two layers printed one on the
-	 * another. */
-
-	switch (cairo_surface_get_type (cairo_get_target (cairoTarget))) {
-
-	case CAIRO_SURFACE_TYPE_PDF:
-	case CAIRO_SURFACE_TYPE_PS:
-	case CAIRO_SURFACE_TYPE_SVG: {
-		double *p0, *p1, *p2;
-
-		/* Get background color from cairo user data to emulate clear
-		 * operator */
-		p0 = cairo_get_user_data (cairoTarget,
-				(cairo_user_data_key_t *)0);
-		p1 = cairo_get_user_data (cairoTarget,
-				(cairo_user_data_key_t *)1);
-		p2 = cairo_get_user_data (cairoTarget,
-				(cairo_user_data_key_t *)2);
-
-		if (p0 != NULL && p1 != NULL && p2 != NULL) {
-			*bg_red =   *p0;
-			*bg_green = *p1;
-			*bg_blue =  *p2;
-		} else {
-			*bg_red = *bg_green = *bg_blue = 1.0;
-		}
-
-		break;
-	}
-
-	default:
-		return FALSE;
-	}
-
-	return TRUE;
+draw_do_vector_export_fix(cairo_t* cairoTarget, double* bg_red, double* bg_green, double* bg_blue) {
+    /* Cairo library produce _raster_ output if polygon is cleared by
+     * negative aperture or other polygon. A workaround is to draw over
+     * with background color instead of clearing. Drawback is: there won't
+     * be any see thru negative opening if two layers printed one on the
+     * another. */
+
+    switch (cairo_surface_get_type(cairo_get_target(cairoTarget))) {
+
+        case CAIRO_SURFACE_TYPE_PDF:
+        case CAIRO_SURFACE_TYPE_PS:
+        case CAIRO_SURFACE_TYPE_SVG:
+            {
+                double *p0, *p1, *p2;
+
+                /* Get background color from cairo user data to emulate clear
+                 * operator */
+                p0 = cairo_get_user_data(cairoTarget, (cairo_user_data_key_t*)0);
+                p1 = cairo_get_user_data(cairoTarget, (cairo_user_data_key_t*)1);
+                p2 = cairo_get_user_data(cairoTarget, (cairo_user_data_key_t*)2);
+
+                if (p0 != NULL && p1 != NULL && p2 != NULL) {
+                    *bg_red   = *p0;
+                    *bg_green = *p1;
+                    *bg_blue  = *p2;
+                } else {
+                    *bg_red = *bg_green = *bg_blue = 1.0;
+                }
+
+                break;
+            }
+
+        default: return FALSE;
+    }
+
+    return TRUE;
 }
diff --git a/src/draw.h b/src/draw.h
index e47e620..22abc4b 100644
--- a/src/draw.h
+++ b/src/draw.h
@@ -39,11 +39,10 @@
 /*
  * Convert a gerber image to a GDK clip mask to be used when creating pixmap
  */
-int
-draw_image_to_cairo_target (cairo_t *cairoTarget, gerbv_image_t *image,
-		gdouble pixelWidth, enum draw_mode drawMode,
-		gerbv_selection_info_t *selectionInfo,
-		gerbv_render_info_t *renderInfo, gboolean allowOptimization,
-		gerbv_user_transformation_t transform, gboolean pixelOutput);
+int draw_image_to_cairo_target(
+    cairo_t* cairoTarget, gerbv_image_t* image, gdouble pixelWidth, enum draw_mode drawMode,
+    gerbv_selection_info_t* selectionInfo, gerbv_render_info_t* renderInfo, gboolean allowOptimization,
+    gerbv_user_transformation_t transform, gboolean pixelOutput
+);
 
 #endif /* DRAW_H */
diff --git a/src/drill.c b/src/drill.c
index 895e399..e64e604 100644
--- a/src/drill.c
+++ b/src/drill.c
@@ -40,7 +40,7 @@
 #include <string.h>
 #endif
 
-#include <math.h>  /* pow() */
+#include <math.h> /* pow() */
 #include <ctype.h>
 
 #include <sys/types.h>
@@ -56,36 +56,41 @@
 #include "drill_stats.h"
 
 /* DEBUG printing.  #define DEBUG 1 in config.h to use this fcn. */
-#define dprintf if(DEBUG) printf
+#define dprintf \
+    if (DEBUG)  \
+    printf
 
-#define MAXL 200
+#define MAXL                   200
 #define DRILL_READ_DOUBLE_SIZE 32
 
 typedef enum {
-    DRILL_NONE, DRILL_HEADER, DRILL_DATA
+    DRILL_NONE,
+    DRILL_HEADER,
+    DRILL_DATA
 } drill_file_section_t;
 
 typedef enum {
-    DRILL_MODE_ABSOLUTE, DRILL_MODE_INCREMENTAL
+    DRILL_MODE_ABSOLUTE,
+    DRILL_MODE_INCREMENTAL
 } drill_coordinate_mode_t;
 
 typedef enum {
-    FMT_00_0000	/* INCH */,
-    FMT_000_000	/* METRIC 6-digit, 1 um */,
-    FMT_000_00	/* METRIC 5-digit, 10 um */,
-    FMT_0000_00	/* METRIC 6-digit, 10 um */,
-    FMT_USER	/* User defined format */
+    FMT_00_0000 /* INCH */,
+    FMT_000_000 /* METRIC 6-digit, 1 um */,
+    FMT_000_00 /* METRIC 5-digit, 10 um */,
+    FMT_0000_00 /* METRIC 6-digit, 10 um */,
+    FMT_USER /* User defined format */
 } number_fmt_t;
 
 typedef struct drill_state {
-    double curr_x;
-    double curr_y;
-    int current_tool;
-    drill_file_section_t curr_section;
+    double                  curr_x;
+    double                  curr_y;
+    int                     current_tool;
+    drill_file_section_t    curr_section;
     drill_coordinate_mode_t coordinate_mode;
-    double origin_x;
-    double origin_y;
-    gerbv_unit_t unit;
+    double                  origin_x;
+    double                  origin_y;
+    gerbv_unit_t            unit;
     /* number_format is used throughout the file itself.
 
        header_number_format is used to parse the tool definition C
@@ -98,10 +103,10 @@ typedef struct drill_state {
 
     /* 0 means we don't try to autodetect any of the other values */
     int autod;
-    
+
     /* in FMT_USER this specifies the number of digits before the
      * decimal point when doing trailing zero suppression.  Otherwise
-     * it is the number of digits *after* the decimal 
+     * it is the number of digits *after* the decimal
      * place in the file
      */
     int decimals;
@@ -109,30 +114,23 @@ typedef struct drill_state {
 } drill_state_t;
 
 /* Local function prototypes */
-static drill_g_code_t drill_parse_G_code(gerb_file_t *fd,
-				gerbv_image_t *image, ssize_t file_line);
-static drill_m_code_t drill_parse_M_code(gerb_file_t *fd, drill_state_t *state,
-				gerbv_image_t *image, ssize_t file_line);
-static int drill_parse_T_code(gerb_file_t *fd, drill_state_t *state,
-				gerbv_image_t *image, ssize_t file_line);
-static int drill_parse_header_is_metric(gerb_file_t *fd, drill_state_t *state,
-				gerbv_image_t *image, ssize_t file_line);
-static int drill_parse_header_is_metric_comment(gerb_file_t *fd, drill_state_t *state,
-                                                gerbv_image_t *image, ssize_t file_line);
-static int drill_parse_header_is_inch(gerb_file_t *fd, drill_state_t *state,
-				gerbv_image_t *image, ssize_t file_line);
-static int drill_parse_header_is_ici(gerb_file_t *fd, drill_state_t *state,
-				gerbv_image_t *image, ssize_t file_line);
-static void drill_parse_coordinate(gerb_file_t *fd, char firstchar,
-				gerbv_image_t *image, drill_state_t *state,
-				ssize_t file_line);
-static drill_state_t *new_state(drill_state_t *state);
-static double read_double(gerb_file_t *fd, number_fmt_t fmt,
-				gerbv_omit_zeros_t omit_zeros, int decimals);
-static void eat_line(gerb_file_t *fd);
-static void eat_whitespace(gerb_file_t *fd);
-static char *get_line(gerb_file_t *fd);
-static int file_check_str(gerb_file_t *fd, const char *str);
+static drill_g_code_t drill_parse_G_code(gerb_file_t* fd, gerbv_image_t* image, ssize_t file_line);
+static drill_m_code_t
+           drill_parse_M_code(gerb_file_t* fd, drill_state_t* state, gerbv_image_t* image, ssize_t file_line);
+static int drill_parse_T_code(gerb_file_t* fd, drill_state_t* state, gerbv_image_t* image, ssize_t file_line);
+static int drill_parse_header_is_metric(gerb_file_t* fd, drill_state_t* state, gerbv_image_t* image, ssize_t file_line);
+static int
+drill_parse_header_is_metric_comment(gerb_file_t* fd, drill_state_t* state, gerbv_image_t* image, ssize_t file_line);
+static int drill_parse_header_is_inch(gerb_file_t* fd, drill_state_t* state, gerbv_image_t* image, ssize_t file_line);
+static int drill_parse_header_is_ici(gerb_file_t* fd, drill_state_t* state, gerbv_image_t* image, ssize_t file_line);
+static void
+drill_parse_coordinate(gerb_file_t* fd, char firstchar, gerbv_image_t* image, drill_state_t* state, ssize_t file_line);
+static drill_state_t* new_state(drill_state_t* state);
+static double         read_double(gerb_file_t* fd, number_fmt_t fmt, gerbv_omit_zeros_t omit_zeros, int decimals);
+static void           eat_line(gerb_file_t* fd);
+static void           eat_whitespace(gerb_file_t* fd);
+static char*          get_line(gerb_file_t* fd);
+static int            file_check_str(gerb_file_t* fd, const char* str);
 
 /* -------------------------------------------------------------- */
 /* This is the list of specific attributes a drill file may have from
@@ -145,18 +143,9 @@ enum {
     SUP_TRAIL
 };
 
-static const char *suppression_list[] = {
-    N_("None"),
-    N_("Leading"),
-    N_("Trailing"),
-    0
-};
+static const char* suppression_list[] = { N_("None"), N_("Leading"), N_("Trailing"), 0 };
 
-static const char *units_list[] = {
-    N_("inch"),
-    N_("mm"),
-    0
-};
+static const char* units_list[] = { N_("inch"), N_("mm"), 0 };
 
 enum {
     HA_auto = 0,
@@ -169,20 +158,21 @@ enum {
 };
 
 static gerbv_HID_Attribute drill_attribute_list[] = {
-    /* This should be first */
-  {N_("autodetect"), N_("Try to autodetect the file format"),
-   HID_Boolean, 0, 0, {1, 0, 0}, 0, 0, 0},
+  /* This should be first */
+    {      N_("autodetect"),N_("Try to autodetect the file format"),HID_Boolean, 0,0, { 1, 0, 0 },0, 0,0                                                                                                                                 },
 
-  {N_("zero_suppression"), N_("Zero suppression"),
-   HID_Enum, 0, 0, {0, 0, 0}, suppression_list, 0, 0},
+    {N_("zero_suppression"),                         N_("Zero suppression"),    HID_Enum, 0, 0, { 0, 0, 0 }, suppression_list, 0, 0},
 
-  {N_("units"), N_("Length units"),
-   HID_Enum, 0, 0, {0, 0, 0}, units_list, 0, 0},
+    {           N_("units"),                             N_("Length units"),    HID_Enum, 0, 0, { 0, 0, 0 },       units_list, 0, 0},
 
-  {N_("digits"), N_("Number of digits.  For trailing zero suppression,"
-   " this is the number of digits before the decimal point.  "
-   "Otherwise this is the number of digits after the decimal point."),
-   HID_Integer, 0, 20, {5, 0, 0}, 0, 0, 0},
+    {          N_("digits"),
+     N_("Number of digits.  For trailing zero suppression,"
+     " this is the number of digits before the decimal point.  "
+     "Otherwise this is the number of digits after the decimal point."),
+     HID_Integer, 0,
+     20, { 5, 0, 0 },
+     0, 0,
+     0                                                                                                                             },
 
 #if 0
   {"tool_units", "Tool size units",
@@ -191,8 +181,7 @@ static gerbv_HID_Attribute drill_attribute_list[] = {
 };
 
 void
-drill_attribute_merge (gerbv_HID_Attribute *dest, int ndest, gerbv_HID_Attribute *src, int nsrc)
-{
+drill_attribute_merge(gerbv_HID_Attribute* dest, int ndest, gerbv_HID_Attribute* src, int nsrc) {
     int i, j;
 
     /* Here is a brain dead merge algorithm which should make anyone cringe.
@@ -200,25 +189,23 @@ drill_attribute_merge (gerbv_HID_Attribute *dest, int ndest, gerbv_HID_Attribute
      * many times either.
      */
 
-    for (i = 0 ; i < nsrc ; i++) {
-	/* see if our destination wants this attribute */
-	j = 0;
-	while (j < ndest && strcmp (src[i].name, dest[j].name) != 0)
-	    j++;
-
-	/* if we wanted it and it is the same type, copy it over */
-	if (j < ndest && src[i].type == dest[j].type) {
-	    dest[j].default_val = src[i].default_val;
-	} else {
-	    GERB_MESSAGE("Ignoring \"%s\" attribute for drill file", src[i].name);
-	}
+    for (i = 0; i < nsrc; i++) {
+        /* see if our destination wants this attribute */
+        j = 0;
+        while (j < ndest && strcmp(src[i].name, dest[j].name) != 0)
+            j++;
+
+        /* if we wanted it and it is the same type, copy it over */
+        if (j < ndest && src[i].type == dest[j].type) {
+            dest[j].default_val = src[i].default_val;
+        } else {
+            GERB_MESSAGE("Ignoring \"%s\" attribute for drill file", src[i].name);
+        }
     }
 }
 
 static void
-drill_update_image_info_min_max_from_bbox(gerbv_image_info_t *info,
-		const gerbv_render_size_t *bbox)
-{
+drill_update_image_info_min_max_from_bbox(gerbv_image_info_t* info, const gerbv_render_size_t* bbox) {
     info->min_x = MIN(info->min_x, bbox->left);
     info->min_y = MIN(info->min_y, bbox->bottom);
     info->max_x = MAX(info->max_x, bbox->right);
@@ -226,51 +213,47 @@ drill_update_image_info_min_max_from_bbox(gerbv_image_info_t *info,
 }
 
 /*
- * Adds the actual drill hole to the drawing 
+ * Adds the actual drill hole to the drawing
  */
-static gerbv_net_t *
-drill_add_drill_hole (gerbv_image_t *image, drill_state_t *state,
-		gerbv_drill_stats_t *stats, gerbv_net_t *curr_net)
-{
-    gerbv_render_size_t *bbox;
-    double r;
+static gerbv_net_t*
+drill_add_drill_hole(gerbv_image_t* image, drill_state_t* state, gerbv_drill_stats_t* stats, gerbv_net_t* curr_net) {
+    gerbv_render_size_t* bbox;
+    double               r;
 
     /* Add one to drill stats  for the current tool */
-    drill_stats_increment_drill_counter(image->drill_stats->drill_list,
-	    state->current_tool);
+    drill_stats_increment_drill_counter(image->drill_stats->drill_list, state->current_tool);
 
     curr_net->next = g_new0(gerbv_net_t, 1);
     if (curr_net->next == NULL)
-	GERB_FATAL_ERROR("malloc curr_net->next failed in %s()",
-			__FUNCTION__);
+        GERB_FATAL_ERROR("malloc curr_net->next failed in %s()", __FUNCTION__);
 
-    curr_net = curr_net->next;
-    curr_net->layer = image->layers;
-    curr_net->state = image->states;
+    curr_net          = curr_net->next;
+    curr_net->layer   = image->layers;
+    curr_net->state   = image->states;
     curr_net->start_x = state->curr_x;
     curr_net->start_y = state->curr_y;
     /* KLUDGE. This function isn't allowed to return anything
        but inches */
-    if(state->unit == GERBV_UNIT_MM) {
-	curr_net->start_x /= 25.4;
-	curr_net->start_y /= 25.4;
-	/* KLUDGE. All images, regardless of input format,
-	   are returned in INCH format */
-	curr_net->state->unit = GERBV_UNIT_INCH;
+    if (state->unit == GERBV_UNIT_MM) {
+        curr_net->start_x /= 25.4;
+        curr_net->start_y /= 25.4;
+        /* KLUDGE. All images, regardless of input format,
+           are returned in INCH format */
+        curr_net->state->unit = GERBV_UNIT_INCH;
     }
 
-    curr_net->stop_x = curr_net->start_x - state->origin_x;
-    curr_net->stop_y = curr_net->start_y - state->origin_y;
-    curr_net->aperture = state->current_tool;
+    curr_net->stop_x         = curr_net->start_x - state->origin_x;
+    curr_net->stop_y         = curr_net->start_y - state->origin_y;
+    curr_net->aperture       = state->current_tool;
     curr_net->aperture_state = GERBV_APERTURE_STATE_FLASH;
 
     /* Check if aperture is set. Ignore the below instead of
        causing SEGV... */
-    if(image->aperture[state->current_tool] == NULL)
-	return curr_net;
+    if (image->aperture[state->current_tool] == NULL)
+        return curr_net;
 
     bbox = &curr_net->boundingBox;
-    r = image->aperture[state->current_tool]->parameter[0] / 2;
+    r    = image->aperture[state->current_tool]->parameter[0] / 2;
 
     /* Set boundingBox */
     bbox->left   = curr_net->start_x - r;
@@ -284,638 +267,624 @@ drill_add_drill_hole (gerbv_image_t *image, drill_state_t *state,
 }
 
 /* -------------------------------------------------------------- */
-gerbv_image_t *
-parse_drillfile(gerb_file_t *fd, gerbv_HID_Attribute *attr_list, int n_attr, int reload)
-{
-    drill_state_t *state = NULL;
-    gerbv_image_t *image = NULL;
-    gerbv_net_t *curr_net = NULL;
-    gerbv_HID_Attribute *hid_attrs;
-    int read;
-    gerbv_drill_stats_t *stats;
-    gchar *tmps;
-    ssize_t file_line = 1;
-
-    /* 
-     * many locales redefine "." as "," and so on, so sscanf and strtod 
+gerbv_image_t*
+parse_drillfile(gerb_file_t* fd, gerbv_HID_Attribute* attr_list, int n_attr, int reload) {
+    drill_state_t*       state    = NULL;
+    gerbv_image_t*       image    = NULL;
+    gerbv_net_t*         curr_net = NULL;
+    gerbv_HID_Attribute* hid_attrs;
+    int                  read;
+    gerbv_drill_stats_t* stats;
+    gchar*               tmps;
+    ssize_t              file_line = 1;
+
+    /*
+     * many locales redefine "." as "," and so on, so sscanf and strtod
      * has problems when reading files using %f format.
      * Fixes bug #1963618 reported by Lorenzo Marcantonio.
      */
-    setlocale(LC_NUMERIC, "C" );
+    setlocale(LC_NUMERIC, "C");
 
     /* Create new image for this layer */
     dprintf("In parse_drillfile, about to create image for this layer\n");
 
     image = gerbv_create_image(image, "Excellon Drill File");
     if (image == NULL)
-	GERB_FATAL_ERROR("malloc image failed in %s()", __FUNCTION__);
+        GERB_FATAL_ERROR("malloc image failed in %s()", __FUNCTION__);
 
     if (reload && attr_list != NULL) {
-      /* FIXME there should probably just be a function to copy an
-	 attribute list including using strdup as needed */
+        /* FIXME there should probably just be a function to copy an
+       attribute list including using strdup as needed */
 
-	image->info->n_attr = n_attr;
-	image->info->attr_list = gerbv_attribute_dup(attr_list, n_attr);
+        image->info->n_attr    = n_attr;
+        image->info->attr_list = gerbv_attribute_dup(attr_list, n_attr);
 
     } else {
-	/* Copy in the default attribute list for drill files.  We make a
-	 * copy here because we will allow per-layer editing of the
-	 * attributes.
-	 */
-	image->info->n_attr = sizeof (drill_attribute_list) / sizeof (drill_attribute_list[0]);
-	image->info->attr_list = gerbv_attribute_dup (drill_attribute_list, image->info->n_attr);
-
-	/* now merge any project attributes */
-	drill_attribute_merge (image->info->attr_list, image->info->n_attr,
-			 attr_list, n_attr);
+        /* Copy in the default attribute list for drill files.  We make a
+         * copy here because we will allow per-layer editing of the
+         * attributes.
+         */
+        image->info->n_attr    = sizeof(drill_attribute_list) / sizeof(drill_attribute_list[0]);
+        image->info->attr_list = gerbv_attribute_dup(drill_attribute_list, image->info->n_attr);
+
+        /* now merge any project attributes */
+        drill_attribute_merge(image->info->attr_list, image->info->n_attr, attr_list, n_attr);
     }
-    
-    curr_net = image->netlist;
-    curr_net->layer = image->layers;
-    curr_net->state = image->states;
+
+    curr_net         = image->netlist;
+    curr_net->layer  = image->layers;
+    curr_net->state  = image->states;
     image->layertype = GERBV_LAYERTYPE_DRILL;
-    stats = gerbv_drill_stats_new();
+    stats            = gerbv_drill_stats_new();
     if (stats == NULL)
-	GERB_FATAL_ERROR("malloc stats failed in %s()", __FUNCTION__);
+        GERB_FATAL_ERROR("malloc stats failed in %s()", __FUNCTION__);
     image->drill_stats = stats;
 
     /* Create local state variable to track photoplotter state */
     state = new_state(state);
     if (state == NULL)
-	GERB_FATAL_ERROR("malloc state failed in %s()", __FUNCTION__);
+        GERB_FATAL_ERROR("malloc state failed in %s()", __FUNCTION__);
 
     image->format = g_new0(gerbv_format_t, 1);
     if (image->format == NULL)
-	GERB_FATAL_ERROR("malloc format failed in %s()", __FUNCTION__);
+        GERB_FATAL_ERROR("malloc format failed in %s()", __FUNCTION__);
 
     image->format->omit_zeros = GERBV_OMIT_ZEROS_UNSPECIFIED;
 
     hid_attrs = image->info->attr_list;
 
     if (!hid_attrs[HA_auto].default_val.int_value) {
-	state->autod = 0;
-	state->number_format = FMT_USER;
-	state->decimals = hid_attrs[HA_digits].default_val.int_value;
-
-	if (GERBV_UNIT_MM == hid_attrs[HA_xy_units].default_val.int_value)
-	    state->unit = GERBV_UNIT_MM;
-
-	switch (hid_attrs[HA_suppression].default_val.int_value) {
-	case SUP_LEAD:
-	    image->format->omit_zeros = GERBV_OMIT_ZEROS_LEADING;
-	    break;
-	    
-	case SUP_TRAIL:
-	    image->format->omit_zeros = GERBV_OMIT_ZEROS_TRAILING;
-	    break;
-
-	default:
-	    image->format->omit_zeros = GERBV_OMIT_ZEROS_EXPLICIT;
-	    break;
-	}
+        state->autod         = 0;
+        state->number_format = FMT_USER;
+        state->decimals      = hid_attrs[HA_digits].default_val.int_value;
+
+        if (GERBV_UNIT_MM == hid_attrs[HA_xy_units].default_val.int_value)
+            state->unit = GERBV_UNIT_MM;
+
+        switch (hid_attrs[HA_suppression].default_val.int_value) {
+            case SUP_LEAD: image->format->omit_zeros = GERBV_OMIT_ZEROS_LEADING; break;
+
+            case SUP_TRAIL: image->format->omit_zeros = GERBV_OMIT_ZEROS_TRAILING; break;
+
+            default: image->format->omit_zeros = GERBV_OMIT_ZEROS_EXPLICIT; break;
+        }
     }
 
-    dprintf("%s():  Starting parsing of drill file \"%s\"\n",
-		    __FUNCTION__, fd->filename);
+    dprintf("%s():  Starting parsing of drill file \"%s\"\n", __FUNCTION__, fd->filename);
 
     while ((read = gerb_fgetc(fd)) != EOF) {
 
-	switch ((char) read) {
-
-	case ';' :
-	    /* Comment found. Eat rest of line */
-	    if (drill_parse_header_is_metric_comment(fd, state, image, file_line)) {
-		break;
-	    }
-	    tmps = get_line(fd);
-	    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_NOTE, -1,
-		    _("Comment \"%s\" at line %ld in file \"%s\""),
-		    tmps, file_line, fd->filename);
-	    dprintf("    Comment with ';' \"%s\" at line %ld\n",
-		    tmps, file_line);
-	    g_free(tmps);
-	    break;
-
-	case 'D' :
-	    gerb_ungetc (fd);
-	    tmps = get_line (fd);
-	    if (strcmp (tmps, "DETECT,ON") == 0 ||
-		strcmp (tmps, "DETECT,OFF") == 0) {
-		gchar *tmps2;
-		gchar *tmps3;
-		if (strcmp (tmps, "DETECT,ON") == 0)
-		    tmps3 = "ON";
-		else
-		    tmps3 = "OFF";
-
-		/* broken tool detect on/off.  Silently ignored. */
-		if (stats->detect) {
-		    tmps2 = g_strdup_printf ("%s\n%s", stats->detect, tmps3);
-		    g_free (stats->detect);
-		} else {
-		    tmps2 = g_strdup_printf ("%s", tmps3);
-		}
-		stats->detect = tmps2;
-	    } else {
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Unrecognised string \"%s\" in header "
-			    "at line %ld in file \"%s\""),
-			tmps, file_line, fd->filename);
-	    }
-	    g_free (tmps);
-	    break;
-
-	case 'F' :
-	    gerb_ungetc (fd);
-	    tmps = get_line (fd);
-
-	    /* Silently ignore FMAT,2.  Not sure what others are allowed */
-	    if (0 == strcmp (tmps, "FMAT,2")) {
-		g_free (tmps);
-		break;
-	    }
-
-	    if (0 == strcmp (tmps, "FMAT,1")) {
-		gerbv_stats_printf(stats->error_list,
-			GERBV_MESSAGE_ERROR, -1,
-			_("File in unsupported format 1 "
-			    "at line %ld in file \"%s\""),
-			file_line, fd->filename);
-
-		gerbv_destroy_image(image);
-		g_free (tmps);
-
-		return NULL;
-	    }
-	    
-	    gerbv_stats_printf(stats->error_list,
-			    GERBV_MESSAGE_ERROR, -1,
-			    _("Unrecognised string \"%s\" in header "
-				    "at line %ld in file \"%s\""),
-			    tmps, file_line, fd->filename);
-
-	    g_free (tmps);
-	    break;
-
-	case 'G': {
-	    /* Most G codes aren't used, for now */
-	    drill_g_code_t  g_code;
-
-	    switch (g_code = drill_parse_G_code(fd, image, file_line)) {
-
-	    case DRILL_G_DRILL :
-		/* Drill mode */
-		break;
-
-	    case DRILL_G_SLOT : {
-		/* Parse drilled slot end coords */
-		gerbv_render_size_t *bbox = &curr_net->boundingBox;
-		double r;
-
-		if (EOF == (read = gerb_fgetc(fd))) {
-		    gerbv_stats_printf(stats->error_list,
-			    GERBV_MESSAGE_ERROR, -1,
-			    _("Unexpected EOF found in file \"%s\""),
-			    fd->filename);
-		    break;
-		}
-
-		drill_parse_coordinate(fd, read, image, state, file_line);
-
-		/* Modify last curr_net as drilled slot */
-		curr_net->stop_x = state->curr_x;
-		curr_net->stop_y = state->curr_y;
-
-		if (state->unit == GERBV_UNIT_MM) {
-		    /* Convert to inches -- internal units */
-		    curr_net->stop_x /= 25.4;
-		    curr_net->stop_y /= 25.4;
-		}
-
-		r = image->aperture[state->current_tool]->parameter[0]/2;
-
-		/* Update boundingBox with drilled slot stop_x,y coords */
-		bbox->left   = MIN(bbox->left,   curr_net->stop_x - r);
-		bbox->right  = MAX(bbox->right,  curr_net->stop_x + r);
-		bbox->bottom = MIN(bbox->bottom, curr_net->stop_y - r);
-		bbox->top    = MAX(bbox->top,    curr_net->stop_y + r);
-
-		drill_update_image_info_min_max_from_bbox(image->info, bbox);
-
-		curr_net->aperture_state = GERBV_APERTURE_STATE_ON;
-
-		break;
-	    }
-
-	    case DRILL_G_ABSOLUTE :
-		state->coordinate_mode = DRILL_MODE_ABSOLUTE;
-		break;
-
-	    case DRILL_G_INCREMENTAL :
-		state->coordinate_mode = DRILL_MODE_INCREMENTAL;
-		break;
-
-	    case DRILL_G_ZEROSET :
-		if (EOF == (read = gerb_fgetc(fd))) {
-		    gerbv_stats_printf(stats->error_list,
-			    GERBV_MESSAGE_ERROR, -1,
-			    _("Unexpected EOF found in file \"%s\""),
-			    fd->filename);
-		    break;
-		}
-
-		drill_parse_coordinate(fd, (char)read, image,
-			state, file_line);
-		state->origin_x = state->curr_x;
-		state->origin_y = state->curr_y;
-		break;
-
-	    case DRILL_G_UNKNOWN:
-		tmps = get_line(fd);
-		gerbv_stats_printf(stats->error_list,
-			GERBV_MESSAGE_ERROR, -1,
-			_("Unrecognized string \"%s\" found "
-			    "at line %ld in file \"%s\""),
-			tmps, file_line, fd->filename);
-		g_free(tmps);
-		break;
-
-	    default:
-		eat_line(fd);
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Unsupported G%02d (%s) code "
-			    "at line %ld in file \"%s\""),
-			g_code, drill_g_code_name(g_code),
-			file_line, fd->filename);
-		break;
-	    }
-
-	    break;
-	}
-
-	case 'I':
-	    gerb_ungetc(fd); /* To compare full string in function or
-				report full string  */
-	    if (drill_parse_header_is_inch(fd, state, image, file_line))
-		break;
-
-	    if (drill_parse_header_is_ici(fd, state, image, file_line))
-		break;
-
-	    tmps = get_line(fd);
-	    gerbv_stats_printf(stats->error_list,
-		    GERBV_MESSAGE_ERROR, -1,
-		    _("Unrecognized string \"%s\" found "
-			"at line %ld in file \"%s\""),
-		    tmps, file_line, fd->filename);
-	    g_free(tmps);
-
-	    break;
-
-	case 'M': {
-	    int m_code;
-
-	    switch (m_code = drill_parse_M_code(fd, state, image, file_line)) {
-	    case DRILL_M_HEADER :
-		state->curr_section = DRILL_HEADER;
-		break;
-	    case DRILL_M_HEADEREND :
-		state->curr_section = DRILL_DATA;
-
-		if (image->format->omit_zeros == GERBV_OMIT_ZEROS_UNSPECIFIED) {
-		    /* Excellon says they default to specify leading
-		       zeros, i.e. omit trailing zeros.	 The Excellon
-		       files floating around that don't specify the
-		       leading/trailing zeros in the header seem to
-		       contradict to this though.
-
-		       XXX We should probably ask the user. */
-
-		    gerbv_stats_printf(stats->error_list,
-			    GERBV_MESSAGE_ERROR, -1,
-			    _("End of Excellon header reached "
-				"but no leading/trailing zero "
-				"handling specified "
-				"at line %ld in file \"%s\""),
-			    file_line, fd->filename);
-		    gerbv_stats_printf(stats->error_list,
-			    GERBV_MESSAGE_WARNING, -1,
-			    _("Assuming leading zeros in file \"%s\""),
-			    fd->filename);
-		    image->format->omit_zeros = GERBV_OMIT_ZEROS_LEADING;
-		}
-		break;
-	    case DRILL_M_METRIC :
-		if (state->unit == GERBV_UNIT_UNSPECIFIED
-		&&  state->curr_section != DRILL_HEADER) {
-		    double size;
-
-		    gerbv_stats_printf(stats->error_list,
-			    GERBV_MESSAGE_WARNING, -1,
-			    _("M71 code found but no METRIC "
-				"specification in header "
-				"at line %ld in file \"%s\""),
-			    file_line, fd->filename);
-		    gerbv_stats_printf(stats->error_list,
-			    GERBV_MESSAGE_WARNING, -1,
-			    _("Assuming all tool sizes are MM in file \"%s\""),
-			    fd->filename);
-
-		    stats = image->drill_stats;
-		    for (int tool_num = TOOL_MIN; tool_num < TOOL_MAX;
-			    tool_num++) {
-			if (image->aperture && image->aperture[tool_num]) {
-			    /* First update stats.   Do this before changing drill dias.
-			     * Maybe also put error into stats? */
-			    size = image->aperture[tool_num]->parameter[0];
-			    drill_stats_modify_drill_list(stats->drill_list, 
-							  tool_num, 
-							  size, 
-							  "MM");
-			    /* Now go back and update all tool dias, since
-			     * tools are displayed in inch units
-			     */
-			    image->aperture[tool_num]->parameter[0] /= 25.4;
-			}
-		    }
-		}
-		if (state->autod) {
-		    state->number_format = state->backup_number_format;
-		    state->unit = GERBV_UNIT_MM;
-		}
-		break;
-	    case DRILL_M_IMPERIAL :
-		if (state->autod) {
-		    if (state->number_format != FMT_00_0000)
-			/* save metric format definition for later */
-			state->backup_number_format = state->number_format;
-		    state->number_format = FMT_00_0000;
-		    state->decimals = 4;
-		    state->unit = GERBV_UNIT_INCH;
-		}
-
-		break;
-	    case DRILL_M_CANNEDTEXTX :
-	    case DRILL_M_CANNEDTEXTY :
-		tmps = get_line(fd);
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_NOTE, -1,
-			_("Canned text \"%s\" "
-			    "at line %ld in drill file \"%s\""),
-			tmps, file_line, fd->filename);
-		g_free(tmps);
-		break;
-	    case DRILL_M_MESSAGELONG :
-	    case DRILL_M_MESSAGE :
-		tmps = get_line(fd);
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_NOTE, -1,
-			_("Message \"%s\" embedded "
-			    "at line %ld in drill file \"%s\""),
-			tmps, file_line, fd->filename);
-		g_free(tmps);
-		break;
-	    case DRILL_M_PATTERNEND :
-	    case DRILL_M_TOOLTIPCHECK :
-		break;
-
-	    case DRILL_M_END :
-		/* M00 has optional arguments */
-		eat_line(fd);
-
-	    case DRILL_M_ENDREWIND :
-		goto drill_parse_end;
-		break;
-
-	    case DRILL_M_UNKNOWN:
-		gerb_ungetc(fd); /* To compare full string in function or
-				    report full string  */
-		if (drill_parse_header_is_metric(fd, state, image, file_line))
-		    break;
-
-		stats->M_unknown++;
-		tmps = get_line(fd);
-		gerbv_stats_printf(stats->error_list,
-			GERBV_MESSAGE_ERROR, -1,
-			_("Unrecognized string \"%s\" found "
-			    "at line %ld in file \"%s\""),
-			tmps, file_line, fd->filename);
-		g_free(tmps);
-
-		break;
-
-	    default:
-		stats->M_unknown++;
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Unsupported M%02d (%s) code found "
-			    "at line %ld in file \"%s\""),
-			m_code, _(drill_m_code_name(m_code)),
-			file_line, fd->filename);
-		break;
-	    } /* switch(m_code) */
-
-	    break;
-	} /* case 'M' */
-
-	case 'R':
-	    if (state->curr_section == DRILL_HEADER) {
-		stats->unknown++;
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Not allowed 'R' code in the header "
-			    "at line %ld in file \"%s\""),
-			file_line, fd->filename);
-	    } else {
-	      double start_x, start_y;
-	      double step_x, step_y;
-	      int c;
-	      int rcnt;
-	      /*
-	       * This is the "Repeat hole" command.  Format is:
-	       * R##[X##][Y##]
-	       * This repeats the previous hole stepping in the X and
-	       * Y increments give.  Example:
-	       * R04X0.1 -- repeats the drill hole 4 times, stepping
-	       * 0.1" in the X direction.  Note that the X and Y step
-	       * sizes default to zero if not given and that they use
-	       * the same format and units as the normal X,Y
-	       * coordinates.
-	       */
-	      stats->R++;
-
-	      start_x = state->curr_x;
-	      start_y = state->curr_y;
-
-	      /* figure out how many repeats there are */
-	      c = gerb_fgetc (fd);
-	      rcnt = 0;
-	      while ( '0' <= c && c <= '9') {
-		rcnt = 10*rcnt + (c - '0');
-		c = gerb_fgetc (fd);
-	      }
-	      dprintf ("working on R code (repeat) with a number of reps equal to %d\n", rcnt);
-
-	      step_x = 0.0;
-	      if (c == 'X') {
-		step_x = read_double(fd, state->number_format, image->format->omit_zeros, state->decimals);
-		c = gerb_fgetc (fd);
-	      }
-
-	      step_y = 0.0;
-	      if( c == 'Y') {
-		  step_y = read_double(fd, state->number_format, image->format->omit_zeros, state->decimals);
-	      } else {
-		gerb_ungetc (fd);
-	      }
-	      
-	      dprintf ("Getting ready to repeat the drill %d times with delta_x = %g, delta_y = %g\n", rcnt, step_x, step_y);
-
-	      /* spit out the drills */
-	      for (c = 1 ; c <= rcnt ; c++) {
-		state->curr_x = start_x + c*step_x;
-		state->curr_y = start_y + c*step_y;
-		dprintf ("    Repeat #%d - new location is (%g, %g)\n", c, state->curr_x, state->curr_y);
-		curr_net = drill_add_drill_hole (image, state, stats, curr_net);
-	      }
-	      
-	    }
-
-	case 'S':
-	    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_NOTE, -1,
-		    _("Ignoring setting spindle speed "
-			"at line %ld in drill file \"%s\""),
-		    file_line, fd->filename);
-	    eat_line(fd);
-	    break;
-	case 'T':
-	    drill_parse_T_code(fd, state, image, file_line);
-	    break;
-	case 'V' :
-	    gerb_ungetc (fd);
-	    tmps = get_line (fd);
-	    /* Silently ignore VER,1.  Not sure what others are allowed */
-	    if (0 != strcmp (tmps, "VER,1")) {
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_NOTE, -1,
-			_("Undefined string \"%s\" in header "
-			    "at line %ld in file \"%s\""),
-			tmps, file_line, fd->filename);
-	    }
-	    g_free (tmps);
-	    break;
-
-	case 'X':
-	case 'Y':
-	    /* Hole coordinate found. Do some parsing */
-	    drill_parse_coordinate(fd, read, image, state, file_line);
-	    
-	    /* add the new drill hole */
-	    curr_net = drill_add_drill_hole (image, state, stats, curr_net);
-	    break;
-
-	case '%':
-	    state->curr_section = DRILL_DATA;
-	    break;
-
-	case '\n' :
-	    file_line++;
-
-	    /* Get <CR> char, if any, from <LF><CR> pair */
-	    read = gerb_fgetc(fd);
-	    if (read != '\r' && read != EOF)
-		    gerb_ungetc(fd);
-	    break;
-
-	case '\r' :
-	    file_line++;
-
-	    /* Get <LF> char, if any, from <CR><LF> pair */
-	    read = gerb_fgetc(fd);
-	    if (read != '\n' && read != EOF)
-		    gerb_ungetc(fd);
-	    break;
-
-	case ' ' :	/* White space */
-	case '\t' :
-	    break;
-
-	default:
-	    stats->unknown++;
-
-	    if (DRILL_HEADER == state->curr_section) {
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Undefined code '%s' (0x%x) found in header "
-			    "at line %ld in file \"%s\""),
-			gerbv_escape_char(read), read,
-			file_line, fd->filename);
-		gerb_ungetc(fd);
-
-		/* Unrecognised crap in the header is thrown away */
-		tmps = get_line(fd);
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,
-			_("Unrecognised string \"%s\" in header "
-			    "at line %ld in file \"%s\""),
-			tmps, file_line, fd->filename);
-	  	g_free (tmps);
-	    } else {
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Ignoring undefined character '%s' (0x%x) "
-			    "found inside data at line %ld in file \"%s\""),
-			gerbv_escape_char(read), read, file_line, fd->filename);
-	    }
-	}
+        switch ((char)read) {
+
+            case ';':
+                /* Comment found. Eat rest of line */
+                if (drill_parse_header_is_metric_comment(fd, state, image, file_line)) {
+                    break;
+                }
+                tmps = get_line(fd);
+                gerbv_stats_printf(
+                    stats->error_list, GERBV_MESSAGE_NOTE, -1, _("Comment \"%s\" at line %ld in file \"%s\""), tmps,
+                    file_line, fd->filename
+                );
+                dprintf("    Comment with ';' \"%s\" at line %ld\n", tmps, file_line);
+                g_free(tmps);
+                break;
+
+            case 'D':
+                gerb_ungetc(fd);
+                tmps = get_line(fd);
+                if (strcmp(tmps, "DETECT,ON") == 0 || strcmp(tmps, "DETECT,OFF") == 0) {
+                    gchar* tmps2;
+                    gchar* tmps3;
+                    if (strcmp(tmps, "DETECT,ON") == 0)
+                        tmps3 = "ON";
+                    else
+                        tmps3 = "OFF";
+
+                    /* broken tool detect on/off.  Silently ignored. */
+                    if (stats->detect) {
+                        tmps2 = g_strdup_printf("%s\n%s", stats->detect, tmps3);
+                        g_free(stats->detect);
+                    } else {
+                        tmps2 = g_strdup_printf("%s", tmps3);
+                    }
+                    stats->detect = tmps2;
+                } else {
+                    gerbv_stats_printf(
+                        stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                        _("Unrecognised string \"%s\" in header "
+                          "at line %ld in file \"%s\""),
+                        tmps, file_line, fd->filename
+                    );
+                }
+                g_free(tmps);
+                break;
+
+            case 'F':
+                gerb_ungetc(fd);
+                tmps = get_line(fd);
+
+                /* Silently ignore FMAT,2.  Not sure what others are allowed */
+                if (0 == strcmp(tmps, "FMAT,2")) {
+                    g_free(tmps);
+                    break;
+                }
+
+                if (0 == strcmp(tmps, "FMAT,1")) {
+                    gerbv_stats_printf(
+                        stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                        _("File in unsupported format 1 "
+                          "at line %ld in file \"%s\""),
+                        file_line, fd->filename
+                    );
+
+                    gerbv_destroy_image(image);
+                    g_free(tmps);
+
+                    return NULL;
+                }
+
+                gerbv_stats_printf(
+                    stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                    _("Unrecognised string \"%s\" in header "
+                      "at line %ld in file \"%s\""),
+                    tmps, file_line, fd->filename
+                );
+
+                g_free(tmps);
+                break;
+
+            case 'G':
+                {
+                    /* Most G codes aren't used, for now */
+                    drill_g_code_t g_code;
+
+                    switch (g_code = drill_parse_G_code(fd, image, file_line)) {
+
+                        case DRILL_G_DRILL:
+                            /* Drill mode */
+                            break;
+
+                        case DRILL_G_SLOT:
+                            {
+                                /* Parse drilled slot end coords */
+                                gerbv_render_size_t* bbox = &curr_net->boundingBox;
+                                double               r;
+
+                                if (EOF == (read = gerb_fgetc(fd))) {
+                                    gerbv_stats_printf(
+                                        stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                                        _("Unexpected EOF found in file \"%s\""), fd->filename
+                                    );
+                                    break;
+                                }
+
+                                drill_parse_coordinate(fd, read, image, state, file_line);
+
+                                /* Modify last curr_net as drilled slot */
+                                curr_net->stop_x = state->curr_x;
+                                curr_net->stop_y = state->curr_y;
+
+                                if (state->unit == GERBV_UNIT_MM) {
+                                    /* Convert to inches -- internal units */
+                                    curr_net->stop_x /= 25.4;
+                                    curr_net->stop_y /= 25.4;
+                                }
+
+                                r = image->aperture[state->current_tool]->parameter[0] / 2;
+
+                                /* Update boundingBox with drilled slot stop_x,y coords */
+                                bbox->left   = MIN(bbox->left, curr_net->stop_x - r);
+                                bbox->right  = MAX(bbox->right, curr_net->stop_x + r);
+                                bbox->bottom = MIN(bbox->bottom, curr_net->stop_y - r);
+                                bbox->top    = MAX(bbox->top, curr_net->stop_y + r);
+
+                                drill_update_image_info_min_max_from_bbox(image->info, bbox);
+
+                                curr_net->aperture_state = GERBV_APERTURE_STATE_ON;
+
+                                break;
+                            }
+
+                        case DRILL_G_ABSOLUTE: state->coordinate_mode = DRILL_MODE_ABSOLUTE; break;
+
+                        case DRILL_G_INCREMENTAL: state->coordinate_mode = DRILL_MODE_INCREMENTAL; break;
+
+                        case DRILL_G_ZEROSET:
+                            if (EOF == (read = gerb_fgetc(fd))) {
+                                gerbv_stats_printf(
+                                    stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                                    _("Unexpected EOF found in file \"%s\""), fd->filename
+                                );
+                                break;
+                            }
+
+                            drill_parse_coordinate(fd, (char)read, image, state, file_line);
+                            state->origin_x = state->curr_x;
+                            state->origin_y = state->curr_y;
+                            break;
+
+                        case DRILL_G_UNKNOWN:
+                            tmps = get_line(fd);
+                            gerbv_stats_printf(
+                                stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                                _("Unrecognized string \"%s\" found "
+                                  "at line %ld in file \"%s\""),
+                                tmps, file_line, fd->filename
+                            );
+                            g_free(tmps);
+                            break;
+
+                        default:
+                            eat_line(fd);
+                            gerbv_stats_printf(
+                                stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                                _("Unsupported G%02d (%s) code "
+                                  "at line %ld in file \"%s\""),
+                                g_code, drill_g_code_name(g_code), file_line, fd->filename
+                            );
+                            break;
+                    }
+
+                    break;
+                }
+
+            case 'I':
+                gerb_ungetc(fd); /* To compare full string in function or
+                        report full string  */
+                if (drill_parse_header_is_inch(fd, state, image, file_line))
+                    break;
+
+                if (drill_parse_header_is_ici(fd, state, image, file_line))
+                    break;
+
+                tmps = get_line(fd);
+                gerbv_stats_printf(
+                    stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                    _("Unrecognized string \"%s\" found "
+                      "at line %ld in file \"%s\""),
+                    tmps, file_line, fd->filename
+                );
+                g_free(tmps);
+
+                break;
+
+            case 'M':
+                {
+                    int m_code;
+
+                    switch (m_code = drill_parse_M_code(fd, state, image, file_line)) {
+                        case DRILL_M_HEADER: state->curr_section = DRILL_HEADER; break;
+                        case DRILL_M_HEADEREND:
+                            state->curr_section = DRILL_DATA;
+
+                            if (image->format->omit_zeros == GERBV_OMIT_ZEROS_UNSPECIFIED) {
+                                /* Excellon says they default to specify leading
+                                   zeros, i.e. omit trailing zeros.	 The Excellon
+                                   files floating around that don't specify the
+                                   leading/trailing zeros in the header seem to
+                                   contradict to this though.
+
+                                   XXX We should probably ask the user. */
+
+                                gerbv_stats_printf(
+                                    stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                                    _("End of Excellon header reached "
+                                      "but no leading/trailing zero "
+                                      "handling specified "
+                                      "at line %ld in file \"%s\""),
+                                    file_line, fd->filename
+                                );
+                                gerbv_stats_printf(
+                                    stats->error_list, GERBV_MESSAGE_WARNING, -1,
+                                    _("Assuming leading zeros in file \"%s\""), fd->filename
+                                );
+                                image->format->omit_zeros = GERBV_OMIT_ZEROS_LEADING;
+                            }
+                            break;
+                        case DRILL_M_METRIC:
+                            if (state->unit == GERBV_UNIT_UNSPECIFIED && state->curr_section != DRILL_HEADER) {
+                                double size;
+
+                                gerbv_stats_printf(
+                                    stats->error_list, GERBV_MESSAGE_WARNING, -1,
+                                    _("M71 code found but no METRIC "
+                                      "specification in header "
+                                      "at line %ld in file \"%s\""),
+                                    file_line, fd->filename
+                                );
+                                gerbv_stats_printf(
+                                    stats->error_list, GERBV_MESSAGE_WARNING, -1,
+                                    _("Assuming all tool sizes are MM in file \"%s\""), fd->filename
+                                );
+
+                                stats = image->drill_stats;
+                                for (int tool_num = TOOL_MIN; tool_num < TOOL_MAX; tool_num++) {
+                                    if (image->aperture && image->aperture[tool_num]) {
+                                        /* First update stats.   Do this before changing drill dias.
+                                         * Maybe also put error into stats? */
+                                        size = image->aperture[tool_num]->parameter[0];
+                                        drill_stats_modify_drill_list(stats->drill_list, tool_num, size, "MM");
+                                        /* Now go back and update all tool dias, since
+                                         * tools are displayed in inch units
+                                         */
+                                        image->aperture[tool_num]->parameter[0] /= 25.4;
+                                    }
+                                }
+                            }
+                            if (state->autod) {
+                                state->number_format = state->backup_number_format;
+                                state->unit          = GERBV_UNIT_MM;
+                            }
+                            break;
+                        case DRILL_M_IMPERIAL:
+                            if (state->autod) {
+                                if (state->number_format != FMT_00_0000)
+                                    /* save metric format definition for later */
+                                    state->backup_number_format = state->number_format;
+                                state->number_format = FMT_00_0000;
+                                state->decimals      = 4;
+                                state->unit          = GERBV_UNIT_INCH;
+                            }
+
+                            break;
+                        case DRILL_M_CANNEDTEXTX:
+                        case DRILL_M_CANNEDTEXTY:
+                            tmps = get_line(fd);
+                            gerbv_stats_printf(
+                                stats->error_list, GERBV_MESSAGE_NOTE, -1,
+                                _("Canned text \"%s\" "
+                                  "at line %ld in drill file \"%s\""),
+                                tmps, file_line, fd->filename
+                            );
+                            g_free(tmps);
+                            break;
+                        case DRILL_M_MESSAGELONG:
+                        case DRILL_M_MESSAGE:
+                            tmps = get_line(fd);
+                            gerbv_stats_printf(
+                                stats->error_list, GERBV_MESSAGE_NOTE, -1,
+                                _("Message \"%s\" embedded "
+                                  "at line %ld in drill file \"%s\""),
+                                tmps, file_line, fd->filename
+                            );
+                            g_free(tmps);
+                            break;
+                        case DRILL_M_PATTERNEND:
+                        case DRILL_M_TOOLTIPCHECK: break;
+
+                        case DRILL_M_END:
+                            /* M00 has optional arguments */
+                            eat_line(fd);
+
+                        case DRILL_M_ENDREWIND: goto drill_parse_end; break;
+
+                        case DRILL_M_UNKNOWN:
+                            gerb_ungetc(fd); /* To compare full string in function or
+                                        report full string  */
+                            if (drill_parse_header_is_metric(fd, state, image, file_line))
+                                break;
+
+                            stats->M_unknown++;
+                            tmps = get_line(fd);
+                            gerbv_stats_printf(
+                                stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                                _("Unrecognized string \"%s\" found "
+                                  "at line %ld in file \"%s\""),
+                                tmps, file_line, fd->filename
+                            );
+                            g_free(tmps);
+
+                            break;
+
+                        default:
+                            stats->M_unknown++;
+                            gerbv_stats_printf(
+                                stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                                _("Unsupported M%02d (%s) code found "
+                                  "at line %ld in file \"%s\""),
+                                m_code, _(drill_m_code_name(m_code)), file_line, fd->filename
+                            );
+                            break;
+                    } /* switch(m_code) */
+
+                    break;
+                } /* case 'M' */
+
+            case 'R':
+                if (state->curr_section == DRILL_HEADER) {
+                    stats->unknown++;
+                    gerbv_stats_printf(
+                        stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                        _("Not allowed 'R' code in the header "
+                          "at line %ld in file \"%s\""),
+                        file_line, fd->filename
+                    );
+                } else {
+                    double start_x, start_y;
+                    double step_x, step_y;
+                    int    c;
+                    int    rcnt;
+                    /*
+                     * This is the "Repeat hole" command.  Format is:
+                     * R##[X##][Y##]
+                     * This repeats the previous hole stepping in the X and
+                     * Y increments give.  Example:
+                     * R04X0.1 -- repeats the drill hole 4 times, stepping
+                     * 0.1" in the X direction.  Note that the X and Y step
+                     * sizes default to zero if not given and that they use
+                     * the same format and units as the normal X,Y
+                     * coordinates.
+                     */
+                    stats->R++;
+
+                    start_x = state->curr_x;
+                    start_y = state->curr_y;
+
+                    /* figure out how many repeats there are */
+                    c    = gerb_fgetc(fd);
+                    rcnt = 0;
+                    while ('0' <= c && c <= '9') {
+                        rcnt = 10 * rcnt + (c - '0');
+                        c    = gerb_fgetc(fd);
+                    }
+                    dprintf("working on R code (repeat) with a number of reps equal to %d\n", rcnt);
+
+                    step_x = 0.0;
+                    if (c == 'X') {
+                        step_x = read_double(fd, state->number_format, image->format->omit_zeros, state->decimals);
+                        c      = gerb_fgetc(fd);
+                    }
+
+                    step_y = 0.0;
+                    if (c == 'Y') {
+                        step_y = read_double(fd, state->number_format, image->format->omit_zeros, state->decimals);
+                    } else {
+                        gerb_ungetc(fd);
+                    }
+
+                    dprintf(
+                        "Getting ready to repeat the drill %d times with delta_x = %g, delta_y = %g\n", rcnt, step_x,
+                        step_y
+                    );
+
+                    /* spit out the drills */
+                    for (c = 1; c <= rcnt; c++) {
+                        state->curr_x = start_x + c * step_x;
+                        state->curr_y = start_y + c * step_y;
+                        dprintf("    Repeat #%d - new location is (%g, %g)\n", c, state->curr_x, state->curr_y);
+                        curr_net = drill_add_drill_hole(image, state, stats, curr_net);
+                    }
+                }
+
+            case 'S':
+                gerbv_stats_printf(
+                    stats->error_list, GERBV_MESSAGE_NOTE, -1,
+                    _("Ignoring setting spindle speed "
+                      "at line %ld in drill file \"%s\""),
+                    file_line, fd->filename
+                );
+                eat_line(fd);
+                break;
+            case 'T': drill_parse_T_code(fd, state, image, file_line); break;
+            case 'V':
+                gerb_ungetc(fd);
+                tmps = get_line(fd);
+                /* Silently ignore VER,1.  Not sure what others are allowed */
+                if (0 != strcmp(tmps, "VER,1")) {
+                    gerbv_stats_printf(
+                        stats->error_list, GERBV_MESSAGE_NOTE, -1,
+                        _("Undefined string \"%s\" in header "
+                          "at line %ld in file \"%s\""),
+                        tmps, file_line, fd->filename
+                    );
+                }
+                g_free(tmps);
+                break;
+
+            case 'X':
+            case 'Y':
+                /* Hole coordinate found. Do some parsing */
+                drill_parse_coordinate(fd, read, image, state, file_line);
+
+                /* add the new drill hole */
+                curr_net = drill_add_drill_hole(image, state, stats, curr_net);
+                break;
+
+            case '%': state->curr_section = DRILL_DATA; break;
+
+            case '\n':
+                file_line++;
+
+                /* Get <CR> char, if any, from <LF><CR> pair */
+                read = gerb_fgetc(fd);
+                if (read != '\r' && read != EOF)
+                    gerb_ungetc(fd);
+                break;
+
+            case '\r':
+                file_line++;
+
+                /* Get <LF> char, if any, from <CR><LF> pair */
+                read = gerb_fgetc(fd);
+                if (read != '\n' && read != EOF)
+                    gerb_ungetc(fd);
+                break;
+
+            case ' ': /* White space */
+            case '\t': break;
+
+            default:
+                stats->unknown++;
+
+                if (DRILL_HEADER == state->curr_section) {
+                    gerbv_stats_printf(
+                        stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                        _("Undefined code '%s' (0x%x) found in header "
+                          "at line %ld in file \"%s\""),
+                        gerbv_escape_char(read), read, file_line, fd->filename
+                    );
+                    gerb_ungetc(fd);
+
+                    /* Unrecognised crap in the header is thrown away */
+                    tmps = get_line(fd);
+                    gerbv_stats_printf(
+                        stats->error_list, GERBV_MESSAGE_WARNING, -1,
+                        _("Unrecognised string \"%s\" in header "
+                          "at line %ld in file \"%s\""),
+                        tmps, file_line, fd->filename
+                    );
+                    g_free(tmps);
+                } else {
+                    gerbv_stats_printf(
+                        stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                        _("Ignoring undefined character '%s' (0x%x) "
+                          "found inside data at line %ld in file \"%s\""),
+                        gerbv_escape_char(read), read, file_line, fd->filename
+                    );
+                }
+        }
     }
 
-    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-	    _("No EOF found in drill file \"%s\""), fd->filename);
+    gerbv_stats_printf(
+        stats->error_list, GERBV_MESSAGE_ERROR, -1, _("No EOF found in drill file \"%s\""), fd->filename
+    );
 
 drill_parse_end:
-    dprintf ("%s():  Populating file attributes\n", __FUNCTION__);
+    dprintf("%s():  Populating file attributes\n", __FUNCTION__);
 
     hid_attrs = image->info->attr_list;
 
     switch (state->unit) {
-    case GERBV_UNIT_MM:
-	hid_attrs[HA_xy_units].default_val.int_value = GERBV_UNIT_MM;
-	break;
+        case GERBV_UNIT_MM: hid_attrs[HA_xy_units].default_val.int_value = GERBV_UNIT_MM; break;
 
-    default:
-	hid_attrs[HA_xy_units].default_val.int_value = GERBV_UNIT_INCH;
-	break;
+        default: hid_attrs[HA_xy_units].default_val.int_value = GERBV_UNIT_INCH; break;
     }
 
     switch (state->number_format) {
-    case FMT_000_00:
-    case FMT_0000_00:
-	hid_attrs[HA_digits].default_val.int_value = 2;
-	break;
-
-    case FMT_000_000:
-	hid_attrs[HA_digits].default_val.int_value = 3;
-	break;
-	
-    case FMT_00_0000:
-	hid_attrs[HA_digits].default_val.int_value = 4;
-	break;
-	
-    case FMT_USER:
-	dprintf ("%s():  Keeping user specified number of decimal places (%d)\n",
-		 __FUNCTION__,
-		 hid_attrs[HA_digits].default_val.int_value);
-	break;
-	
-    default:
-	break;
+        case FMT_000_00:
+        case FMT_0000_00: hid_attrs[HA_digits].default_val.int_value = 2; break;
+
+        case FMT_000_000: hid_attrs[HA_digits].default_val.int_value = 3; break;
+
+        case FMT_00_0000: hid_attrs[HA_digits].default_val.int_value = 4; break;
+
+        case FMT_USER:
+            dprintf(
+                "%s():  Keeping user specified number of decimal places (%d)\n", __FUNCTION__,
+                hid_attrs[HA_digits].default_val.int_value
+            );
+            break;
+
+        default: break;
     }
 
     switch (image->format->omit_zeros) {
-    case GERBV_OMIT_ZEROS_LEADING:
-	hid_attrs[HA_suppression].default_val.int_value = SUP_LEAD;
-	break;
-	    
-    case GERBV_OMIT_ZEROS_TRAILING:
-	hid_attrs[HA_suppression].default_val.int_value = SUP_TRAIL;
-	break;
-
-    default:
-	hid_attrs[HA_suppression].default_val.int_value = SUP_NONE;
-	break;
+        case GERBV_OMIT_ZEROS_LEADING: hid_attrs[HA_suppression].default_val.int_value = SUP_LEAD; break;
+
+        case GERBV_OMIT_ZEROS_TRAILING: hid_attrs[HA_suppression].default_val.int_value = SUP_TRAIL; break;
+
+        default: hid_attrs[HA_suppression].default_val.int_value = SUP_NONE; break;
     }
 
     g_free(state);
@@ -923,211 +892,203 @@ drill_parse_end:
     return image;
 } /* parse_drillfile */
 
-
 /* -------------------------------------------------------------- */
 /*
  * Checks for signs that this is a drill file
  * Returns TRUE if it is, FALSE if not.
  */
 gboolean
-drill_file_p(gerb_file_t *fd, gboolean *returnFoundBinary)
-{
-    char *buf=NULL, *tbuf;
-    int len = 0;
-    char *letter;
-    int ascii;
-    int zero = 48; /* ascii 0 */
-    int nine = 57; /* ascii 9 */
-    int i;
-    gboolean found_binary = FALSE;
-    gboolean found_M48 = FALSE;
-    gboolean found_M30 = FALSE;
+drill_file_p(gerb_file_t* fd, gboolean* returnFoundBinary) {
+    char *   buf = NULL, *tbuf;
+    int      len = 0;
+    char*    letter;
+    int      ascii;
+    int      zero = 48; /* ascii 0 */
+    int      nine = 57; /* ascii 9 */
+    int      i;
+    gboolean found_binary  = FALSE;
+    gboolean found_M48     = FALSE;
+    gboolean found_M30     = FALSE;
     gboolean found_percent = FALSE;
-    gboolean found_T = FALSE;
-    gboolean found_X = FALSE;
-    gboolean found_Y = FALSE;
-    gboolean end_comments=FALSE;
- 
+    gboolean found_T       = FALSE;
+    gboolean found_X       = FALSE;
+    gboolean found_Y       = FALSE;
+    gboolean end_comments  = FALSE;
+
     tbuf = g_malloc(MAXL);
-    if (tbuf == NULL) 
-	GERB_FATAL_ERROR(
-		"malloc buf failed while checking for drill file in %s()",
-		__FUNCTION__);
+    if (tbuf == NULL)
+        GERB_FATAL_ERROR("malloc buf failed while checking for drill file in %s()", __FUNCTION__);
 
     while (fgets(tbuf, MAXL, fd->fd) != NULL) {
-	len = strlen(tbuf);
-	buf = tbuf;
-	/* check for comments at top of file.  */
-	if(!end_comments){
-		if(g_strstr_len(buf, len, ";")!=NULL){/* comments at top of file  */
-			for (i = 0; i < len-1; ++i) {
-				if (buf[i] == '\n'
-				&&  buf[i+1] != ';'
-				&&  buf[i+1] != '\r'
-				&&  buf[i+1] != '\n') {
-					end_comments = TRUE;
-					/* Set rest of parser to end of
-					 * comments */
-					buf = &tbuf[i+1];
-					
-				}
-			}
-			if(!end_comments)
-				continue;
-		}			
-		else 
-			end_comments=TRUE;
-	}
-
-	/* First look through the file for indications of its type */
-	len = strlen(buf);
-	/* check that file is not binary (non-printing chars) */
-	for (i = 0; i < len; i++) {
-	    ascii = (int) buf[i];
-	    if ((ascii > 128) || (ascii < 0)) {
-		found_binary = TRUE;
-	    }
-	}
-
-	/* Check for M48 = start of drill header */
-	if (g_strstr_len(buf, len, "M48")) {
-	    found_M48 = TRUE; 
-	}
-
-	/* Check for M30 = end of drill program */
-	if (g_strstr_len(buf, len, "M30")) {
-	    if (found_percent) {
-		found_M30 = TRUE; /* Found M30 after % = good */
-	    }
-	}
-
-	/* Check for % on its own line at end of header */
-	if ((letter = g_strstr_len(buf, len, "%")) != NULL) {
-	    if ((letter[1] ==  '\r') || (letter[1] ==  '\n'))
-		found_percent = TRUE;
-	}
-
-	/* Check for T<number> */
-	if ((letter = g_strstr_len(buf, len, "T")) != NULL) {
-	    if (!found_T && (found_X || found_Y)) {
-		found_T = FALSE;  /* Found first T after X or Y */
-	    } else {
-		if (isdigit( (int) letter[1])) { /* verify next char is digit */
-		    found_T = TRUE;
-		}
-	    }
-	}
-
-	/* look for X<number> or Y<number> */
-	if ((letter = g_strstr_len(buf, len, "X")) != NULL) {
-	    ascii = (int) letter[1]; /* grab char after X */
-	    if ((ascii >= zero) && (ascii <= nine)) {
-		found_X = TRUE;
-	    }
-	}
-	if ((letter = g_strstr_len(buf, len, "Y")) != NULL) {
-	    ascii = (int) letter[1]; /* grab char after Y */
-	    if ((ascii >= zero) && (ascii <= nine)) {
-		found_Y = TRUE;
-	    }
-	}
+        len = strlen(tbuf);
+        buf = tbuf;
+        /* check for comments at top of file.  */
+        if (!end_comments) {
+            if (g_strstr_len(buf, len, ";") != NULL) { /* comments at top of file  */
+                for (i = 0; i < len - 1; ++i) {
+                    if (buf[i] == '\n' && buf[i + 1] != ';' && buf[i + 1] != '\r' && buf[i + 1] != '\n') {
+                        end_comments = TRUE;
+                        /* Set rest of parser to end of
+                         * comments */
+                        buf = &tbuf[i + 1];
+                    }
+                }
+                if (!end_comments)
+                    continue;
+            } else
+                end_comments = TRUE;
+        }
+
+        /* First look through the file for indications of its type */
+        len = strlen(buf);
+        /* check that file is not binary (non-printing chars) */
+        for (i = 0; i < len; i++) {
+            ascii = (int)buf[i];
+            if ((ascii > 128) || (ascii < 0)) {
+                found_binary = TRUE;
+            }
+        }
+
+        /* Check for M48 = start of drill header */
+        if (g_strstr_len(buf, len, "M48")) {
+            found_M48 = TRUE;
+        }
+
+        /* Check for M30 = end of drill program */
+        if (g_strstr_len(buf, len, "M30")) {
+            if (found_percent) {
+                found_M30 = TRUE; /* Found M30 after % = good */
+            }
+        }
+
+        /* Check for % on its own line at end of header */
+        if ((letter = g_strstr_len(buf, len, "%")) != NULL) {
+            if ((letter[1] == '\r') || (letter[1] == '\n'))
+                found_percent = TRUE;
+        }
+
+        /* Check for T<number> */
+        if ((letter = g_strstr_len(buf, len, "T")) != NULL) {
+            if (!found_T && (found_X || found_Y)) {
+                found_T = FALSE; /* Found first T after X or Y */
+            } else {
+                if (isdigit((int)letter[1])) { /* verify next char is digit */
+                    found_T = TRUE;
+                }
+            }
+        }
+
+        /* look for X<number> or Y<number> */
+        if ((letter = g_strstr_len(buf, len, "X")) != NULL) {
+            ascii = (int)letter[1]; /* grab char after X */
+            if ((ascii >= zero) && (ascii <= nine)) {
+                found_X = TRUE;
+            }
+        }
+        if ((letter = g_strstr_len(buf, len, "Y")) != NULL) {
+            ascii = (int)letter[1]; /* grab char after Y */
+            if ((ascii >= zero) && (ascii <= nine)) {
+                found_Y = TRUE;
+            }
+        }
     } /* while (fgets(buf, MAXL, fd->fd) */
 
     rewind(fd->fd);
     g_free(tbuf);
     *returnFoundBinary = found_binary;
-    
+
     /* Now form logical expression determining if this is a drill file */
-    if ( ((found_X || found_Y) && found_T) && 
-	 (found_M48 || (found_percent && found_M30)) ) 
-	return TRUE;
+    if (((found_X || found_Y) && found_T) && (found_M48 || (found_percent && found_M30)))
+        return TRUE;
     else if (found_M48 && found_percent && found_M30)
-	/* Pathological case of drill file with valid header 
-	   and EOF but no drill XY locations. */
-	return TRUE;
-    else 
-	return FALSE;
+        /* Pathological case of drill file with valid header
+           and EOF but no drill XY locations. */
+        return TRUE;
+    else
+        return FALSE;
 } /* drill_file_p */
 
-
 /* -------------------------------------------------------------- */
 /* Parse tool definition. This can get a bit tricky since it can
    appear in the header and/or data section.
    Returns tool number on success, -1 on error */
 static int
-drill_parse_T_code(gerb_file_t *fd, drill_state_t *state,
-			gerbv_image_t *image, ssize_t file_line)
-{
-    int tool_num;
-    gboolean done = FALSE;
-    int temp;
-    double size;
-    gerbv_drill_stats_t *stats = image->drill_stats;
-    gerbv_aperture_t *apert;
-    gchar *tmps;
-    gchar *string;
+drill_parse_T_code(gerb_file_t* fd, drill_state_t* state, gerbv_image_t* image, ssize_t file_line) {
+    int                  tool_num;
+    gboolean             done = FALSE;
+    int                  temp;
+    double               size;
+    gerbv_drill_stats_t* stats = image->drill_stats;
+    gerbv_aperture_t*    apert;
+    gchar*               tmps;
+    gchar*               string;
 
     dprintf("---> entering %s()...\n", __FUNCTION__);
 
     /* Sneak a peek at what's hiding after the 'T'. Ugly fix for
        broken headers from Orcad, which is crap */
     temp = gerb_fgetc(fd);
-    dprintf("  Found a char '%s' (0x%02x) after the T\n",
-	    gerbv_escape_char(temp), temp);
-    
+    dprintf("  Found a char '%s' (0x%02x) after the T\n", gerbv_escape_char(temp), temp);
+
     /* might be a tool tool change stop switch on/off*/
-    if((temp == 'C') && ((fd->ptr + 2) < fd->datalen)){
-    	if(gerb_fgetc(fd) == 'S'){
-    	    if (gerb_fgetc(fd) == 'T' ){
-    	  	fd->ptr -= 4;
-    	  	tmps = get_line(fd++);
-    	  	gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_NOTE, -1,
-			_("Tool change stop switch found \"%s\" "
-			    "at line %ld in file \"%s\""),
-			tmps, file_line, fd->filename);
-	  	g_free (tmps);
-
-	  	return -1;
-	    }
-	    gerb_ungetc(fd);
-	}
-	gerb_ungetc(fd);
+    if ((temp == 'C') && ((fd->ptr + 2) < fd->datalen)) {
+        if (gerb_fgetc(fd) == 'S') {
+            if (gerb_fgetc(fd) == 'T') {
+                fd->ptr -= 4;
+                tmps = get_line(fd++);
+                gerbv_stats_printf(
+                    stats->error_list, GERBV_MESSAGE_NOTE, -1,
+                    _("Tool change stop switch found \"%s\" "
+                      "at line %ld in file \"%s\""),
+                    tmps, file_line, fd->filename
+                );
+                g_free(tmps);
+
+                return -1;
+            }
+            gerb_ungetc(fd);
+        }
+        gerb_ungetc(fd);
     }
 
-    if( !(isdigit(temp) != 0 || temp == '+' || temp =='-') ) {
-	if(temp != EOF) {
-	    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-		   _("OrCAD bug: Junk text found in place of tool definition"));
-	    tmps = get_line(fd);
-	    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,
-		    _("Junk text \"%s\" "
-			"at line %ld in file \"%s\""),
-		    tmps, file_line, fd->filename);
-	    g_free (tmps);
-	    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,
-				  _("Ignoring junk text"));
-	}
-	return -1;
+    if (!(isdigit(temp) != 0 || temp == '+' || temp == '-')) {
+        if (temp != EOF) {
+            gerbv_stats_printf(
+                stats->error_list, GERBV_MESSAGE_ERROR, -1, _("OrCAD bug: Junk text found in place of tool definition")
+            );
+            tmps = get_line(fd);
+            gerbv_stats_printf(
+                stats->error_list, GERBV_MESSAGE_WARNING, -1,
+                _("Junk text \"%s\" "
+                  "at line %ld in file \"%s\""),
+                tmps, file_line, fd->filename
+            );
+            g_free(tmps);
+            gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1, _("Ignoring junk text"));
+        }
+        return -1;
     }
     gerb_ungetc(fd);
 
-    tool_num = (int) gerb_fgetint(fd, NULL);
-    dprintf ("  Handling tool T%d at line %ld\n", tool_num, file_line);
+    tool_num = (int)gerb_fgetint(fd, NULL);
+    dprintf("  Handling tool T%d at line %ld\n", tool_num, file_line);
 
-    if (tool_num == 0) 
-	return tool_num; /* T00 is a command to unload the drill */
+    if (tool_num == 0)
+        return tool_num; /* T00 is a command to unload the drill */
 
     if (tool_num < TOOL_MIN || tool_num >= TOOL_MAX) {
-	gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Out of bounds drill number %d "
-		    "at line %ld in file \"%s\""),
-		tool_num, file_line, fd->filename);
-	return -1;
+        gerbv_stats_printf(
+            stats->error_list, GERBV_MESSAGE_ERROR, -1,
+            _("Out of bounds drill number %d "
+              "at line %ld in file \"%s\""),
+            tool_num, file_line, fd->filename
+        );
+        return -1;
     }
 
     /* Set the current tool to the correct one */
     state->current_tool = tool_num;
-    apert = image->aperture[tool_num];
+    apert               = image->aperture[tool_num];
 
     /* Check for a size definition */
     temp = gerb_fgetc(fd);
@@ -1135,113 +1096,115 @@ drill_parse_T_code(gerb_file_t *fd, drill_state_t *state,
     /* This bit of code looks for a tool definition by scanning for strings
      * of form TxxC, TxxF, TxxS.  */
     while (!done) {
-	switch((char)temp) {
-	case 'C':
-	    size = read_double(fd, state->header_number_format, GERBV_OMIT_ZEROS_TRAILING, state->decimals);
-	    dprintf ("  Read a size of %g\n", size);
-
-	    if (state->unit == GERBV_UNIT_MM) {
-		size /= 25.4;
-	    } else if(size >= 4.0) {
-		/* If the drill size is >= 4 inches, assume that this
-		   must be wrong and that the units are mils.
-		   The limit being 4 inches is because the smallest drill
-		   I've ever seen used is 0,3mm(about 12mil). Half of that
-		   seemed a bit too small a margin, so a third it is */
-
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Read a drill of diameter %g inches "
-			    "at line %ld in file \"%s\""),
-			    size, file_line, fd->filename);
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,
-			_("Assuming units are mils"));
-		size /= 1000.0;
-	    }
-
-	    if (size <= 0. || size >= 10000.) {
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Unreasonable drill size %g found for drill %d "
-			    "at line %ld in file \"%s\""),
-			    size, tool_num, file_line, fd->filename);
-	    } else {
-		if (apert != NULL) {
-		    /* allow a redefine of a tool only if the new definition is exactly the same.
-		     * This avoid lots of spurious complaints with the output of some cad
-		     * tools while keeping complaints if there is a true problem
-		     */
-		    if (apert->parameter[0] != size
-		    ||  apert->type != GERBV_APTYPE_CIRCLE
-		    ||  apert->nuf_parameters != 1
-		    ||  apert->unit != GERBV_UNIT_INCH) {
-
-			gerbv_stats_printf(stats->error_list,
-				GERBV_MESSAGE_ERROR, -1,
-				_("Found redefinition of drill %d "
-				"at line %ld in file \"%s\""),
-				tool_num, file_line, fd->filename);
-		    }
-		} else {
-		    apert = image->aperture[tool_num] =
-						g_new0(gerbv_aperture_t, 1);
-		    if (apert == NULL)
-			GERB_FATAL_ERROR("malloc tool failed in %s()",
-					__FUNCTION__);
-
-		    /* There's really no way of knowing what unit the tools
-		       are defined in without sneaking a peek in the rest of
-		       the file first. That's done in drill_guess_format() */
-		    apert->parameter[0] = size;
-		    apert->type = GERBV_APTYPE_CIRCLE;
-		    apert->nuf_parameters = 1;
-		    apert->unit = GERBV_UNIT_INCH;
-		}
-	    }
-	    
-	    /* Add the tool whose definition we just found into the list
-	     * of tools for this layer used to generate statistics. */
-	    stats = image->drill_stats;
-	    string = g_strdup_printf("%s", (state->unit == GERBV_UNIT_MM ? _("mm") : _("inch")));
-	    drill_stats_add_to_drill_list(stats->drill_list, 
-					  tool_num, 
-					  state->unit == GERBV_UNIT_MM ? size*25.4 : size, 
-					  string);
-	    g_free(string);
-	    break;
-
-	case 'F':
-	case 'S' :
-	    /* Silently ignored. They're not important. */
-	    gerb_fgetint(fd, NULL);
-	    break;
-
-	default:
-	    /* Stop when finding anything but what's expected
-	       (and put it back) */
-	    gerb_ungetc(fd);
-	    done = TRUE;
-	    break;
-	}  /* switch((char)temp) */
-
-	temp = gerb_fgetc(fd);
-	if (EOF == temp) {
-	    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Unexpected EOF encountered in header of "
-			"drill file \"%s\""), fd->filename);
-
-	/* Restore new line character for processing */
-	if ('\n' == temp || '\r' == temp)
-	    gerb_ungetc(fd);
-	}
-    }   /* while(!done) */  /* Done looking at tool definitions */
+        switch ((char)temp) {
+            case 'C':
+                size = read_double(fd, state->header_number_format, GERBV_OMIT_ZEROS_TRAILING, state->decimals);
+                dprintf("  Read a size of %g\n", size);
+
+                if (state->unit == GERBV_UNIT_MM) {
+                    size /= 25.4;
+                } else if (size >= 4.0) {
+                    /* If the drill size is >= 4 inches, assume that this
+                       must be wrong and that the units are mils.
+                       The limit being 4 inches is because the smallest drill
+                       I've ever seen used is 0,3mm(about 12mil). Half of that
+                       seemed a bit too small a margin, so a third it is */
+
+                    gerbv_stats_printf(
+                        stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                        _("Read a drill of diameter %g inches "
+                          "at line %ld in file \"%s\""),
+                        size, file_line, fd->filename
+                    );
+                    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1, _("Assuming units are mils"));
+                    size /= 1000.0;
+                }
+
+                if (size <= 0. || size >= 10000.) {
+                    gerbv_stats_printf(
+                        stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                        _("Unreasonable drill size %g found for drill %d "
+                          "at line %ld in file \"%s\""),
+                        size, tool_num, file_line, fd->filename
+                    );
+                } else {
+                    if (apert != NULL) {
+                        /* allow a redefine of a tool only if the new definition is exactly the same.
+                         * This avoid lots of spurious complaints with the output of some cad
+                         * tools while keeping complaints if there is a true problem
+                         */
+                        if (apert->parameter[0] != size || apert->type != GERBV_APTYPE_CIRCLE
+                            || apert->nuf_parameters != 1 || apert->unit != GERBV_UNIT_INCH) {
+
+                            gerbv_stats_printf(
+                                stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                                _("Found redefinition of drill %d "
+                                  "at line %ld in file \"%s\""),
+                                tool_num, file_line, fd->filename
+                            );
+                        }
+                    } else {
+                        apert = image->aperture[tool_num] = g_new0(gerbv_aperture_t, 1);
+                        if (apert == NULL)
+                            GERB_FATAL_ERROR("malloc tool failed in %s()", __FUNCTION__);
+
+                        /* There's really no way of knowing what unit the tools
+                           are defined in without sneaking a peek in the rest of
+                           the file first. That's done in drill_guess_format() */
+                        apert->parameter[0]   = size;
+                        apert->type           = GERBV_APTYPE_CIRCLE;
+                        apert->nuf_parameters = 1;
+                        apert->unit           = GERBV_UNIT_INCH;
+                    }
+                }
+
+                /* Add the tool whose definition we just found into the list
+                 * of tools for this layer used to generate statistics. */
+                stats  = image->drill_stats;
+                string = g_strdup_printf("%s", (state->unit == GERBV_UNIT_MM ? _("mm") : _("inch")));
+                drill_stats_add_to_drill_list(
+                    stats->drill_list, tool_num, state->unit == GERBV_UNIT_MM ? size * 25.4 : size, string
+                );
+                g_free(string);
+                break;
+
+            case 'F':
+            case 'S':
+                /* Silently ignored. They're not important. */
+                gerb_fgetint(fd, NULL);
+                break;
+
+            default:
+                /* Stop when finding anything but what's expected
+                   (and put it back) */
+                gerb_ungetc(fd);
+                done = TRUE;
+                break;
+        } /* switch((char)temp) */
+
+        temp = gerb_fgetc(fd);
+        if (EOF == temp) {
+            gerbv_stats_printf(
+                stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                _("Unexpected EOF encountered in header of "
+                  "drill file \"%s\""),
+                fd->filename
+            );
+
+            /* Restore new line character for processing */
+            if ('\n' == temp || '\r' == temp)
+                gerb_ungetc(fd);
+        }
+    } /* while(!done) */ /* Done looking at tool definitions */
 
     /* Catch the tools that aren't defined.
        This isn't strictly a good thing, but at least something is shown */
     if (apert == NULL) {
         double dia;
 
-	apert = image->aperture[tool_num] = g_new0(gerbv_aperture_t, 1);
-	if (apert == NULL)
-	    GERB_FATAL_ERROR("malloc tool failed in %s()", __FUNCTION__);
+        apert = image->aperture[tool_num] = g_new0(gerbv_aperture_t, 1);
+        if (apert == NULL)
+            GERB_FATAL_ERROR("malloc tool failed in %s()", __FUNCTION__);
 
         /* See if we have the tool table */
         dia = gerbv_get_tool_diameter(tool_num);
@@ -1257,48 +1220,46 @@ drill_parse_T_code(gerb_file_t *fd, drill_state_t *state,
              * tool definitions inside the file never seem to use T00 at all.
              */
             if (tool_num != 0) {
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Tool %02d used without being defined "
-			    "at line %ld in file \"%s\""),
-			tool_num, file_line, fd->filename);
-		gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,
-			_("Setting a default size of %g\""), dia);
+                gerbv_stats_printf(
+                    stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                    _("Tool %02d used without being defined "
+                      "at line %ld in file \"%s\""),
+                    tool_num, file_line, fd->filename
+                );
+                gerbv_stats_printf(
+                    stats->error_list, GERBV_MESSAGE_WARNING, -1, _("Setting a default size of %g\""), dia
+                );
             }
-	}
-
-	apert->type = GERBV_APTYPE_CIRCLE;
-	apert->nuf_parameters = 1;
-	apert->parameter[0] = dia;
-
-	/* Add the tool whose definition we just found into the list
-	 * of tools for this layer used to generate statistics. */
-	if (tool_num != 0) {  /* Only add non-zero tool nums.  
-			       * Zero = unload command. */
-	    stats = image->drill_stats;
-	    string = g_strdup_printf("%s", 
-				     (state->unit == GERBV_UNIT_MM ? _("mm") : _("inch")));
-	    drill_stats_add_to_drill_list(stats->drill_list, 
-					  tool_num, 
-					  state->unit == GERBV_UNIT_MM ? dia*25.4 : dia,
-					  string);
-	    g_free(string);
-	}
-    } /* if(image->aperture[tool_num] == NULL) */	
-    
+        }
+
+        apert->type           = GERBV_APTYPE_CIRCLE;
+        apert->nuf_parameters = 1;
+        apert->parameter[0]   = dia;
+
+        /* Add the tool whose definition we just found into the list
+         * of tools for this layer used to generate statistics. */
+        if (tool_num != 0) { /* Only add non-zero tool nums.
+                              * Zero = unload command. */
+            stats  = image->drill_stats;
+            string = g_strdup_printf("%s", (state->unit == GERBV_UNIT_MM ? _("mm") : _("inch")));
+            drill_stats_add_to_drill_list(
+                stats->drill_list, tool_num, state->unit == GERBV_UNIT_MM ? dia * 25.4 : dia, string
+            );
+            g_free(string);
+        }
+    } /* if(image->aperture[tool_num] == NULL) */
+
     dprintf("<----  ...leaving %s()\n", __FUNCTION__);
 
     return tool_num;
 } /* drill_parse_T_code() */
 
-
 /* -------------------------------------------------------------- */
 static drill_m_code_t
-drill_parse_M_code(gerb_file_t *fd, drill_state_t *state,
-	gerbv_image_t *image, ssize_t file_line)
-{
-    gerbv_drill_stats_t *stats = image->drill_stats;
-    drill_m_code_t m_code;
-    char op[3];
+drill_parse_M_code(gerb_file_t* fd, drill_state_t* state, gerbv_image_t* image, ssize_t file_line) {
+    gerbv_drill_stats_t* stats = image->drill_stats;
+    drill_m_code_t       m_code;
+    char                 op[3];
 
     dprintf("---> entering %s() ...\n", __FUNCTION__);
 
@@ -1306,73 +1267,51 @@ drill_parse_M_code(gerb_file_t *fd, drill_state_t *state,
     op[1] = gerb_fgetc(fd);
     op[2] = '\0';
 
-    if (op[0] == EOF
-    ||  op[1] == EOF) {
-	gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Unexpected EOF found while parsing M-code in file \"%s\""),
-		fd->filename);
+    if (op[0] == EOF || op[1] == EOF) {
+        gerbv_stats_printf(
+            stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Unexpected EOF found while parsing M-code in file \"%s\""),
+            fd->filename
+        );
 
-	return DRILL_M_UNKNOWN;
+        return DRILL_M_UNKNOWN;
     }
 
     dprintf("  Compare M-code \"%s\" at line %ld\n", op, file_line);
 
     switch (m_code = atoi(op)) {
-    case 0:
-	/* atoi() return 0 in case of error, recheck string */
-	if (0 != strncmp(op, "00", 2)) {
-	    m_code = DRILL_M_UNKNOWN;
-	    gerb_ungetc(fd);
-	    gerb_ungetc(fd);
-	    break;
-	}
-	stats->M00++;
-	break;
-    case 1:
-	stats->M01++;
-	break;
-    case 18:
-	stats->M18++;
-	break;
-    case 25:
-	stats->M25++;
-	break;
-    case 30:
-	stats->M30++;
-	break;
-    case 45:
-	stats->M45++;
-	break;
-    case 47:
-	stats->M47++;
-	break;
-    case 48:
-	stats->M48++;
-	break;
-    case 71:
-	stats->M71++;
-	eat_line(fd);
-	break;
-    case 72:
-	stats->M72++;
-	eat_line(fd);
-	break;
-    case 95:
-	stats->M95++;
-	break;
-    case 97:
-	stats->M97++;
-	break;
-    case 98:
-	stats->M98++;
-	break;
-
-    default:
-    case DRILL_M_UNKNOWN:
-	break;
+        case 0:
+            /* atoi() return 0 in case of error, recheck string */
+            if (0 != strncmp(op, "00", 2)) {
+                m_code = DRILL_M_UNKNOWN;
+                gerb_ungetc(fd);
+                gerb_ungetc(fd);
+                break;
+            }
+            stats->M00++;
+            break;
+        case 1: stats->M01++; break;
+        case 18: stats->M18++; break;
+        case 25: stats->M25++; break;
+        case 30: stats->M30++; break;
+        case 45: stats->M45++; break;
+        case 47: stats->M47++; break;
+        case 48: stats->M48++; break;
+        case 71:
+            stats->M71++;
+            eat_line(fd);
+            break;
+        case 72:
+            stats->M72++;
+            eat_line(fd);
+            break;
+        case 95: stats->M95++; break;
+        case 97: stats->M97++; break;
+        case 98: stats->M98++; break;
+
+        default:
+        case DRILL_M_UNKNOWN: break;
     }
 
-
     dprintf("<----  ...leaving %s()\n", __FUNCTION__);
 
     return m_code;
@@ -1380,11 +1319,9 @@ drill_parse_M_code(gerb_file_t *fd, drill_state_t *state,
 
 /* -------------------------------------------------------------- */
 static int
-drill_parse_header_is_metric(gerb_file_t *fd, drill_state_t *state,
-			gerbv_image_t *image, ssize_t file_line)
-{
-    gerbv_drill_stats_t *stats = image->drill_stats;
-    char c, op[3];
+drill_parse_header_is_metric(gerb_file_t* fd, drill_state_t* state, gerbv_image_t* image, ssize_t file_line) {
+    gerbv_drill_stats_t* stats = image->drill_stats;
+    char                 c, op[3];
 
     dprintf("    %s(): entering\n", __FUNCTION__);
 
@@ -1396,132 +1333,136 @@ drill_parse_header_is_metric(gerb_file_t *fd, drill_state_t *state,
      */
 
     if (DRILL_HEADER != state->curr_section)
-	return 0;
+        return 0;
 
     switch (file_check_str(fd, "METRIC")) {
-    case -1:
-	gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Unexpected EOF found while parsing \"%s\" string "
-		    "in file \"%s\""), "METRIC", fd->filename);
-	return 0;
-
-    case 0:
-	return 0;
+        case -1:
+            gerbv_stats_printf(
+                stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                _("Unexpected EOF found while parsing \"%s\" string "
+                  "in file \"%s\""),
+                "METRIC", fd->filename
+            );
+            return 0;
+
+        case 0: return 0;
     }
 
 header_again:
 
     if (',' != gerb_fgetc(fd)) {
-	gerb_ungetc(fd);
-	eat_line(fd);
+        gerb_ungetc(fd);
+        eat_line(fd);
     } else {
-	/* Is it TZ, LZ, or zerofmt? */
-	switch (c = gerb_fgetc(fd)) {
-	case 'T':
-	case 'L':
-	    if ('Z' != gerb_fgetc(fd))
-		goto header_junk;
-
-	    if (c == 'L') {
-		dprintf ("    %s(): Detected a file that probably has "
-			"trailing zero suppression\n", __FUNCTION__);
-		if (state->autod)
-		    image->format->omit_zeros = GERBV_OMIT_ZEROS_TRAILING;
-	    } else {
-		dprintf ("    %s(): Detected a file that probably has "
-			"leading zero suppression\n", __FUNCTION__);
-		if (state->autod)
-		    image->format->omit_zeros = GERBV_OMIT_ZEROS_LEADING;
-	    }
-
-	    if (state->autod && state->number_format != FMT_USER) {
-		/* Default metric number format is 6-digit, 1 um
-		 * resolution.  The header number format (for T#C#
-		 * definitions) is fixed to that, while the number
-		 * format within the file can differ.  If the
-		 * number_format is already FMT_USER, that means that
-		 * we have set the number format in another way, maybe
-		 * with one of the altium FILE_FORMAT= style comments,
-		 * so don't do this default. */
-		state->header_number_format =
-		    state->number_format = FMT_000_000;
-		state->decimals = 3;
-	    }
-
-	    if (',' == gerb_fgetc(fd))
-		/* Anticipate number format will follow */
-		goto header_again;
-
-	    gerb_ungetc(fd);
-
-	    break;
-
-	case '0':
-	    if ('0' != gerb_fgetc(fd)
-	    ||  '0' != gerb_fgetc(fd))
-		goto header_junk;
-
-	    /* We just parsed three 0s, the remainder options
-	       so far are: .000 | .00 | 0.00 */
-	    op[0] = gerb_fgetc(fd);
-	    op[1] = gerb_fgetc(fd);
-	    op[2] = '\0';
-	    if (EOF == op[0]
-	    ||  EOF == op[1])
-		goto header_junk;
-
-	    if (0 == strcmp(op, "0.")) {
-		/* expecting FMT_0000_00,
-		   two trailing 0s must follow */
-		if ('0' != gerb_fgetc(fd)
-		||  '0' != gerb_fgetc(fd))
-		    goto header_junk;
-
-		eat_line(fd);
-
-		if (state->autod) {
-		    state->number_format = FMT_0000_00;
-		    state->decimals = 2;
-		}
-		break;
-	    }
-
-	    if (0 != strcmp(op, ".0"))
-		goto header_junk;
-
-	    /* Must be either FMT_000_000 or FMT_000_00, depending
-	     * on whether one or two 0s are following */
-	    if ('0' != gerb_fgetc(fd))
-		goto header_junk;
-
-	    if ('0' == gerb_fgetc(fd)
-	    &&  state->autod) {
-		state->number_format = FMT_000_000;
-		state->decimals = 3;
-	    } else {
-		gerb_ungetc(fd);
-
-		if (state->autod) {
-		    state->number_format = FMT_000_00;
-		    state->decimals = 2;
-		}
-	    }
-
-	    eat_line(fd);
-	    break;
-
-	default:
+        /* Is it TZ, LZ, or zerofmt? */
+        switch (c = gerb_fgetc(fd)) {
+            case 'T':
+            case 'L':
+                if ('Z' != gerb_fgetc(fd))
+                    goto header_junk;
+
+                if (c == 'L') {
+                    dprintf(
+                        "    %s(): Detected a file that probably has "
+                        "trailing zero suppression\n",
+                        __FUNCTION__
+                    );
+                    if (state->autod)
+                        image->format->omit_zeros = GERBV_OMIT_ZEROS_TRAILING;
+                } else {
+                    dprintf(
+                        "    %s(): Detected a file that probably has "
+                        "leading zero suppression\n",
+                        __FUNCTION__
+                    );
+                    if (state->autod)
+                        image->format->omit_zeros = GERBV_OMIT_ZEROS_LEADING;
+                }
+
+                if (state->autod && state->number_format != FMT_USER) {
+                    /* Default metric number format is 6-digit, 1 um
+                     * resolution.  The header number format (for T#C#
+                     * definitions) is fixed to that, while the number
+                     * format within the file can differ.  If the
+                     * number_format is already FMT_USER, that means that
+                     * we have set the number format in another way, maybe
+                     * with one of the altium FILE_FORMAT= style comments,
+                     * so don't do this default. */
+                    state->header_number_format = state->number_format = FMT_000_000;
+                    state->decimals                                    = 3;
+                }
+
+                if (',' == gerb_fgetc(fd))
+                    /* Anticipate number format will follow */
+                    goto header_again;
+
+                gerb_ungetc(fd);
+
+                break;
+
+            case '0':
+                if ('0' != gerb_fgetc(fd) || '0' != gerb_fgetc(fd))
+                    goto header_junk;
+
+                /* We just parsed three 0s, the remainder options
+                   so far are: .000 | .00 | 0.00 */
+                op[0] = gerb_fgetc(fd);
+                op[1] = gerb_fgetc(fd);
+                op[2] = '\0';
+                if (EOF == op[0] || EOF == op[1])
+                    goto header_junk;
+
+                if (0 == strcmp(op, "0.")) {
+                    /* expecting FMT_0000_00,
+                       two trailing 0s must follow */
+                    if ('0' != gerb_fgetc(fd) || '0' != gerb_fgetc(fd))
+                        goto header_junk;
+
+                    eat_line(fd);
+
+                    if (state->autod) {
+                        state->number_format = FMT_0000_00;
+                        state->decimals      = 2;
+                    }
+                    break;
+                }
+
+                if (0 != strcmp(op, ".0"))
+                    goto header_junk;
+
+                /* Must be either FMT_000_000 or FMT_000_00, depending
+                 * on whether one or two 0s are following */
+                if ('0' != gerb_fgetc(fd))
+                    goto header_junk;
+
+                if ('0' == gerb_fgetc(fd) && state->autod) {
+                    state->number_format = FMT_000_000;
+                    state->decimals      = 3;
+                } else {
+                    gerb_ungetc(fd);
+
+                    if (state->autod) {
+                        state->number_format = FMT_000_00;
+                        state->decimals      = 2;
+                    }
+                }
+
+                eat_line(fd);
+                break;
+
+            default:
 header_junk:
-	    gerb_ungetc(fd);
-	    eat_line(fd);
-
-	    gerbv_stats_printf(stats->error_list,
-		    GERBV_MESSAGE_WARNING, -1,
-		    _("Found junk after METRIC command "
-			"at line %ld in file \"%s\""),
-		    file_line, fd->filename);
-	    break;
-	}
+                gerb_ungetc(fd);
+                eat_line(fd);
+
+                gerbv_stats_printf(
+                    stats->error_list, GERBV_MESSAGE_WARNING, -1,
+                    _("Found junk after METRIC command "
+                      "at line %ld in file \"%s\""),
+                    file_line, fd->filename
+                );
+                break;
+        }
     }
 
     state->unit = GERBV_UNIT_MM;
@@ -1535,141 +1476,145 @@ header_junk:
  * Return non-zero if we find a FILE_FORMAT header, otherwise return
  * 0. */
 static int
-drill_parse_header_is_metric_comment(gerb_file_t *fd, drill_state_t *state,
-                                     gerbv_image_t *image, ssize_t file_line) {
-  gerbv_drill_stats_t *stats = image->drill_stats;
+drill_parse_header_is_metric_comment(gerb_file_t* fd, drill_state_t* state, gerbv_image_t* image, ssize_t file_line) {
+    gerbv_drill_stats_t* stats = image->drill_stats;
 
-  dprintf("    %s(): entering\n", __FUNCTION__);
-  /* The leading semicolon is already gone. */
-  if (DRILL_HEADER != state->curr_section) {
-    return 0;
-  }
-
-  switch (file_check_str(fd, "FILE_FORMAT")) {
-    case -1:
-      gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-                         _("Unexpected EOF found while parsing \"%s\" string "
-                           "in file \"%s\" on line %ld"),
-                         "FILE_FORMAT", fd->filename, file_line);
-      return 0;
-    case 0:
-      return 0;
-  }
-
-  eat_whitespace(fd);
-  if (file_check_str(fd, "=") != 1) {
-    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-                       _("Expected '=' while parsing \"%s\" string "
-                         "in file \"%s\" on line %ld"),
-                       "FILE_FORMAT", fd->filename, file_line);
-    return 0;
-  }
-  eat_whitespace(fd);
-  int len = -1;
-  gerb_fgetint(fd, &len);
-  if (len < 1) {
-    /* We've failed to read a number. */
-    gerbv_stats_printf(
-        stats->error_list, GERBV_MESSAGE_ERROR, -1,
-        _("Expected integer after '=' while parsing \"%s\" string "
-          "in file \"%s\" on line %ld"),
-        "FILE_FORMAT", fd->filename, file_line);
-    return 0;
-  }
-  eat_whitespace(fd);
-  if (file_check_str(fd, ":") != 1) {
-    gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-                       _("Expected ':' while parsing \"%s\" string "
-                         "in file \"%s\" on line %ld"),
-                       "FILE_FORMAT", fd->filename, file_line);
-    return 0;
-  }
-  eat_whitespace(fd);
-  len = -1;
-  int digits_after = gerb_fgetint(fd, &len);
-  if (len < 1) {
-    gerbv_stats_printf(
-        stats->error_list, GERBV_MESSAGE_ERROR, -1,
-        _("Expected integer after ':' while parsing \"%s\" string "
-          "in file \"%s\" on line %ld"),
-        "FILE_FORMAT", fd->filename, file_line);
-    /* We've failed to read a number. */
-    return 0;
-  }
-  state->header_number_format = state->number_format = FMT_USER;
-  state->decimals = digits_after;
-  state->autod = 0;
-  return 1;
+    dprintf("    %s(): entering\n", __FUNCTION__);
+    /* The leading semicolon is already gone. */
+    if (DRILL_HEADER != state->curr_section) {
+        return 0;
+    }
+
+    switch (file_check_str(fd, "FILE_FORMAT")) {
+        case -1:
+            gerbv_stats_printf(
+                stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                _("Unexpected EOF found while parsing \"%s\" string "
+                  "in file \"%s\" on line %ld"),
+                "FILE_FORMAT", fd->filename, file_line
+            );
+            return 0;
+        case 0: return 0;
+    }
+
+    eat_whitespace(fd);
+    if (file_check_str(fd, "=") != 1) {
+        gerbv_stats_printf(
+            stats->error_list, GERBV_MESSAGE_ERROR, -1,
+            _("Expected '=' while parsing \"%s\" string "
+              "in file \"%s\" on line %ld"),
+            "FILE_FORMAT", fd->filename, file_line
+        );
+        return 0;
+    }
+    eat_whitespace(fd);
+    int len = -1;
+    gerb_fgetint(fd, &len);
+    if (len < 1) {
+        /* We've failed to read a number. */
+        gerbv_stats_printf(
+            stats->error_list, GERBV_MESSAGE_ERROR, -1,
+            _("Expected integer after '=' while parsing \"%s\" string "
+              "in file \"%s\" on line %ld"),
+            "FILE_FORMAT", fd->filename, file_line
+        );
+        return 0;
+    }
+    eat_whitespace(fd);
+    if (file_check_str(fd, ":") != 1) {
+        gerbv_stats_printf(
+            stats->error_list, GERBV_MESSAGE_ERROR, -1,
+            _("Expected ':' while parsing \"%s\" string "
+              "in file \"%s\" on line %ld"),
+            "FILE_FORMAT", fd->filename, file_line
+        );
+        return 0;
+    }
+    eat_whitespace(fd);
+    len              = -1;
+    int digits_after = gerb_fgetint(fd, &len);
+    if (len < 1) {
+        gerbv_stats_printf(
+            stats->error_list, GERBV_MESSAGE_ERROR, -1,
+            _("Expected integer after ':' while parsing \"%s\" string "
+              "in file \"%s\" on line %ld"),
+            "FILE_FORMAT", fd->filename, file_line
+        );
+        /* We've failed to read a number. */
+        return 0;
+    }
+    state->header_number_format = state->number_format = FMT_USER;
+    state->decimals                                    = digits_after;
+    state->autod                                       = 0;
+    return 1;
 } /* drill_parse_header_is_metric_comment() */
 
 /* -------------------------------------------------------------- */
 static int
-drill_parse_header_is_inch(gerb_file_t *fd, drill_state_t *state,
-			gerbv_image_t *image, ssize_t file_line)
-{
-    gerbv_drill_stats_t *stats = image->drill_stats;
-    char c;
+drill_parse_header_is_inch(gerb_file_t* fd, drill_state_t* state, gerbv_image_t* image, ssize_t file_line) {
+    gerbv_drill_stats_t* stats = image->drill_stats;
+    char                 c;
 
     dprintf("    %s(): entering\n", __FUNCTION__);
 
-    if (DRILL_HEADER != state->curr_section) 
-	return 0;
+    if (DRILL_HEADER != state->curr_section)
+        return 0;
 
     switch (file_check_str(fd, "INCH")) {
-    case -1:
-	gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Unexpected EOF found while parsing \"%s\" string "
-		    "in file \"%s\""), "INCH", fd->filename);
-	return 0;
-
-    case 0:
-	return 0;
+        case -1:
+            gerbv_stats_printf(
+                stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                _("Unexpected EOF found while parsing \"%s\" string "
+                  "in file \"%s\""),
+                "INCH", fd->filename
+            );
+            return 0;
+
+        case 0: return 0;
     }
 
     /* Look for TZ/LZ */
     if (',' != gerb_fgetc(fd)) {
-	/* Unget the char in case we just advanced past a new line char */
-	gerb_ungetc (fd);
+        /* Unget the char in case we just advanced past a new line char */
+        gerb_ungetc(fd);
     } else {
-	c = gerb_fgetc(fd);
-	if (c != EOF && 'Z' == gerb_fgetc(fd)) {
-	    switch (c) {
-	    case 'L':
-		if (state->autod) {
-		    image->format->omit_zeros = GERBV_OMIT_ZEROS_TRAILING;
-		    state->header_number_format =
-			state->number_format = FMT_00_0000;
-		    state->decimals = 4;
-		}
-		break;
-
-	    case 'T':
-		if (state->autod) {
-		    image->format->omit_zeros = GERBV_OMIT_ZEROS_LEADING;
-		    state->header_number_format =
-			state->number_format = FMT_00_0000;
-		    state->decimals = 4;
-		}
-		break;
-
-	    default:
-		gerbv_stats_printf(stats->error_list,
-			GERBV_MESSAGE_WARNING, -1,
-			_("Found junk '%s' after "
-			    "INCH command "
-			    "at line %ld in file \"%s\""),
-			gerbv_escape_char(c),
-			file_line, fd->filename);
-		break;
-	    }
-	} else {
-	    gerbv_stats_printf(stats->error_list,
-		    GERBV_MESSAGE_WARNING, -1,
-		    _("Found junk '%s' after INCH command "
-			"at line %ld in file \"%s\""),
-		    gerbv_escape_char(c),
-		    file_line, fd->filename);
-	}
+        c = gerb_fgetc(fd);
+        if (c != EOF && 'Z' == gerb_fgetc(fd)) {
+            switch (c) {
+                case 'L':
+                    if (state->autod) {
+                        image->format->omit_zeros   = GERBV_OMIT_ZEROS_TRAILING;
+                        state->header_number_format = state->number_format = FMT_00_0000;
+                        state->decimals                                    = 4;
+                    }
+                    break;
+
+                case 'T':
+                    if (state->autod) {
+                        image->format->omit_zeros   = GERBV_OMIT_ZEROS_LEADING;
+                        state->header_number_format = state->number_format = FMT_00_0000;
+                        state->decimals                                    = 4;
+                    }
+                    break;
+
+                default:
+                    gerbv_stats_printf(
+                        stats->error_list, GERBV_MESSAGE_WARNING, -1,
+                        _("Found junk '%s' after "
+                          "INCH command "
+                          "at line %ld in file \"%s\""),
+                        gerbv_escape_char(c), file_line, fd->filename
+                    );
+                    break;
+            }
+        } else {
+            gerbv_stats_printf(
+                stats->error_list, GERBV_MESSAGE_WARNING, -1,
+                _("Found junk '%s' after INCH command "
+                  "at line %ld in file \"%s\""),
+                gerbv_escape_char(c), file_line, fd->filename
+            );
+        }
     }
 
     state->unit = GERBV_UNIT_INCH;
@@ -1680,102 +1625,83 @@ drill_parse_header_is_inch(gerb_file_t *fd, drill_state_t *state,
 /* -------------------------------------------------------------- */
 /* Check "ICI" incremental input of coordinates */
 static int
-drill_parse_header_is_ici(gerb_file_t *fd, drill_state_t *state,
-			gerbv_image_t *image, ssize_t file_line)
-{
-    gerbv_drill_stats_t *stats = image->drill_stats;
+drill_parse_header_is_ici(gerb_file_t* fd, drill_state_t* state, gerbv_image_t* image, ssize_t file_line) {
+    gerbv_drill_stats_t* stats = image->drill_stats;
 
     switch (file_check_str(fd, "ICI,ON")) {
-    case -1:
-	gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Unexpected EOF found while parsing \"%s\" string "
-		    "in file \"%s\""), "ICI,ON", fd->filename);
-	return 0;
-
-    case 1:
-	state->coordinate_mode = DRILL_MODE_INCREMENTAL;
-	return 1;
+        case -1:
+            gerbv_stats_printf(
+                stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                _("Unexpected EOF found while parsing \"%s\" string "
+                  "in file \"%s\""),
+                "ICI,ON", fd->filename
+            );
+            return 0;
+
+        case 1: state->coordinate_mode = DRILL_MODE_INCREMENTAL; return 1;
     }
 
     switch (file_check_str(fd, "ICI,OFF")) {
-    case -1:
-	gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Unexpected EOF found while parsing \"%s\" string "
-		    "in file \"%s\""), "ICI,OFF", fd->filename);
-	return 0;
-
-    case 1:
-	state->coordinate_mode = DRILL_MODE_ABSOLUTE;
-	return 1;
+        case -1:
+            gerbv_stats_printf(
+                stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                _("Unexpected EOF found while parsing \"%s\" string "
+                  "in file \"%s\""),
+                "ICI,OFF", fd->filename
+            );
+            return 0;
+
+        case 1: state->coordinate_mode = DRILL_MODE_ABSOLUTE; return 1;
     }
 
     return 0;
 } /* drill_parse_header_is_ici() */
 
 /* -------------------------------------------------------------- */
-static drill_g_code_t 
-drill_parse_G_code(gerb_file_t *fd, gerbv_image_t *image, ssize_t file_line)
-{
-    char op[3];
-    drill_g_code_t g_code;
-    gerbv_drill_stats_t *stats = image->drill_stats;
-    
+static drill_g_code_t
+drill_parse_G_code(gerb_file_t* fd, gerbv_image_t* image, ssize_t file_line) {
+    char                 op[3];
+    drill_g_code_t       g_code;
+    gerbv_drill_stats_t* stats = image->drill_stats;
+
     dprintf("---> entering %s()...\n", __FUNCTION__);
 
     op[0] = gerb_fgetc(fd);
     op[1] = gerb_fgetc(fd);
     op[2] = '\0';
 
-    if (op[0] == EOF
-    ||  op[1] == EOF) {
-	gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Unexpected EOF found while parsing G-code in file \"%s\""),
-		fd->filename);
-	return DRILL_G_UNKNOWN;
+    if (op[0] == EOF || op[1] == EOF) {
+        gerbv_stats_printf(
+            stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Unexpected EOF found while parsing G-code in file \"%s\""),
+            fd->filename
+        );
+        return DRILL_G_UNKNOWN;
     }
 
     dprintf("  Compare G-code \"%s\" at line %ld\n", op, file_line);
 
     switch (g_code = atoi(op)) {
-    case 0:
-	/* atoi() return 0 in case of error, recheck string */
-	if (0 != strncmp(op, "00", 2)) {
-	    g_code = DRILL_G_UNKNOWN;
-	    gerb_ungetc(fd);
-	    gerb_ungetc(fd);
-	    break;
-	}
-	stats->G00++;
-	break;
-    case 1:
-	stats->G01++;
-	break;
-    case 2:
-	stats->G02++;
-	break;
-    case 3:
-	stats->G03++;
-	break;
-    case 5:
-	stats->G05++;
-	break;
-    case 85:
-	stats->G85++;
-	break;
-    case 90:
-	stats->G90++;
-	break;
-    case 91:
-	stats->G91++;
-	break;
-    case 93:
-	stats->G93++;
-	break;
-
-    case DRILL_G_UNKNOWN:
-    default:
-	stats->G_unknown++;
-	break;
+        case 0:
+            /* atoi() return 0 in case of error, recheck string */
+            if (0 != strncmp(op, "00", 2)) {
+                g_code = DRILL_G_UNKNOWN;
+                gerb_ungetc(fd);
+                gerb_ungetc(fd);
+                break;
+            }
+            stats->G00++;
+            break;
+        case 1: stats->G01++; break;
+        case 2: stats->G02++; break;
+        case 3: stats->G03++; break;
+        case 5: stats->G05++; break;
+        case 85: stats->G85++; break;
+        case 90: stats->G90++; break;
+        case 91: stats->G91++; break;
+        case 93: stats->G93++; break;
+
+        case DRILL_G_UNKNOWN:
+        default: stats->G_unknown++; break;
     }
 
     dprintf("<----  ...leaving %s()\n", __FUNCTION__);
@@ -1783,237 +1709,219 @@ drill_parse_G_code(gerb_file_t *fd, gerbv_image_t *image, ssize_t file_line)
     return g_code;
 } /* drill_parse_G_code() */
 
-
 /* -------------------------------------------------------------- */
 /* Parse on drill file coordinate.
    Returns nothing, but modifies state */
 static void
-drill_parse_coordinate(gerb_file_t *fd, char firstchar,
-		       gerbv_image_t *image, drill_state_t *state,
-		       ssize_t file_line)
-{
-    gerbv_drill_stats_t *stats = image->drill_stats;
+drill_parse_coordinate(gerb_file_t* fd, char firstchar, gerbv_image_t* image, drill_state_t* state, ssize_t file_line) {
+    gerbv_drill_stats_t* stats = image->drill_stats;
 
-    double x = 0;
+    double   x       = 0;
     gboolean found_x = FALSE;
-    double y = 0;
+    double   y       = 0;
     gboolean found_y = FALSE;
 
-
     while (TRUE) {
-      if (firstchar == 'X') {
-        x = read_double(fd, state->number_format, image->format->omit_zeros, state->decimals);
-        found_x = TRUE;
-      } else if (firstchar == 'Y') {
-        y = read_double(fd, state->number_format, image->format->omit_zeros, state->decimals);
-        found_y = TRUE;
-      } else {
-        gerb_ungetc(fd);
-        break;
-      }
-      eat_whitespace(fd);
-      firstchar = gerb_fgetc(fd);
+        if (firstchar == 'X') {
+            x       = read_double(fd, state->number_format, image->format->omit_zeros, state->decimals);
+            found_x = TRUE;
+        } else if (firstchar == 'Y') {
+            y       = read_double(fd, state->number_format, image->format->omit_zeros, state->decimals);
+            found_y = TRUE;
+        } else {
+            gerb_ungetc(fd);
+            break;
+        }
+        eat_whitespace(fd);
+        firstchar = gerb_fgetc(fd);
     }
-    if(state->coordinate_mode == DRILL_MODE_ABSOLUTE) {
-      if (found_x) {
-        state->curr_x = x;
-      }
-      if (found_y) {
-        state->curr_y = y;
-      }
-    } else if(state->coordinate_mode == DRILL_MODE_INCREMENTAL) {
-      if (found_x) {
-        state->curr_x += x;
-      }
-      if (found_y) {
-        state->curr_y += y;
-      }
+    if (state->coordinate_mode == DRILL_MODE_ABSOLUTE) {
+        if (found_x) {
+            state->curr_x = x;
+        }
+        if (found_y) {
+            state->curr_y = y;
+        }
+    } else if (state->coordinate_mode == DRILL_MODE_INCREMENTAL) {
+        if (found_x) {
+            state->curr_x += x;
+        }
+        if (found_y) {
+            state->curr_y += y;
+        }
     } else {
-      gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-                         _("Coordinate mode is not absolute and not incremental "
-                           "at line %ld in file \"%s\""),
-                         file_line, fd->filename);
+        gerbv_stats_printf(
+            stats->error_list, GERBV_MESSAGE_ERROR, -1,
+            _("Coordinate mode is not absolute and not incremental "
+              "at line %ld in file \"%s\""),
+            file_line, fd->filename
+        );
     }
 } /* drill_parse_coordinate */
 
-
 /* Allocates and returns a new drill_state structure
    Returns state pointer on success, NULL on ERROR */
-static drill_state_t *
-new_state(drill_state_t *state)
-{
+static drill_state_t*
+new_state(drill_state_t* state) {
     state = g_new0(drill_state_t, 1);
     if (state != NULL) {
-	/* Init structure */
-	state->curr_section = DRILL_NONE;
-	state->coordinate_mode = DRILL_MODE_ABSOLUTE;
-	state->origin_x = 0.0;
-	state->origin_y = 0.0;
-	state->unit = GERBV_UNIT_UNSPECIFIED;
-	state->backup_number_format = FMT_000_000; /* only used for METRIC */
-	state->header_number_format = state->number_format = FMT_00_0000; /* i. e. INCH */
-	state->autod = 1;
-	state->decimals = 4;
+        /* Init structure */
+        state->curr_section         = DRILL_NONE;
+        state->coordinate_mode      = DRILL_MODE_ABSOLUTE;
+        state->origin_x             = 0.0;
+        state->origin_y             = 0.0;
+        state->unit                 = GERBV_UNIT_UNSPECIFIED;
+        state->backup_number_format = FMT_000_000;                        /* only used for METRIC */
+        state->header_number_format = state->number_format = FMT_00_0000; /* i. e. INCH */
+        state->autod                                       = 1;
+        state->decimals                                    = 4;
     }
 
     return state;
 } /* new_state */
 
-
 /* -------------------------------------------------------------- */
 /* Reads one double from fd and returns it.
    If a decimal point is found, fmt is not used. */
 static double
-read_double(gerb_file_t *fd, number_fmt_t fmt, gerbv_omit_zeros_t omit_zeros, int decimals)
-{
-    int read;
-    char temp[DRILL_READ_DOUBLE_SIZE];
+read_double(gerb_file_t* fd, number_fmt_t fmt, gerbv_omit_zeros_t omit_zeros, int decimals) {
+    int          read;
+    char         temp[DRILL_READ_DOUBLE_SIZE];
     unsigned int i = 0, ndigits = 0;
-    double result;
-    gboolean decimal_point = FALSE;
-    gboolean sign_prepend = FALSE;
+    double       result;
+    gboolean     decimal_point = FALSE;
+    gboolean     sign_prepend  = FALSE;
 
     memset(temp, 0, sizeof(temp));
 
     read = gerb_fgetc(fd);
-    while(read != EOF && i < (DRILL_READ_DOUBLE_SIZE -1) &&
-	  (isdigit(read) || read == '.' || read == ',' || read == '+' || read == '-')) {
-      if(read == ',' || read == '.') decimal_point = TRUE;
-      
-      /*
-       * FIXME -- if we are going to do this, don't we need a
-       * locale-independent strtod()?  I think pcb has one.
-       */
-      if(read == ',')
-	    read = '.'; /* adjust for strtod() */
-      
-      if(isdigit(read)) ndigits++;
-      
-	if(read == '-' || read == '+')
-	    sign_prepend = TRUE;
-
-      temp[i++] = (char)read;
-      read = gerb_fgetc(fd);
+    while (read != EOF && i < (DRILL_READ_DOUBLE_SIZE - 1)
+           && (isdigit(read) || read == '.' || read == ',' || read == '+' || read == '-')) {
+        if (read == ',' || read == '.')
+            decimal_point = TRUE;
+
+        /*
+         * FIXME -- if we are going to do this, don't we need a
+         * locale-independent strtod()?  I think pcb has one.
+         */
+        if (read == ',')
+            read = '.'; /* adjust for strtod() */
+
+        if (isdigit(read))
+            ndigits++;
+
+        if (read == '-' || read == '+')
+            sign_prepend = TRUE;
+
+        temp[i++] = (char)read;
+        read      = gerb_fgetc(fd);
     }
 
     temp[i] = 0;
     gerb_ungetc(fd);
 
     if (decimal_point) {
-	result = strtod(temp, NULL);
+        result = strtod(temp, NULL);
     } else {
-	unsigned int wantdigits;
-	double scale;
-	char tmp2[DRILL_READ_DOUBLE_SIZE];
-
-	memset(tmp2, 0, sizeof(tmp2));
-
-	/* Nothing to take care for when leading zeros are
-	   omitted. */
-	if (omit_zeros == GERBV_OMIT_ZEROS_TRAILING) {
-	    switch (fmt) {
-	    case FMT_00_0000:
-	      wantdigits = 2;
-	      break;
-
-	    case FMT_000_000:
-	      wantdigits = 3;
-	      break;
-
-	    case FMT_0000_00:
-		wantdigits = 4;
-		break;
-
-	    case FMT_000_00:
-		wantdigits = 3;
-		break;
-
-	    case FMT_USER:
-		wantdigits = decimals;
-		break;
-
-	    default:
-	      /* cannot happen, just plugs a compiler warning */
-	      fprintf(stderr, _("%s():  omit_zeros == GERBV_OMIT_ZEROS_TRAILING but fmt = %d.\n"
-		      "This should never have happened\n"), __FUNCTION__, fmt);
-	      return 0;
-	    }
-	    
-	    /* need to add an extra char for '+' or '-' */
-	    if (sign_prepend)
-	      wantdigits++;
-
-
-	    /* 
-	     * we need at least wantdigits + one for the decimal place
-	     * + one for the terminating null character
-	     */
-	    if (wantdigits > sizeof(tmp2) - 2) {
-	      fprintf(stderr, _("%s():  wantdigits = %d which exceeds the maximum allowed size\n"),
-		      __FUNCTION__, wantdigits);
-	      return 0;
-	    }
-
-	    /*
-	     * After we have read the correct number of digits
-	     * preceeding the decimal point, insert a decimal point
-	     * and append the rest of the digits.
-	     */
-	    dprintf("%s():  wantdigits = %d, strlen(\"%s\") = %ld\n",
-		    __FUNCTION__, wantdigits, temp, (long) strlen(temp));
-	    for (i = 0 ; i < wantdigits && i < strlen(temp) ; i++) {
-	      tmp2[i] = temp[i];
-	    }
-	    for ( ; i < wantdigits ; i++) {
-	      tmp2[i] = '0';
-	    }
-	    tmp2[i++] = '.';
-	    for ( ; i <= strlen(temp) ; i++) {
-	      tmp2[i] = temp[i-1];
-	    }
-	    dprintf("%s():  After dealing with trailing zero suppression, convert \"%s\"\n", __FUNCTION__, tmp2);
-	    scale = 1.0;
-	    
-	    for (i = 0 ; i <= strlen(tmp2) && i < sizeof (temp) ; i++) {
-	      temp[i] = tmp2[i];
-	    }
-
-	} else {
-
-	  /*
-	   * figure out the scale factor when we are not suppressing
-	   * trailing zeros.
-	   */
-	  switch (fmt) {
-	  case FMT_00_0000:
-	    scale = 1E-4;
-	    break;
-	    
-	  case FMT_000_000:
-	    scale = 1E-3;
-	    break;
-	    
-	  case FMT_000_00:
-	  case FMT_0000_00:
-	    scale = 1E-2;
-	    break;
-	    
-	  case FMT_USER:
-	    scale = pow (10.0, -1.0*decimals);
-	    break;
-	    
-	  default:
-	    /* cannot happen, just plugs a compiler warning */
-	    fprintf (stderr, _("%s(): Unhandled fmt ` %d\n"), __FUNCTION__, fmt);
-	    exit (1);
-	  }
-	}
-
-	result = strtod(temp, NULL) * scale;
+        unsigned int wantdigits;
+        double       scale;
+        char         tmp2[DRILL_READ_DOUBLE_SIZE];
+
+        memset(tmp2, 0, sizeof(tmp2));
+
+        /* Nothing to take care for when leading zeros are
+           omitted. */
+        if (omit_zeros == GERBV_OMIT_ZEROS_TRAILING) {
+            switch (fmt) {
+                case FMT_00_0000: wantdigits = 2; break;
+
+                case FMT_000_000: wantdigits = 3; break;
+
+                case FMT_0000_00: wantdigits = 4; break;
+
+                case FMT_000_00: wantdigits = 3; break;
+
+                case FMT_USER: wantdigits = decimals; break;
+
+                default:
+                    /* cannot happen, just plugs a compiler warning */
+                    fprintf(
+                        stderr,
+                        _("%s():  omit_zeros == GERBV_OMIT_ZEROS_TRAILING but fmt = %d.\n"
+                          "This should never have happened\n"),
+                        __FUNCTION__, fmt
+                    );
+                    return 0;
+            }
+
+            /* need to add an extra char for '+' or '-' */
+            if (sign_prepend)
+                wantdigits++;
+
+            /*
+             * we need at least wantdigits + one for the decimal place
+             * + one for the terminating null character
+             */
+            if (wantdigits > sizeof(tmp2) - 2) {
+                fprintf(
+                    stderr, _("%s():  wantdigits = %d which exceeds the maximum allowed size\n"), __FUNCTION__,
+                    wantdigits
+                );
+                return 0;
+            }
+
+            /*
+             * After we have read the correct number of digits
+             * preceeding the decimal point, insert a decimal point
+             * and append the rest of the digits.
+             */
+            dprintf(
+                "%s():  wantdigits = %d, strlen(\"%s\") = %ld\n", __FUNCTION__, wantdigits, temp, (long)strlen(temp)
+            );
+            for (i = 0; i < wantdigits && i < strlen(temp); i++) {
+                tmp2[i] = temp[i];
+            }
+            for (; i < wantdigits; i++) {
+                tmp2[i] = '0';
+            }
+            tmp2[i++] = '.';
+            for (; i <= strlen(temp); i++) {
+                tmp2[i] = temp[i - 1];
+            }
+            dprintf("%s():  After dealing with trailing zero suppression, convert \"%s\"\n", __FUNCTION__, tmp2);
+            scale = 1.0;
+
+            for (i = 0; i <= strlen(tmp2) && i < sizeof(temp); i++) {
+                temp[i] = tmp2[i];
+            }
+
+        } else {
+
+            /*
+             * figure out the scale factor when we are not suppressing
+             * trailing zeros.
+             */
+            switch (fmt) {
+                case FMT_00_0000: scale = 1E-4; break;
+
+                case FMT_000_000: scale = 1E-3; break;
+
+                case FMT_000_00:
+                case FMT_0000_00: scale = 1E-2; break;
+
+                case FMT_USER: scale = pow(10.0, -1.0 * decimals); break;
+
+                default:
+                    /* cannot happen, just plugs a compiler warning */
+                    fprintf(stderr, _("%s(): Unhandled fmt ` %d\n"), __FUNCTION__, fmt);
+                    exit(1);
+            }
+        }
+
+        result = strtod(temp, NULL) * scale;
     }
 
-    dprintf("    %s()=%f: fmt=%d, omit_zeros=%d, decimals=%d \n",
-		    __FUNCTION__, result, fmt, omit_zeros, decimals);
+    dprintf("    %s()=%f: fmt=%d, omit_zeros=%d, decimals=%d \n", __FUNCTION__, result, fmt, omit_zeros, decimals);
 
     return result;
 } /* read_double */
@@ -2022,61 +1930,58 @@ read_double(gerb_file_t *fd, number_fmt_t fmt, gerbv_omit_zeros_t omit_zeros, in
 /* Eats all characters up to and including
    the first one of CR or LF */
 static void
-eat_line(gerb_file_t *fd)
-{
+eat_line(gerb_file_t* fd) {
     int read;
 
     do {
-	read = gerb_fgetc(fd);
+        read = gerb_fgetc(fd);
     } while (read != '\n' && read != '\r' && read != EOF);
 
     /* Restore new line character for processing */
     if (read != EOF)
-	gerb_ungetc(fd);
+        gerb_ungetc(fd);
 } /* eat_line */
 
 /* -------------------------------------------------------------- */
 /* Eats all tabs and spaces. */
 static void
-eat_whitespace(gerb_file_t *fd)
-{
+eat_whitespace(gerb_file_t* fd) {
     int read;
 
     do {
-	read = gerb_fgetc(fd);
+        read = gerb_fgetc(fd);
     } while ((read == ' ' || read == '\t') && read != EOF);
 
     /* Restore the non-whitespace character for processing */
     if (read != EOF)
-	gerb_ungetc(fd);
+        gerb_ungetc(fd);
 } /* eat_whitespace */
 
 /* -------------------------------------------------------------- */
-static char *
-get_line(gerb_file_t *fd)
-{
-	int read;
-	gchar *retstring;
-	gchar *tmps=g_strdup("");
-
-	read = gerb_fgetc(fd);
-	while (read != '\n' && read != '\r' && read != EOF) {
-		retstring = g_strdup_printf("%s%c", tmps, read);
-
-		/* since g_strdup_printf allocates memory, we need to free it */
-		if (tmps)  {
-			g_free (tmps);
-			tmps = NULL;
-		}
-		tmps = retstring;
-		read = gerb_fgetc(fd);
-	}
-
-	/* Restore new line character for processing */
-	if (read != EOF)
-	    gerb_ungetc(fd);
-
-	return tmps;
+static char*
+get_line(gerb_file_t* fd) {
+    int    read;
+    gchar* retstring;
+    gchar* tmps = g_strdup("");
+
+    read = gerb_fgetc(fd);
+    while (read != '\n' && read != '\r' && read != EOF) {
+        retstring = g_strdup_printf("%s%c", tmps, read);
+
+        /* since g_strdup_printf allocates memory, we need to free it */
+        if (tmps) {
+            g_free(tmps);
+            tmps = NULL;
+        }
+        tmps = retstring;
+        read = gerb_fgetc(fd);
+    }
+
+    /* Restore new line character for processing */
+    if (read != EOF)
+        gerb_ungetc(fd);
+
+    return tmps;
 } /* get_line */
 
 /* -------------------------------------------------------------- */
@@ -2086,25 +1991,24 @@ get_line(gerb_file_t *fd)
  * string is consumed.
  */
 static int
-file_check_str(gerb_file_t *fd, const char *str)
-{
+file_check_str(gerb_file_t* fd, const char* str) {
     char c;
 
     for (int i = 0; str[i] != '\0'; i++) {
 
-	c = gerb_fgetc(fd);
+        c = gerb_fgetc(fd);
 
-	if (c == EOF)
-	    return -1;
+        if (c == EOF)
+            return -1;
 
-	if (c != str[i]) {
-	    do {
-		/* Restore checked string */
-		gerb_ungetc(fd);
-	    } while (i--);
+        if (c != str[i]) {
+            do {
+                /* Restore checked string */
+                gerb_ungetc(fd);
+            } while (i--);
 
-	    return 0;
-	}
+            return 0;
+        }
     }
 
     return 1;
@@ -2112,150 +2016,85 @@ file_check_str(gerb_file_t *fd, const char *str)
 
 /* -------------------------------------------------------------- */
 /** Return drill G-code name by code number. */
-const char *drill_g_code_name(drill_g_code_t g_code)
-{
+const char*
+drill_g_code_name(drill_g_code_t g_code) {
     switch (g_code) {
-    case DRILL_G_ROUT:
-	return N_("rout mode");
-    case DRILL_G_LINEARMOVE:
-	return N_("linear mode");
-    case DRILL_G_CWMOVE:
-	return N_("circular CW mode");
-    case DRILL_G_CCWMOVE:
-	return N_("circular CCW mode");
-    case DRILL_G_VARIABLEDWELL:
-	return N_("variable dwell");
-    case DRILL_G_DRILL:
-	return N_("drill mode");
-    case DRILL_G_OVERRIDETOOLSPEED:
-	return N_("override tool feed or speed");
-    case DRILL_G_ROUTCIRCLE:
-	return N_("routed CW circle");
-    case DRILL_G_ROUTCIRCLECCW:
-	return N_("routed CCW circle");
-    case DRILL_G_VISTOOL:
-	return N_("select vision tool");
-    case DRILL_G_VISSINGLEPOINTOFFSET:
-	return N_("single point vision offset");
-    case DRILL_G_VISMULTIPOINTTRANS:
-	return N_("multipoint vision translation");
-    case DRILL_G_VISCANCEL:
-	return N_("cancel vision translation or offset");
-    case DRILL_G_VISCORRHOLEDRILL:
-	return N_("vision corrected single hole drilling");
-    case DRILL_G_VISAUTOCALIBRATION:
-	return N_("vision system autocalibration");
-    case DRILL_G_CUTTERCOMPOFF:
-	return N_("cutter compensation off");
-    case DRILL_G_CUTTERCOMPLEFT:
-	return N_("cutter compensation left");
-    case DRILL_G_CUTTERCOMPRIGHT:
-	return N_("cutter compensation right");
-    case DRILL_G_VISSINGLEPOINTOFFSETREL:
-	return N_("single point vision relative offset");
-    case DRILL_G_VISMULTIPOINTTRANSREL:
-	return N_("multipoint vision relative translation");
-    case DRILL_G_VISCANCELREL:
-	return N_("cancel vision relative translation or offset");
-    case DRILL_G_VISCORRHOLEDRILLREL:
-	return N_("vision corrected single hole relative drilling");
-    case DRILL_G_PACKDIP2:
-	return N_("dual in line package");
-    case DRILL_G_PACKDIP:
-	return N_("dual in line package");
-    case DRILL_G_PACK8PINL:
-	return N_("eight pin L package");
-    case DRILL_G_CIRLE:
-	return N_("canned circle");
-    case DRILL_G_SLOT:
-	return N_("canned slot");
-    case DRILL_G_ROUTSLOT:
-	return N_("routed step slot");
-    case DRILL_G_ABSOLUTE:
-	return N_("absolute input mode");
-    case DRILL_G_INCREMENTAL:
-	return N_("incremental input mode");
-    case DRILL_G_ZEROSET:
-	return N_("zero set");
-
-    case DRILL_G_UNKNOWN:
-    default:
-	return N_("unknown G-code");
+        case DRILL_G_ROUT: return N_("rout mode");
+        case DRILL_G_LINEARMOVE: return N_("linear mode");
+        case DRILL_G_CWMOVE: return N_("circular CW mode");
+        case DRILL_G_CCWMOVE: return N_("circular CCW mode");
+        case DRILL_G_VARIABLEDWELL: return N_("variable dwell");
+        case DRILL_G_DRILL: return N_("drill mode");
+        case DRILL_G_OVERRIDETOOLSPEED: return N_("override tool feed or speed");
+        case DRILL_G_ROUTCIRCLE: return N_("routed CW circle");
+        case DRILL_G_ROUTCIRCLECCW: return N_("routed CCW circle");
+        case DRILL_G_VISTOOL: return N_("select vision tool");
+        case DRILL_G_VISSINGLEPOINTOFFSET: return N_("single point vision offset");
+        case DRILL_G_VISMULTIPOINTTRANS: return N_("multipoint vision translation");
+        case DRILL_G_VISCANCEL: return N_("cancel vision translation or offset");
+        case DRILL_G_VISCORRHOLEDRILL: return N_("vision corrected single hole drilling");
+        case DRILL_G_VISAUTOCALIBRATION: return N_("vision system autocalibration");
+        case DRILL_G_CUTTERCOMPOFF: return N_("cutter compensation off");
+        case DRILL_G_CUTTERCOMPLEFT: return N_("cutter compensation left");
+        case DRILL_G_CUTTERCOMPRIGHT: return N_("cutter compensation right");
+        case DRILL_G_VISSINGLEPOINTOFFSETREL: return N_("single point vision relative offset");
+        case DRILL_G_VISMULTIPOINTTRANSREL: return N_("multipoint vision relative translation");
+        case DRILL_G_VISCANCELREL: return N_("cancel vision relative translation or offset");
+        case DRILL_G_VISCORRHOLEDRILLREL: return N_("vision corrected single hole relative drilling");
+        case DRILL_G_PACKDIP2: return N_("dual in line package");
+        case DRILL_G_PACKDIP: return N_("dual in line package");
+        case DRILL_G_PACK8PINL: return N_("eight pin L package");
+        case DRILL_G_CIRLE: return N_("canned circle");
+        case DRILL_G_SLOT: return N_("canned slot");
+        case DRILL_G_ROUTSLOT: return N_("routed step slot");
+        case DRILL_G_ABSOLUTE: return N_("absolute input mode");
+        case DRILL_G_INCREMENTAL: return N_("incremental input mode");
+        case DRILL_G_ZEROSET: return N_("zero set");
+
+        case DRILL_G_UNKNOWN:
+        default: return N_("unknown G-code");
     }
 } /* drill_g_code_name() */
 
 /* -------------------------------------------------------------- */
 /** Return drill M-code name by code number. */
-const char *drill_m_code_name(drill_m_code_t m_code)
-{
+const char*
+drill_m_code_name(drill_m_code_t m_code) {
     switch (m_code) {
-    case DRILL_M_END:
-	return N_("end of program");
-    case DRILL_M_PATTERNEND:
-	return N_("pattern end");
-    case DRILL_M_REPEATPATTERNOFFSET:
-	return N_("repeat pattern offset");
-    case DRILL_M_STOPOPTIONAL:
-	return N_("stop optional");
-    case DRILL_M_SANDREND:
-	return N_("step and repeat end");
-    case DRILL_M_STOPINSPECTION:
-	return N_("stop for inspection");
-    case DRILL_M_ZAXISROUTEPOSITIONDEPTHCTRL:
-	return N_("Z-axis rout position with depth control");
-    case DRILL_M_ZAXISROUTEPOSITION:
-	return N_("Z-axis rout position");
-    case DRILL_M_RETRACTCLAMPING:
-	return N_("retract with clamping");
-    case DRILL_M_RETRACTNOCLAMPING:
-	return N_("retract without clamping");
-    case DRILL_M_TOOLTIPCHECK:
-	return N_("tool tip check");
-    case DRILL_M_PATTERN:
-	return N_("pattern start");
-    case DRILL_M_ENDREWIND:
-	return N_("end of program with rewind");
-    case DRILL_M_MESSAGELONG:
-	return N_("long operator message");
-    case DRILL_M_MESSAGE:
-	return N_("operator message");
-    case DRILL_M_HEADER:
-	return N_("header start");
-    case DRILL_M_VISANDRPATTERN:
-	return N_("vision step and repeat pattern start");
-    case DRILL_M_VISANDRPATTERNREWIND:
-	return N_("vision step and repeat rewind");
-    case DRILL_M_VISANDRPATTERNOFFSETCOUNTERCTRL:
-	return N_("vision step and repeat offset counter control");
-    case DRILL_M_REFSCALING:
-	return N_("reference scaling on");
-    case DRILL_M_REFSCALINGEND:
-	return N_("reference scaling off");
-    case DRILL_M_PECKDRILLING:
-	return N_("peck drilling on");
-    case DRILL_M_PECKDRILLINGEND:
-	return N_("peck drilling off");
-    case DRILL_M_SWAPAXIS:
-	return N_("swap axes");
-    case DRILL_M_METRIC:
-	return N_("metric measuring mode");
-    case DRILL_M_IMPERIAL:
-	return N_("inch measuring mode");
-    case DRILL_M_MIRRORX:
-	return N_("mirror image X-axis");
-    case DRILL_M_MIRRORY:
-	return N_("mirror image Y-axis");
-    case DRILL_M_HEADEREND:
-	return N_("header end");
-    case DRILL_M_CANNEDTEXTX:
-	return N_("canned text along X-axis");
-    case DRILL_M_CANNEDTEXTY:
-	return N_("canned text along Y-axis");
-    case DRILL_M_USERDEFPATTERN:
-	return N_("user defined stored pattern");
-
-    case DRILL_M_UNKNOWN:
-    default:
-	return N_("unknown M-code");
+        case DRILL_M_END: return N_("end of program");
+        case DRILL_M_PATTERNEND: return N_("pattern end");
+        case DRILL_M_REPEATPATTERNOFFSET: return N_("repeat pattern offset");
+        case DRILL_M_STOPOPTIONAL: return N_("stop optional");
+        case DRILL_M_SANDREND: return N_("step and repeat end");
+        case DRILL_M_STOPINSPECTION: return N_("stop for inspection");
+        case DRILL_M_ZAXISROUTEPOSITIONDEPTHCTRL: return N_("Z-axis rout position with depth control");
+        case DRILL_M_ZAXISROUTEPOSITION: return N_("Z-axis rout position");
+        case DRILL_M_RETRACTCLAMPING: return N_("retract with clamping");
+        case DRILL_M_RETRACTNOCLAMPING: return N_("retract without clamping");
+        case DRILL_M_TOOLTIPCHECK: return N_("tool tip check");
+        case DRILL_M_PATTERN: return N_("pattern start");
+        case DRILL_M_ENDREWIND: return N_("end of program with rewind");
+        case DRILL_M_MESSAGELONG: return N_("long operator message");
+        case DRILL_M_MESSAGE: return N_("operator message");
+        case DRILL_M_HEADER: return N_("header start");
+        case DRILL_M_VISANDRPATTERN: return N_("vision step and repeat pattern start");
+        case DRILL_M_VISANDRPATTERNREWIND: return N_("vision step and repeat rewind");
+        case DRILL_M_VISANDRPATTERNOFFSETCOUNTERCTRL: return N_("vision step and repeat offset counter control");
+        case DRILL_M_REFSCALING: return N_("reference scaling on");
+        case DRILL_M_REFSCALINGEND: return N_("reference scaling off");
+        case DRILL_M_PECKDRILLING: return N_("peck drilling on");
+        case DRILL_M_PECKDRILLINGEND: return N_("peck drilling off");
+        case DRILL_M_SWAPAXIS: return N_("swap axes");
+        case DRILL_M_METRIC: return N_("metric measuring mode");
+        case DRILL_M_IMPERIAL: return N_("inch measuring mode");
+        case DRILL_M_MIRRORX: return N_("mirror image X-axis");
+        case DRILL_M_MIRRORY: return N_("mirror image Y-axis");
+        case DRILL_M_HEADEREND: return N_("header end");
+        case DRILL_M_CANNEDTEXTX: return N_("canned text along X-axis");
+        case DRILL_M_CANNEDTEXTY: return N_("canned text along Y-axis");
+        case DRILL_M_USERDEFPATTERN: return N_("user defined stored pattern");
+
+        case DRILL_M_UNKNOWN:
+        default: return N_("unknown M-code");
     }
 } /* drill_m_code_name() */
diff --git a/src/drill.h b/src/drill.h
index be87ee8..78cbed2 100644
--- a/src/drill.h
+++ b/src/drill.h
@@ -37,110 +37,109 @@ extern "C" {
 #include "gerb_image.h"
 #include "gerb_file.h"
 
-#define TOOL_MIN 1  /* T00 code is reserved for unload tool command */
+#define TOOL_MIN 1 /* T00 code is reserved for unload tool command */
 #define TOOL_MAX 9999
 
-gerbv_image_t *parse_drillfile(gerb_file_t *fd, gerbv_HID_Attribute *attr_list,
-				int n_attr, int reload);
-gboolean drill_file_p(gerb_file_t *fd, gboolean *returnFoundBinary);
+gerbv_image_t* parse_drillfile(gerb_file_t* fd, gerbv_HID_Attribute* attr_list, int n_attr, int reload);
+gboolean       drill_file_p(gerb_file_t* fd, gboolean* returnFoundBinary);
 
 /* NOTE: keep drill_g_code_t in actual G code order. */
 typedef enum {
-	DRILL_G_UNKNOWN = -1,
-
-	DRILL_G_ROUT = 0, /* Route mode */
-	DRILL_G_LINEARMOVE, /* Linear (straight line) mode */
-	DRILL_G_CWMOVE,  /* Circular CW mode */
-	DRILL_G_CCWMOVE, /* Circular CCW mode */
-	DRILL_G_VARIABLEDWELL, /* Variable dwell */
-	DRILL_G_DRILL, /* Drill mode */
-
-	DRILL_G_OVERRIDETOOLSPEED = 7, /* Override current tool feed or speed */
-
-	DRILL_G_ROUTCIRCLE = 32, /* Routed circle canned cycle CW */
-	DRILL_G_ROUTCIRCLECCW,   /* Routed circle canned cycle CCW */
-	DRILL_G_VISTOOL, /* Select vision tool */
-	DRILL_G_VISSINGLEPOINTOFFSET, /* Single point vision offset */
-	DRILL_G_VISMULTIPOINTTRANS, /* Multipoint vision translation */
-	DRILL_G_VISCANCEL, /* Cancel vision translation or offset */
-	DRILL_G_VISCORRHOLEDRILL, /* Vision corrected single hole drilling */
-	DRILL_G_VISAUTOCALIBRATION, /* Vision system autocalibration */
-	DRILL_G_CUTTERCOMPOFF, /* Cutter compensation off */
-	DRILL_G_CUTTERCOMPLEFT, /* Cutter compensation left */
-	DRILL_G_CUTTERCOMPRIGHT, /* Cutter compensation right */
-
-	DRILL_G_VISSINGLEPOINTOFFSETREL = 45, /* Single point vision offset
-						 relative to G35 or G36 */
-	DRILL_G_VISMULTIPOINTTRANSREL, /* Multipoint vision translation
-					  relative to G35 or G36 */
-	DRILL_G_VISCANCELREL, /* Cancel vision translation or offset
-				 from G45 or G46 */
-	DRILL_G_VISCORRHOLEDRILLREL, /* Vision corrected single hole drilling
-					relative to G35 or G36 */
-	DRILL_G_PACKDIP2 = 81,/* Dual in line package, same to G82 in Format2 */
-	DRILL_G_PACKDIP, /* Dual in line package */
-	DRILL_G_PACK8PINL, /* Eight pin L pack */
-	DRILL_G_CIRLE, /* Canned circle */
-	DRILL_G_SLOT, /* Canned slot */
-
-	DRILL_G_ROUTSLOT = 87, /* Routed slot canned cycle */
-
-	DRILL_G_ABSOLUTE = 90, /* Absolute input mode */
-	DRILL_G_INCREMENTAL, /* Incremental input mode */
-
-	DRILL_G_ZEROSET = 93, /* Sets work zero relative to absolute zero */
+    DRILL_G_UNKNOWN = -1,
+
+    DRILL_G_ROUT = 0,      /* Route mode */
+    DRILL_G_LINEARMOVE,    /* Linear (straight line) mode */
+    DRILL_G_CWMOVE,        /* Circular CW mode */
+    DRILL_G_CCWMOVE,       /* Circular CCW mode */
+    DRILL_G_VARIABLEDWELL, /* Variable dwell */
+    DRILL_G_DRILL,         /* Drill mode */
+
+    DRILL_G_OVERRIDETOOLSPEED = 7, /* Override current tool feed or speed */
+
+    DRILL_G_ROUTCIRCLE = 32,      /* Routed circle canned cycle CW */
+    DRILL_G_ROUTCIRCLECCW,        /* Routed circle canned cycle CCW */
+    DRILL_G_VISTOOL,              /* Select vision tool */
+    DRILL_G_VISSINGLEPOINTOFFSET, /* Single point vision offset */
+    DRILL_G_VISMULTIPOINTTRANS,   /* Multipoint vision translation */
+    DRILL_G_VISCANCEL,            /* Cancel vision translation or offset */
+    DRILL_G_VISCORRHOLEDRILL,     /* Vision corrected single hole drilling */
+    DRILL_G_VISAUTOCALIBRATION,   /* Vision system autocalibration */
+    DRILL_G_CUTTERCOMPOFF,        /* Cutter compensation off */
+    DRILL_G_CUTTERCOMPLEFT,       /* Cutter compensation left */
+    DRILL_G_CUTTERCOMPRIGHT,      /* Cutter compensation right */
+
+    DRILL_G_VISSINGLEPOINTOFFSETREL = 45, /* Single point vision offset
+                         relative to G35 or G36 */
+    DRILL_G_VISMULTIPOINTTRANSREL,        /* Multipoint vision translation
+                             relative to G35 or G36 */
+    DRILL_G_VISCANCELREL,                 /* Cancel vision translation or offset
+                                 from G45 or G46 */
+    DRILL_G_VISCORRHOLEDRILLREL,          /* Vision corrected single hole drilling
+                             relative to G35 or G36 */
+    DRILL_G_PACKDIP2 = 81,                /* Dual in line package, same to G82 in Format2 */
+    DRILL_G_PACKDIP,                      /* Dual in line package */
+    DRILL_G_PACK8PINL,                    /* Eight pin L pack */
+    DRILL_G_CIRLE,                        /* Canned circle */
+    DRILL_G_SLOT,                         /* Canned slot */
+
+    DRILL_G_ROUTSLOT = 87, /* Routed slot canned cycle */
+
+    DRILL_G_ABSOLUTE = 90, /* Absolute input mode */
+    DRILL_G_INCREMENTAL,   /* Incremental input mode */
+
+    DRILL_G_ZEROSET = 93, /* Sets work zero relative to absolute zero */
 } drill_g_code_t;
 
 /* NOTE: keep drill_m_code_t in actual M code order. */
 typedef enum {
-	DRILL_M_UNKNOWN = -1,
+    DRILL_M_UNKNOWN = -1,
 
-	DRILL_M_END = 0,
-	DRILL_M_PATTERNEND,
-	DRILL_M_REPEATPATTERNOFFSET,
+    DRILL_M_END = 0,
+    DRILL_M_PATTERNEND,
+    DRILL_M_REPEATPATTERNOFFSET,
 
-	DRILL_M_STOPOPTIONAL = 6,
+    DRILL_M_STOPOPTIONAL = 6,
 
-	DRILL_M_SANDREND = 8,	/* Step and repeat */
-	DRILL_M_STOPINSPECTION,
+    DRILL_M_SANDREND = 8, /* Step and repeat */
+    DRILL_M_STOPINSPECTION,
 
-	DRILL_M_ZAXISROUTEPOSITIONDEPTHCTRL = 14,
-	DRILL_M_ZAXISROUTEPOSITION,
-	DRILL_M_RETRACTCLAMPING,
-	DRILL_M_RETRACTNOCLAMPING,
-	DRILL_M_TOOLTIPCHECK,
+    DRILL_M_ZAXISROUTEPOSITIONDEPTHCTRL = 14,
+    DRILL_M_ZAXISROUTEPOSITION,
+    DRILL_M_RETRACTCLAMPING,
+    DRILL_M_RETRACTNOCLAMPING,
+    DRILL_M_TOOLTIPCHECK,
 
-	DRILL_M_PATTERN = 25,
-	DRILL_M_ENDREWIND = 30,
-	DRILL_M_MESSAGELONG = 45,
+    DRILL_M_PATTERN     = 25,
+    DRILL_M_ENDREWIND   = 30,
+    DRILL_M_MESSAGELONG = 45,
 
-	DRILL_M_MESSAGE = 47,
-	DRILL_M_HEADER,
+    DRILL_M_MESSAGE = 47,
+    DRILL_M_HEADER,
 
-	DRILL_M_VISANDRPATTERN = 50,	/* Visual step and repeat */
-	DRILL_M_VISANDRPATTERNREWIND,
-	DRILL_M_VISANDRPATTERNOFFSETCOUNTERCTRL,
+    DRILL_M_VISANDRPATTERN = 50, /* Visual step and repeat */
+    DRILL_M_VISANDRPATTERNREWIND,
+    DRILL_M_VISANDRPATTERNOFFSETCOUNTERCTRL,
 
-	DRILL_M_REFSCALING = 60,	/* Reference scaling */
-	DRILL_M_REFSCALINGEND,
-	DRILL_M_PECKDRILLING,
-	DRILL_M_PECKDRILLINGEND,
+    DRILL_M_REFSCALING = 60, /* Reference scaling */
+    DRILL_M_REFSCALINGEND,
+    DRILL_M_PECKDRILLING,
+    DRILL_M_PECKDRILLINGEND,
 
-	DRILL_M_SWAPAXIS = 70,
-	DRILL_M_METRIC,
-	DRILL_M_IMPERIAL,
+    DRILL_M_SWAPAXIS = 70,
+    DRILL_M_METRIC,
+    DRILL_M_IMPERIAL,
 
-	DRILL_M_MIRRORX = 80,
-	DRILL_M_MIRRORY = 90,
-	DRILL_M_HEADEREND = 95,
+    DRILL_M_MIRRORX   = 80,
+    DRILL_M_MIRRORY   = 90,
+    DRILL_M_HEADEREND = 95,
 
-	DRILL_M_CANNEDTEXTX = 97,
-	DRILL_M_CANNEDTEXTY,
-	DRILL_M_USERDEFPATTERN,
+    DRILL_M_CANNEDTEXTX = 97,
+    DRILL_M_CANNEDTEXTY,
+    DRILL_M_USERDEFPATTERN,
 } drill_m_code_t;
 
-const char *drill_g_code_name(drill_g_code_t g_code);
-const char *drill_m_code_name(drill_m_code_t m_code);
+const char* drill_g_code_name(drill_g_code_t g_code);
+const char* drill_m_code_name(drill_m_code_t m_code);
 
 #ifdef __cplusplus
 }
diff --git a/src/drill_stats.c b/src/drill_stats.c
index 6266742..81f3227 100644
--- a/src/drill_stats.c
+++ b/src/drill_stats.c
@@ -37,18 +37,19 @@
 #include "drill_stats.h"
 #include "gerb_stats.h"
 
-#define dprintf if(DEBUG) printf
-
+#define dprintf \
+    if (DEBUG)  \
+    printf
 
 /* ------------------------------------------------------- */
 /** Allocates a new drill_stats structure
    @return drill_stats pointer on success, NULL on ERROR */
-gerbv_drill_stats_t *
+gerbv_drill_stats_t*
 gerbv_drill_stats_new(void) {
 
-    gerbv_drill_stats_t *stats;
-    gerbv_drill_list_t *drill_list;
-    gerbv_error_list_t *error_list;
+    gerbv_drill_stats_t* stats;
+    gerbv_drill_list_t*  drill_list;
+    gerbv_error_list_t*  error_list;
 
     /* Malloc space for new stats struct.  Return NULL if error. */
     if (NULL == (stats = g_new0(gerbv_drill_stats_t, 1))) {
@@ -59,13 +60,13 @@ gerbv_drill_stats_new(void) {
     drill_list = gerbv_drill_stats_new_drill_list();
     if (drill_list == NULL)
         GERB_FATAL_ERROR("malloc drill_list failed in %s()", __FUNCTION__);
-    stats->drill_list = (gerbv_drill_list_t *) drill_list;
+    stats->drill_list = (gerbv_drill_list_t*)drill_list;
 
     /* Initialize error list */
     error_list = gerbv_drill_stats_new_error_list();
     if (error_list == NULL)
         GERB_FATAL_ERROR("malloc error_list failed in %s()", __FUNCTION__);
-    stats->error_list = (gerbv_error_list_t *) error_list;
+    stats->error_list = (gerbv_error_list_t*)error_list;
 
     stats->detect = NULL;
 
@@ -73,47 +74,45 @@ gerbv_drill_stats_new(void) {
 }
 
 void
-gerbv_drill_destroy_error_list (gerbv_error_list_t *errorList) {
-	gerbv_error_list_t *nextError=errorList,*tempError;
-	
-	while (nextError) {
-		tempError = nextError->next;
-		g_free (nextError->error_text);
-		g_free (nextError);
-		nextError = tempError;
-	}
+gerbv_drill_destroy_error_list(gerbv_error_list_t* errorList) {
+    gerbv_error_list_t *nextError = errorList, *tempError;
+
+    while (nextError) {
+        tempError = nextError->next;
+        g_free(nextError->error_text);
+        g_free(nextError);
+        nextError = tempError;
+    }
 }
 
 void
-gerbv_drill_destroy_drill_list (gerbv_drill_list_t *apertureList) {
-	gerbv_drill_list_t *nextAperture=apertureList,*tempAperture;
-	
-	while (nextAperture) {
-		tempAperture = nextAperture->next;
-		g_free(nextAperture->drill_unit);
-		g_free (nextAperture);
-		nextAperture = tempAperture;
-	}
+gerbv_drill_destroy_drill_list(gerbv_drill_list_t* apertureList) {
+    gerbv_drill_list_t *nextAperture = apertureList, *tempAperture;
+
+    while (nextAperture) {
+        tempAperture = nextAperture->next;
+        g_free(nextAperture->drill_unit);
+        g_free(nextAperture);
+        nextAperture = tempAperture;
+    }
 }
 
 void
-gerbv_drill_stats_destroy(gerbv_drill_stats_t *stats) {
-	if (stats == NULL)
-		return;
-	gerbv_drill_destroy_error_list (stats->error_list);
-	gerbv_drill_destroy_drill_list (stats->drill_list);
-	g_free (stats);
-}	
-	
+gerbv_drill_stats_destroy(gerbv_drill_stats_t* stats) {
+    if (stats == NULL)
+        return;
+    gerbv_drill_destroy_error_list(stats->error_list);
+    gerbv_drill_destroy_drill_list(stats->drill_list);
+    g_free(stats);
+}
+
 /* ------------------------------------------------------- */
 void
-gerbv_drill_stats_add_layer(gerbv_drill_stats_t *accum_stats, 
-		      gerbv_drill_stats_t *input_stats,
-		      int this_layer) {
+gerbv_drill_stats_add_layer(gerbv_drill_stats_t* accum_stats, gerbv_drill_stats_t* input_stats, int this_layer) {
 
-    gerbv_drill_list_t *drill;
-    gerbv_error_list_t *error;
-    char *tmps, *tmps2;
+    gerbv_drill_list_t* drill;
+    gerbv_error_list_t* error;
+    char *              tmps, *tmps2;
 
     dprintf("--->  Entering gerbv_drill_stats_add_layer ..... \n");
 
@@ -153,92 +152,75 @@ gerbv_drill_stats_add_layer(gerbv_drill_stats_t *accum_stats,
     accum_stats->R += input_stats->R;
 
     /* ==== Now deal with the drill list ==== */
-    for (drill = input_stats->drill_list;
-         drill != NULL;
-	 drill = drill->next) {
-	dprintf("   In gerbv_drill_stats_add_layer, adding drill_num = %d to list\n",
-		drill->drill_num);
-	/* First add this input drill to the accumulated list.
-	 * Drills already in accum list will not be added. */
-	drill_stats_add_to_drill_list(accum_stats->drill_list,
-		 		      drill->drill_num, 
-				      drill->drill_size,
-				      drill->drill_unit);
-
-	/* Now add count of input drill to accum list */
-	dprintf("   adding count %d of drills for drill %d\n", 
-		drill->drill_count, drill->drill_num);
-	drill_stats_add_to_drill_counter(accum_stats->drill_list,
-					 drill->drill_num,
-					 drill->drill_count);
-	accum_stats->total_count += drill->drill_count;
+    for (drill = input_stats->drill_list; drill != NULL; drill = drill->next) {
+        dprintf("   In gerbv_drill_stats_add_layer, adding drill_num = %d to list\n", drill->drill_num);
+        /* First add this input drill to the accumulated list.
+         * Drills already in accum list will not be added. */
+        drill_stats_add_to_drill_list(accum_stats->drill_list, drill->drill_num, drill->drill_size, drill->drill_unit);
+
+        /* Now add count of input drill to accum list */
+        dprintf("   adding count %d of drills for drill %d\n", drill->drill_count, drill->drill_num);
+        drill_stats_add_to_drill_counter(accum_stats->drill_list, drill->drill_num, drill->drill_count);
+        accum_stats->total_count += drill->drill_count;
     }
 
     /* ==== Now deal with the error list ==== */
     for (error = input_stats->error_list; error != NULL; error = error->next) {
-	if (error->error_text != NULL)
-	    gerbv_stats_printf(accum_stats->error_list, error->type,
-		    this_layer, "%s", error->error_text);
+        if (error->error_text != NULL)
+            gerbv_stats_printf(accum_stats->error_list, error->type, this_layer, "%s", error->error_text);
     }
 
     /* ==== Now deal with the misc header stuff ==== */
-    tmps = NULL;
+    tmps  = NULL;
     tmps2 = NULL;
     if (input_stats->detect) {
-	tmps2 = g_strdup_printf (_("Broken tool detect %s (layer %d)"), input_stats->detect, this_layer);
-    }    
+        tmps2 = g_strdup_printf(_("Broken tool detect %s (layer %d)"), input_stats->detect, this_layer);
+    }
     if (accum_stats->detect) {
-	if (tmps2) {
-	    tmps = g_strdup_printf ("%s\n%s", accum_stats->detect, tmps2);
-	    g_free (accum_stats->detect);
-	    accum_stats->detect = NULL;
-	}
+        if (tmps2) {
+            tmps = g_strdup_printf("%s\n%s", accum_stats->detect, tmps2);
+            g_free(accum_stats->detect);
+            accum_stats->detect = NULL;
+        }
     } else {
-	if (tmps2) {
-	    tmps = g_strdup_printf ("%s", tmps2);
-	}
+        if (tmps2) {
+            tmps = g_strdup_printf("%s", tmps2);
+        }
     }
     if (tmps2) {
-	g_free (tmps2);
+        g_free(tmps2);
     }
     if (tmps != NULL) {
-	accum_stats->detect = tmps;
+        accum_stats->detect = tmps;
     }
 
-    for (error = input_stats->error_list;
-         error != NULL;
-	 error = error->next) {
-	if (error->error_text != NULL) {
-	    gerbv_stats_printf(accum_stats->error_list, error->type,
-			    this_layer, "%s", error->error_text);
-	}
+    for (error = input_stats->error_list; error != NULL; error = error->next) {
+        if (error->error_text != NULL) {
+            gerbv_stats_printf(accum_stats->error_list, error->type, this_layer, "%s", error->error_text);
+        }
     }
 
-
     dprintf("<---  .... Leaving gerbv_drill_stats_add_layer.\n");
-	    
+
     return;
 }
 
-
 /* ------------------------------------------------------- */
 gboolean
-drill_stats_in_drill_list(gerbv_drill_list_t *drill_list_in,
-			  int drill_num_in) {
-    gerbv_drill_list_t *drill;
-    for(drill = drill_list_in; drill != NULL; drill = drill->next) {
-	if (drill_num_in == drill->drill_num) {
-	    return TRUE;
-	}
+drill_stats_in_drill_list(gerbv_drill_list_t* drill_list_in, int drill_num_in) {
+    gerbv_drill_list_t* drill;
+    for (drill = drill_list_in; drill != NULL; drill = drill->next) {
+        if (drill_num_in == drill->drill_num) {
+            return TRUE;
+        }
     }
     return FALSE;
-
 }
 
 /* ------------------------------------------------------- */
-gerbv_drill_list_t *
+gerbv_drill_list_t*
 gerbv_drill_stats_new_drill_list() {
-    gerbv_drill_list_t *drill_list;
+    gerbv_drill_list_t* drill_list;
 
     /* Malloc space for new drill_list struct.  Return NULL if error. */
     if (NULL == (drill_list = g_new(gerbv_drill_list_t, 1))) {
@@ -246,69 +228,62 @@ gerbv_drill_stats_new_drill_list() {
     }
 
     drill_list->drill_count = 0;
-    drill_list->drill_num = -1; /* default val */
-    drill_list->drill_size = 0.0;
-    drill_list->drill_unit = NULL;
-    drill_list->next = NULL;
+    drill_list->drill_num   = -1; /* default val */
+    drill_list->drill_size  = 0.0;
+    drill_list->drill_unit  = NULL;
+    drill_list->next        = NULL;
     return drill_list;
-} 
-
+}
 
 /* ------------------------------------------------------- */
 void
-drill_stats_add_to_drill_list(gerbv_drill_list_t *drill_list_in, 
-			      int drill_num_in, double drill_size_in,
-			      char *drill_unit_in) {
+drill_stats_add_to_drill_list(
+    gerbv_drill_list_t* drill_list_in, int drill_num_in, double drill_size_in, char* drill_unit_in
+) {
 
-    gerbv_drill_list_t *drill_list_new;
-    gerbv_drill_list_t *drill;
-    gerbv_drill_list_t *drill_last = NULL;
+    gerbv_drill_list_t* drill_list_new;
+    gerbv_drill_list_t* drill;
+    gerbv_drill_list_t* drill_last = NULL;
 
-    dprintf ("%s(%p, %d, %g, \"%s\")\n", __FUNCTION__, drill_list_in, drill_num_in,
-	     drill_size_in, drill_unit_in);
+    dprintf("%s(%p, %d, %g, \"%s\")\n", __FUNCTION__, drill_list_in, drill_num_in, drill_size_in, drill_unit_in);
 
-    dprintf("   ---> Entering drill_stats_add_to_drill_list, first drill_num in list = %d ...\n", 
-	    drill_list_in->drill_num);
+    dprintf(
+        "   ---> Entering drill_stats_add_to_drill_list, first drill_num in list = %d ...\n", drill_list_in->drill_num
+    );
 
     /* First check for empty list.  If empty, then just add this drill */
     if (drill_list_in->drill_num == -1) {
-	dprintf("    .... In drill_stats_add_to_drill_list, adding first drill, no %d\n", 
-		drill_num_in);
-	drill_list_in->drill_num = drill_num_in;
-	drill_list_in->drill_size = drill_size_in;
-	drill_list_in->drill_count = 0;
-	drill_list_in->drill_unit = g_strdup_printf("%s", drill_unit_in);
-	drill_list_in->next = NULL;
-	return;
+        dprintf("    .... In drill_stats_add_to_drill_list, adding first drill, no %d\n", drill_num_in);
+        drill_list_in->drill_num   = drill_num_in;
+        drill_list_in->drill_size  = drill_size_in;
+        drill_list_in->drill_count = 0;
+        drill_list_in->drill_unit  = g_strdup_printf("%s", drill_unit_in);
+        drill_list_in->next        = NULL;
+        return;
     }
     /* Else check to see if this drill is already in the list */
-    for(drill = drill_list_in; 
-	drill != NULL; 
-	drill = (gerbv_drill_list_t *) drill->next) {
-	dprintf("checking this drill_num %d against that in list %d.\n", 
-		drill_num_in, drill->drill_num);
-	if (drill_num_in == drill->drill_num) {
-	    dprintf("   .... In drill_stats_add_to_drill_list, drill no %d already in list\n", 
-		    drill_num_in);
-	    return;  /* Found it in list, so return */
-	}
-	drill_last = drill;
+    for (drill = drill_list_in; drill != NULL; drill = (gerbv_drill_list_t*)drill->next) {
+        dprintf("checking this drill_num %d against that in list %d.\n", drill_num_in, drill->drill_num);
+        if (drill_num_in == drill->drill_num) {
+            dprintf("   .... In drill_stats_add_to_drill_list, drill no %d already in list\n", drill_num_in);
+            return; /* Found it in list, so return */
+        }
+        drill_last = drill;
     }
 
     /* Now malloc space for new drill list element */
     if (NULL == (drill_list_new = g_new(gerbv_drill_list_t, 1))) {
-	GERB_FATAL_ERROR("malloc format failed in %s()", __FUNCTION__);
+        GERB_FATAL_ERROR("malloc format failed in %s()", __FUNCTION__);
     }
 
     /* Now set various parameters based upon calling args */
-    dprintf("    .... In drill_stats_add_to_drill_list, adding new drill, no %d\n", 
-	    drill_num_in);
-    drill_list_new->drill_num = drill_num_in;
-    drill_list_new->drill_size = drill_size_in;
+    dprintf("    .... In drill_stats_add_to_drill_list, adding new drill, no %d\n", drill_num_in);
+    drill_list_new->drill_num   = drill_num_in;
+    drill_list_new->drill_size  = drill_size_in;
     drill_list_new->drill_count = 0;
-    drill_list_new->drill_unit = g_strdup_printf("%s", drill_unit_in);
-    drill_list_new->next = NULL;
-    drill_last->next = drill_list_new;
+    drill_list_new->drill_unit  = g_strdup_printf("%s", drill_unit_in);
+    drill_list_new->next        = NULL;
+    drill_last->next            = drill_list_new;
 
     dprintf("   <---- ... leaving drill_stats_add_to_drill_list.\n");
     return;
@@ -316,30 +291,28 @@ drill_stats_add_to_drill_list(gerbv_drill_list_t *drill_list_in,
 
 /* ------------------------------------------------------- */
 void
-drill_stats_modify_drill_list(gerbv_drill_list_t *drill_list_in, 
-			      int drill_num_in, double drill_size_in,
-			      char *drill_unit_in) {
+drill_stats_modify_drill_list(
+    gerbv_drill_list_t* drill_list_in, int drill_num_in, double drill_size_in, char* drill_unit_in
+) {
 
-    gerbv_drill_list_t *drill;
+    gerbv_drill_list_t* drill;
 
-    dprintf("   ---> Entering drill_stats_modify_drill_list, first drill_num in list = %d ...\n", 
-	    drill_list_in->drill_num);
+    dprintf(
+        "   ---> Entering drill_stats_modify_drill_list, first drill_num in list = %d ...\n", drill_list_in->drill_num
+    );
 
     /* Look for this drill num in list */
-    for(drill = drill_list_in; 
-	drill != NULL; 
-	drill = (gerbv_drill_list_t *) drill->next) {
-	dprintf("checking this drill_num %d against that in list %d.\n", 
-		drill_num_in, drill->drill_num);
-	if (drill_num_in == drill->drill_num) {
-	    dprintf("   .... Found it, now update it ....\n");
-	    drill->drill_size = drill_size_in;
-	    if (drill->drill_unit) 
-		g_free(drill->drill_unit);
-	    drill->drill_unit = g_strdup_printf("%s", drill_unit_in);
-	    dprintf("   <---- ... Modified drill.  leaving drill_stats_modify_drill_list.\n");
-	    return;
-	}
+    for (drill = drill_list_in; drill != NULL; drill = (gerbv_drill_list_t*)drill->next) {
+        dprintf("checking this drill_num %d against that in list %d.\n", drill_num_in, drill->drill_num);
+        if (drill_num_in == drill->drill_num) {
+            dprintf("   .... Found it, now update it ....\n");
+            drill->drill_size = drill_size_in;
+            if (drill->drill_unit)
+                g_free(drill->drill_unit);
+            drill->drill_unit = g_strdup_printf("%s", drill_unit_in);
+            dprintf("   <---- ... Modified drill.  leaving drill_stats_modify_drill_list.\n");
+            return;
+        }
     }
     dprintf("   <---- ... Did not find drill.  leaving drill_stats_modify_drill_list.\n");
     return;
@@ -347,65 +320,59 @@ drill_stats_modify_drill_list(gerbv_drill_list_t *drill_list_in,
 
 /* ------------------------------------------------------- */
 void
-drill_stats_increment_drill_counter(gerbv_drill_list_t *drill_list_in, 
-				    int drill_num_in) {
+drill_stats_increment_drill_counter(gerbv_drill_list_t* drill_list_in, int drill_num_in) {
 
     dprintf("   ----> Entering drill_stats_increment_drill_counter......\n");
     /* First check to see if this drill is already in the list */
-    gerbv_drill_list_t *drill;
-    for(drill = drill_list_in; drill != NULL; drill = drill->next) {
-	if (drill_num_in == drill->drill_num) {
-	    drill->drill_count++;
-	    dprintf("         .... incrementing drill count.  drill_num = %d, drill_count = %d.\n",
-		    drill_list_in->drill_num, drill->drill_count);
-	    dprintf("   <---- .... Leaving drill_stats_increment_drill_counter after incrementing counter.\n");
-	    return;
-	}
+    gerbv_drill_list_t* drill;
+    for (drill = drill_list_in; drill != NULL; drill = drill->next) {
+        if (drill_num_in == drill->drill_num) {
+            drill->drill_count++;
+            dprintf(
+                "         .... incrementing drill count.  drill_num = %d, drill_count = %d.\n",
+                drill_list_in->drill_num, drill->drill_count
+            );
+            dprintf("   <---- .... Leaving drill_stats_increment_drill_counter after incrementing counter.\n");
+            return;
+        }
     }
     dprintf("   <---- .... Leaving drill_stats_increment_drill_counter without incrementing any counter.\n");
-
 }
 
 /* ------------------------------------------------------- */
 void
-drill_stats_add_to_drill_counter(gerbv_drill_list_t *drill_list_in, 
-				 int drill_num_in, 
-				 int increment) {
-
-    gerbv_drill_list_t *drill;
-    for(drill = drill_list_in; drill != NULL; drill = drill->next) {
-	if (drill_num_in == drill->drill_num) {
-	    dprintf("    In drill_stats_add_to_drill_counter, adding increment = %d drills to drill list\n", increment);
-	    drill->drill_count += increment;
-	    return;
-	}
+drill_stats_add_to_drill_counter(gerbv_drill_list_t* drill_list_in, int drill_num_in, int increment) {
+
+    gerbv_drill_list_t* drill;
+    for (drill = drill_list_in; drill != NULL; drill = drill->next) {
+        if (drill_num_in == drill->drill_num) {
+            dprintf("    In drill_stats_add_to_drill_counter, adding increment = %d drills to drill list\n", increment);
+            drill->drill_count += increment;
+            return;
+        }
     }
 }
 
-
 /* ------------------------------------------------------- */
-gerbv_error_list_t *
+gerbv_error_list_t*
 gerbv_drill_stats_new_error_list() {
-    gerbv_error_list_t *error_list;
+    gerbv_error_list_t* error_list;
 
     /* Malloc space for new error_list struct.  Return NULL if error. */
     if (NULL == (error_list = g_new(gerbv_error_list_t, 1))) {
         return NULL;
     }
 
-    error_list->layer = -1;
+    error_list->layer      = -1;
     error_list->error_text = NULL;
-    error_list->next = NULL;
+    error_list->next       = NULL;
     return error_list;
-} 
+}
 
 /* ------------------------------------------------------- */
 /** Add statistic message for drill layer.
  * It is recommend to use gerbv_stats_printf() instead of this function. */
 void
-drill_stats_add_error(gerbv_error_list_t *error_list_in, 
-		      int layer, const char *error_text,
-		      gerbv_message_type_t type)
-{
+drill_stats_add_error(gerbv_error_list_t* error_list_in, int layer, const char* error_text, gerbv_message_type_t type) {
     gerbv_stats_add_error(error_list_in, layer, error_text, type);
 }
diff --git a/src/drill_stats.h b/src/drill_stats.h
index e3b309d..479e8bb 100644
--- a/src/drill_stats.h
+++ b/src/drill_stats.h
@@ -29,27 +29,22 @@
 #ifndef DRILL_STATS_H
 #define DRILL_STATS_H
 
-#include <gdk/gdk.h>      /* This imports gboolean type */
-
+#include <gdk/gdk.h> /* This imports gboolean type */
 
 /* ===================  Prototypes ================ */
 
-gboolean drill_stats_in_drill_list(gerbv_drill_list_t *drill_list, int drill_num);
-gerbv_drill_list_t *gerbv_drill_stats_new_drill_list(void);
-void drill_stats_add_to_drill_list(gerbv_drill_list_t *drill_list_in,
-				   int drill_num_in, double drill_size_in,
-				   char *drill_unit_in);
-void drill_stats_modify_drill_list(gerbv_drill_list_t *drill_list_in,
-				   int drill_num_in, double drill_size_in,
-				   char *drill_unit_in);
-void drill_stats_increment_drill_counter(gerbv_drill_list_t *drill_list_in,
-					 int drill_num_in);
-void drill_stats_add_to_drill_counter(gerbv_drill_list_t *drill_list_in,
-				      int drill_num_in,
-				      int increment);
-gerbv_error_list_t *gerbv_drill_stats_new_error_list(void);
-void drill_stats_add_error(gerbv_error_list_t *error_list_in,
-			   int layer, const char *error_text, 
-			   gerbv_message_type_t type);
+gboolean            drill_stats_in_drill_list(gerbv_drill_list_t* drill_list, int drill_num);
+gerbv_drill_list_t* gerbv_drill_stats_new_drill_list(void);
+void                drill_stats_add_to_drill_list(
+                   gerbv_drill_list_t* drill_list_in, int drill_num_in, double drill_size_in, char* drill_unit_in
+               );
+void drill_stats_modify_drill_list(
+    gerbv_drill_list_t* drill_list_in, int drill_num_in, double drill_size_in, char* drill_unit_in
+);
+void drill_stats_increment_drill_counter(gerbv_drill_list_t* drill_list_in, int drill_num_in);
+void drill_stats_add_to_drill_counter(gerbv_drill_list_t* drill_list_in, int drill_num_in, int increment);
+gerbv_error_list_t* gerbv_drill_stats_new_error_list(void);
+void
+drill_stats_add_error(gerbv_error_list_t* error_list_in, int layer, const char* error_text, gerbv_message_type_t type);
 
 #endif /* DRILL_STATS_H */
diff --git a/src/dynload.c b/src/dynload.c
index 47061af..2e8e80b 100644
--- a/src/dynload.c
+++ b/src/dynload.c
@@ -17,16 +17,16 @@
 #include "common.h"
 
 #ifndef MAXPATHLEN
-# define MAXPATHLEN 1024
+#define MAXPATHLEN 1024
 #endif
 
-static void make_filename(const char *name, char *filename); 
-static void make_init_fn(const char *name, char *init_fn); 
+static void make_filename(const char* name, char* filename);
+static void make_init_fn(const char* name, char* init_fn);
 
 #ifdef _WIN32
-# include <windows.h>
+#include <windows.h>
 #else
-typedef void *HMODULE;
+typedef void* HMODULE;
 typedef void (*FARPROC)();
 #ifndef SUN_DL
 #define SUN_DL
@@ -39,27 +39,31 @@ typedef void (*FARPROC)();
 #define PREFIX ""
 #define SUFFIX ".dll"
 
- static void display_w32_error_msg(const char *additional_message) 
- { 
-   LPVOID msg_buf; 
- 
-   FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, 
-		 NULL, GetLastError(), 0, 
-		 (LPTSTR)&msg_buf, 0, NULL); 
-   fprintf(stderr, _("scheme load-extension: %s: %s"), additional_message, (char *) msg_buf); 
-   LocalFree(msg_buf); 
- } 
-
-static HMODULE dl_attach(const char *module) {
-  HMODULE dll = LoadLibrary(module);
-  if (!dll) display_w32_error_msg(module); 
-  return dll; 
+static void
+display_w32_error_msg(const char* additional_message) {
+    LPVOID msg_buf;
+
+    FormatMessage(
+        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, GetLastError(), 0, (LPTSTR)&msg_buf, 0, NULL
+    );
+    fprintf(stderr, _("scheme load-extension: %s: %s"), additional_message, (char*)msg_buf);
+    LocalFree(msg_buf);
+}
+
+static HMODULE
+dl_attach(const char* module) {
+    HMODULE dll = LoadLibrary(module);
+    if (!dll)
+        display_w32_error_msg(module);
+    return dll;
 }
 
-static FARPROC dl_proc(HMODULE mo, const char *proc) {
-  FARPROC procedure = GetProcAddress(mo,proc); 
-  if (!procedure) display_w32_error_msg(proc); 
-  return procedure; 
+static FARPROC
+dl_proc(HMODULE mo, const char* proc) {
+    FARPROC procedure = GetProcAddress(mo, proc);
+    if (!procedure)
+        display_w32_error_msg(proc);
+    return procedure;
 }
 #if 0
 static void dl_detach(HMODULE mo) {
@@ -73,83 +77,78 @@ static void dl_detach(HMODULE mo) {
 #define PREFIX "lib"
 #define SUFFIX ".so"
 
-static HMODULE dl_attach(const char *module) {
-  HMODULE so=dlopen(module,RTLD_LAZY);
-  if(!so) {
-    fprintf(stderr, _("Error loading scheme extension \"%s\": %s\n"), module, dlerror()); 
-  }
-  return so;
+static HMODULE
+dl_attach(const char* module) {
+    HMODULE so = dlopen(module, RTLD_LAZY);
+    if (!so) {
+        fprintf(stderr, _("Error loading scheme extension \"%s\": %s\n"), module, dlerror());
+    }
+    return so;
 }
 
-static FARPROC dl_proc(HMODULE mo, const char *proc) {
-  const char *errmsg;
-  FARPROC fp=(FARPROC)dlsym(mo,proc);
-  if ((errmsg = dlerror()) == 0) {
-    return fp;
-  }
-  fprintf(stderr, _("Error initializing scheme module \"%s\": %s\n"), proc, errmsg);
- return 0;
+static FARPROC
+dl_proc(HMODULE mo, const char* proc) {
+    const char* errmsg;
+    FARPROC     fp = (FARPROC)dlsym(mo, proc);
+    if ((errmsg = dlerror()) == 0) {
+        return fp;
+    }
+    fprintf(stderr, _("Error initializing scheme module \"%s\": %s\n"), proc, errmsg);
+    return 0;
 }
 #if 0
 static void dl_detach(HMODULE mo) {
  (void)dlclose(mo);
 }
-#endif 
+#endif
 #endif
 
-pointer scm_load_ext(scheme *sc, pointer args)
-{
-   pointer first_arg;
-   pointer retval;
-   char filename[MAXPATHLEN], init_fn[MAXPATHLEN+6];
-   char *name;
-   HMODULE dll_handle;
-   void (*module_init)(scheme *sc);
-   
-   if ((args != sc->NIL) && is_string((first_arg = pair_car(args)))) {
-      name = string_value(first_arg);
-      make_filename(name,filename);     
-      make_init_fn(name,init_fn);     
-      dll_handle = dl_attach(filename);
-      if (dll_handle == 0) {
-         retval = sc -> F;
-      }
-      else {
-         module_init = (void(*)(scheme *))dl_proc(dll_handle, init_fn);
-         if (module_init != 0) {
-            (*module_init)(sc);
-            retval = sc -> T;
-         }
-         else {
+pointer
+scm_load_ext(scheme* sc, pointer args) {
+    pointer first_arg;
+    pointer retval;
+    char    filename[MAXPATHLEN], init_fn[MAXPATHLEN + 6];
+    char*   name;
+    HMODULE dll_handle;
+    void (*module_init)(scheme * sc);
+
+    if ((args != sc->NIL) && is_string((first_arg = pair_car(args)))) {
+        name = string_value(first_arg);
+        make_filename(name, filename);
+        make_init_fn(name, init_fn);
+        dll_handle = dl_attach(filename);
+        if (dll_handle == 0) {
             retval = sc->F;
-         }
-      }
-   }
-   else {
-      retval = sc -> F;
-   }
-   
-  return(retval);
+        } else {
+            module_init = (void (*)(scheme*))dl_proc(dll_handle, init_fn);
+            if (module_init != 0) {
+                (*module_init)(sc);
+                retval = sc->T;
+            } else {
+                retval = sc->F;
+            }
+        }
+    } else {
+        retval = sc->F;
+    }
+
+    return (retval);
 }
 
-static void make_filename(const char *name, char *filename) {
- strcpy(filename,name);
- strcat(filename,SUFFIX);
-}         
-
-static void make_init_fn(const char *name, char *init_fn) {
- const char *p=strrchr(name,'/');/*CHECK ME MINGW PATH SEPARATOR*/
- if(p==0) {
-     p=name;
- } else {
-     p++;
- }
- strcpy(init_fn,"init_");
- strcat(init_fn,p);
+static void
+make_filename(const char* name, char* filename) {
+    strcpy(filename, name);
+    strcat(filename, SUFFIX);
 }
 
-
-
-
-
-
+static void
+make_init_fn(const char* name, char* init_fn) {
+    const char* p = strrchr(name, '/'); /*CHECK ME MINGW PATH SEPARATOR*/
+    if (p == 0) {
+        p = name;
+    } else {
+        p++;
+    }
+    strcpy(init_fn, "init_");
+    strcat(init_fn, p);
+}
diff --git a/src/dynload.h b/src/dynload.h
index 25a60de..249e428 100644
--- a/src/dynload.h
+++ b/src/dynload.h
@@ -12,6 +12,6 @@
 
 #include "scheme-private.h"
 
-SCHEME_EXPORT pointer scm_load_ext(scheme *sc, pointer arglist);
+SCHEME_EXPORT pointer scm_load_ext(scheme* sc, pointer arglist);
 
 #endif
diff --git a/src/export-drill.c b/src/export-drill.c
index 1903053..743c7b4 100644
--- a/src/export-drill.c
+++ b/src/export-drill.c
@@ -33,95 +33,95 @@
 
 #include "common.h"
 
-#define dprintf if(DEBUG) printf
+#define dprintf \
+    if (DEBUG)  \
+    printf
 
-#define round(x) floor(x+0.5)
+#define round(x) floor(x + 0.5)
 
 gboolean
-gerbv_export_drill_file_from_image (const gchar *filename, gerbv_image_t *inputImage,
-		gerbv_user_transformation_t *transform) {
-	FILE *fd;
-	GArray *apertureTable = g_array_new(FALSE, FALSE, sizeof(int));
-	gerbv_net_t *net;
-	
-	/* force gerbv to output decimals as dots (not commas for other locales) */
-	setlocale(LC_NUMERIC, "C");
-	
-	if ((fd = g_fopen(filename, "w")) == NULL) {
-		GERB_COMPILE_ERROR( _("Can't open file for writing: %s"),
-				filename);
-		return FALSE;
-	}
-	
-	/* duplicate the image, cleaning it in the process */
-	gerbv_image_t *image = gerbv_image_duplicate_image (inputImage, transform);
-	
-	/* write header info */
-	fprintf(fd, "M48\n");
-	fprintf(fd, "INCH,TZ\n");
-
-	/* define all apertures */
-	gerbv_aperture_t *aperture;
-
-	/* the image should already have been cleaned by a duplicate_image call, so we can safely
-	   assume the aperture range is correct */
-	for (int i = APERTURE_MIN; i < APERTURE_MAX; i++) {
-		aperture = image->aperture[i];
-		
-		if (!aperture)
-			continue;
-
-		switch (aperture->type) {
-		case GERBV_APTYPE_CIRCLE:
-			fprintf(fd, "T%dC%1.3f\n", i, aperture->parameter[0]);
-			/* add the "approved" aperture to our valid list */
-			g_array_append_val(apertureTable, i);
-			break;
-		default:
-			break;
-		}
-	}
-	
-	fprintf(fd, "%%\n");
-	/* write rest of image */
-	
-	for (guint i = 0; i < apertureTable->len; i++) {
-		int aperture_idx = g_array_index(apertureTable, int, i);
-		
-		/* write tool change */
-		fprintf(fd, "T%d\n", aperture_idx);
-		
-		/* run through all nets and look for drills using this aperture */
-		for (net = image->netlist; net; net = net->next) {
-			if (net->aperture != aperture_idx)
-				continue;
-
-			switch (net->aperture_state) {
-			case GERBV_APERTURE_STATE_FLASH:
-				fprintf(fd, "X%06ldY%06ld\n",
-					(long)round(net->stop_x * 10000.0),
-					(long)round(net->stop_y * 10000.0));
-				break;
-			case GERBV_APERTURE_STATE_ON:	/* Cut slot */
-				fprintf(fd, "X%06ldY%06ldG85X%06ldY%06ld\n",
-					(long)round(net->start_x * 10000.0),
-					(long)round(net->start_y * 10000.0),
-					(long)round(net->stop_x * 10000.0),
-					(long)round(net->stop_y * 10000.0));
-				break;
-			default:
-				break;
-			}
-		}
-	}
-	g_array_free (apertureTable, TRUE);
-
-	/* write footer */
-	fprintf(fd, "M30\n\n");
-	gerbv_destroy_image(image);
-	fclose(fd);
-	
-	/* return to the default locale */
-	setlocale(LC_NUMERIC, "");
-	return TRUE;
+gerbv_export_drill_file_from_image(
+    const gchar* filename, gerbv_image_t* inputImage, gerbv_user_transformation_t* transform
+) {
+    FILE*        fd;
+    GArray*      apertureTable = g_array_new(FALSE, FALSE, sizeof(int));
+    gerbv_net_t* net;
+
+    /* force gerbv to output decimals as dots (not commas for other locales) */
+    setlocale(LC_NUMERIC, "C");
+
+    if ((fd = g_fopen(filename, "w")) == NULL) {
+        GERB_COMPILE_ERROR(_("Can't open file for writing: %s"), filename);
+        return FALSE;
+    }
+
+    /* duplicate the image, cleaning it in the process */
+    gerbv_image_t* image = gerbv_image_duplicate_image(inputImage, transform);
+
+    /* write header info */
+    fprintf(fd, "M48\n");
+    fprintf(fd, "INCH,TZ\n");
+
+    /* define all apertures */
+    gerbv_aperture_t* aperture;
+
+    /* the image should already have been cleaned by a duplicate_image call, so we can safely
+       assume the aperture range is correct */
+    for (int i = APERTURE_MIN; i < APERTURE_MAX; i++) {
+        aperture = image->aperture[i];
+
+        if (!aperture)
+            continue;
+
+        switch (aperture->type) {
+            case GERBV_APTYPE_CIRCLE:
+                fprintf(fd, "T%dC%1.3f\n", i, aperture->parameter[0]);
+                /* add the "approved" aperture to our valid list */
+                g_array_append_val(apertureTable, i);
+                break;
+            default: break;
+        }
+    }
+
+    fprintf(fd, "%%\n");
+    /* write rest of image */
+
+    for (guint i = 0; i < apertureTable->len; i++) {
+        int aperture_idx = g_array_index(apertureTable, int, i);
+
+        /* write tool change */
+        fprintf(fd, "T%d\n", aperture_idx);
+
+        /* run through all nets and look for drills using this aperture */
+        for (net = image->netlist; net; net = net->next) {
+            if (net->aperture != aperture_idx)
+                continue;
+
+            switch (net->aperture_state) {
+                case GERBV_APERTURE_STATE_FLASH:
+                    fprintf(
+                        fd, "X%06ldY%06ld\n", (long)round(net->stop_x * 10000.0), (long)round(net->stop_y * 10000.0)
+                    );
+                    break;
+                case GERBV_APERTURE_STATE_ON: /* Cut slot */
+                    fprintf(
+                        fd, "X%06ldY%06ldG85X%06ldY%06ld\n", (long)round(net->start_x * 10000.0),
+                        (long)round(net->start_y * 10000.0), (long)round(net->stop_x * 10000.0),
+                        (long)round(net->stop_y * 10000.0)
+                    );
+                    break;
+                default: break;
+            }
+        }
+    }
+    g_array_free(apertureTable, TRUE);
+
+    /* write footer */
+    fprintf(fd, "M30\n\n");
+    gerbv_destroy_image(image);
+    fclose(fd);
+
+    /* return to the default locale */
+    setlocale(LC_NUMERIC, "");
+    return TRUE;
 }
diff --git a/src/export-dxf.cpp b/src/export-dxf.cpp
index ee6ec6a..b1617b6 100644
--- a/src/export-dxf.cpp
+++ b/src/export-dxf.cpp
@@ -35,329 +35,302 @@
 
 #include "common.h"
 
-/* dxflib version difference */			
+/* dxflib version difference */
 #ifndef DL_STRGRP_END
-# define DL_STRGRP_END STRGRP_END
+#define DL_STRGRP_END STRGRP_END
 #endif
 #ifndef DL_ATTFLAGS_CODE
-# define DL_ATTFLAGS_CODE ATTFLAGS_CODE
+#define DL_ATTFLAGS_CODE ATTFLAGS_CODE
 #endif
 #ifndef DL_TXTHI_CODE
-# define DL_TXTHI_CODE TXTHI_CODE
+#define DL_TXTHI_CODE TXTHI_CODE
 #endif
 #ifndef DL_TXT_STYLE_CODE
-# define DL_TXT_STYLE_CODE TXT_STYLE_CODE
+#define DL_TXT_STYLE_CODE TXT_STYLE_CODE
 #endif
 #ifndef DL_FIRST_XCOORD_CODE
-# define DL_FIRST_XCOORD_CODE FIRST_XCOORD_CODE
+#define DL_FIRST_XCOORD_CODE FIRST_XCOORD_CODE
 #endif
 #ifndef DL_FIRST_YCOORD_CODE
-# define DL_FIRST_YCOORD_CODE FIRST_YCOORD_CODE
+#define DL_FIRST_YCOORD_CODE FIRST_YCOORD_CODE
 #endif
 #ifndef DL_CLOSED_PLINE
-# define DL_CLOSED_PLINE CLOSED_PLINE
+#define DL_CLOSED_PLINE CLOSED_PLINE
 #endif
 
 enum insunits {
-	INSUNITS_NONE = 0,
-	INSUNITS_INCH,
-	INSUNITS_FEET,
-	INSUNITS_MILE,
-	INSUNITS_MM,
-	INSUNITS_CM,
-	INSUNITS_M,
-	INSUNITS_KM,
-	INSUNITS_MICROINCH,
-	INSUNITS_MIL,
-	/* ... and more ... */
+    INSUNITS_NONE = 0,
+    INSUNITS_INCH,
+    INSUNITS_FEET,
+    INSUNITS_MILE,
+    INSUNITS_MM,
+    INSUNITS_CM,
+    INSUNITS_M,
+    INSUNITS_KM,
+    INSUNITS_MICROINCH,
+    INSUNITS_MIL,
+    /* ... and more ... */
 };
 
-extern "C"
-{
+extern "C" {
 gboolean
-gerbv_export_dxf_file_from_image(const gchar *file_name,
-		gerbv_image_t *input_img,
-		gerbv_user_transformation_t *trans)
-{
-	DL_Codes::version exportVersion = DL_Codes::AC1015;
-	DL_Dxf* dxf = new DL_Dxf();
-	DL_WriterA* dw;
-	gerbv_aperture_t *apert;
-	gerbv_image_t *img;
-	gerbv_net_t *net;
-	GArray *apert_tab;
-	double x[4], y[4], r, dx, dy, nom;
-	unsigned int i;
+gerbv_export_dxf_file_from_image(const gchar* file_name, gerbv_image_t* input_img, gerbv_user_transformation_t* trans) {
+    DL_Codes::version exportVersion = DL_Codes::AC1015;
+    DL_Dxf*           dxf           = new DL_Dxf();
+    DL_WriterA*       dw;
+    gerbv_aperture_t* apert;
+    gerbv_image_t*    img;
+    gerbv_net_t*      net;
+    GArray*           apert_tab;
+    double            x[4], y[4], r, dx, dy, nom;
+    unsigned int      i;
 
-	dw = dxf->out(file_name, exportVersion);
+    dw = dxf->out(file_name, exportVersion);
 
-	if (dw == NULL) {
-		GERB_MESSAGE(_("Can't open file for writing: %s"), file_name);
-		return FALSE;
-	}
+    if (dw == NULL) {
+        GERB_MESSAGE(_("Can't open file for writing: %s"), file_name);
+        return FALSE;
+    }
 
-	/* Output decimals as dots for all locales */
-	setlocale(LC_NUMERIC, "C");
+    /* Output decimals as dots for all locales */
+    setlocale(LC_NUMERIC, "C");
 
-	/* Duplicate the image, cleaning it in the process */
-	img = gerbv_image_duplicate_image(input_img, trans);
+    /* Duplicate the image, cleaning it in the process */
+    img = gerbv_image_duplicate_image(input_img, trans);
 
-	dxf->writeHeader(*dw);
+    dxf->writeHeader(*dw);
 
-	dw->dxfString(DL_STRGRP_END, "$INSUNITS");
-	dw->dxfInt(DL_ATTFLAGS_CODE, INSUNITS_INCH);
+    dw->dxfString(DL_STRGRP_END, "$INSUNITS");
+    dw->dxfInt(DL_ATTFLAGS_CODE, INSUNITS_INCH);
 
-	dw->dxfString(DL_STRGRP_END, "$DIMEXE");
-	dw->dxfReal(DL_TXTHI_CODE, 1.25);
+    dw->dxfString(DL_STRGRP_END, "$DIMEXE");
+    dw->dxfReal(DL_TXTHI_CODE, 1.25);
 
-	dw->dxfString(DL_STRGRP_END, "$TEXTSTYLE");
-	dw->dxfString(DL_TXT_STYLE_CODE, "Standard");
+    dw->dxfString(DL_STRGRP_END, "$TEXTSTYLE");
+    dw->dxfString(DL_TXT_STYLE_CODE, "Standard");
 
-	/* TODO ? */
-	dw->dxfString(DL_STRGRP_END, "$LIMMIN");
-	dw->dxfReal(DL_FIRST_XCOORD_CODE, 0.0);
-	dw->dxfReal(DL_FIRST_YCOORD_CODE, 0.0);
+    /* TODO ? */
+    dw->dxfString(DL_STRGRP_END, "$LIMMIN");
+    dw->dxfReal(DL_FIRST_XCOORD_CODE, 0.0);
+    dw->dxfReal(DL_FIRST_YCOORD_CODE, 0.0);
 
-	dw->sectionEnd();
+    dw->sectionEnd();
 
-	dw->sectionTables();
-	dxf->writeVPort(*dw);
+    dw->sectionTables();
+    dxf->writeVPort(*dw);
 
-	/* Line types */
+    /* Line types */
 #if (DL_VERSION_MAJOR == 3)
-	dw->tableLinetypes(1);
-	dxf->writeLinetype(*dw, DL_LinetypeData("ByLayer", "ByLayer", 0, 0, 0));
+    dw->tableLinetypes(1);
+    dxf->writeLinetype(*dw, DL_LinetypeData("ByLayer", "ByLayer", 0, 0, 0));
 #else
-	dw->tableLineTypes(1);
-	dxf->writeLineType(*dw, DL_LineTypeData("ByLayer", 0));
+    dw->tableLineTypes(1);
+    dxf->writeLineType(*dw, DL_LineTypeData("ByLayer", 0));
 #endif
 
-	dw->tableEnd();
+    dw->tableEnd();
 
-	/* Layers */
-	dw->tableLayers(1);			/* One layer */
+    /* Layers */
+    dw->tableLayers(1); /* One layer */
 
 #if (DL_VERSION_MAJOR == 3)
-	dxf->writeLayer(*dw, DL_LayerData("0", 0),
-			DL_Attributes("",
-				DL_Codes::black,/* Color */
-				10,		/* Width */
-				"Continuous", 1)); /* Line style and scale */
+    dxf->writeLayer(
+        *dw, DL_LayerData("0", 0),
+        DL_Attributes(
+            "", DL_Codes::black, /* Color */
+            10,                  /* Width */
+            "Continuous", 1
+        )
+    ); /* Line style and scale */
 #else
-	dxf->writeLayer(*dw, DL_LayerData("0", 0),
-			DL_Attributes("",
-				DL_Codes::black,/* Color */
-				10,		/* Width */
-				"Continuous"));	/* Line style */
+    dxf->writeLayer(
+        *dw, DL_LayerData("0", 0),
+        DL_Attributes(
+            "", DL_Codes::black, /* Color */
+            10,                  /* Width */
+            "Continuous"
+        )
+    ); /* Line style */
 #endif
 
-	dw->tableEnd();
+    dw->tableEnd();
 
 #if (DL_VERSION_MAJOR == 3)
-	dxf->writeStyle(*dw, DL_StyleData("Standard",
-				0, 2.5, 1.0, 0.0, 0, 2.5, "txt", ""));
+    dxf->writeStyle(*dw, DL_StyleData("Standard", 0, 2.5, 1.0, 0.0, 0, 2.5, "txt", ""));
 #else
-	dxf->writeStyle(*dw);
+    dxf->writeStyle(*dw);
 #endif
 
-	dxf->writeView(*dw);
-	dxf->writeUcs(*dw);
-	dw->tableAppid(1);
-	dw->tableAppidEntry(0x12);
-	dw->dxfString(2, "ACAD");
-	dw->dxfInt(DL_ATTFLAGS_CODE, 0);
-	dw->tableEnd();
-	dw->sectionEnd();
+    dxf->writeView(*dw);
+    dxf->writeUcs(*dw);
+    dw->tableAppid(1);
+    dw->tableAppidEntry(0x12);
+    dw->dxfString(2, "ACAD");
+    dw->dxfInt(DL_ATTFLAGS_CODE, 0);
+    dw->tableEnd();
+    dw->sectionEnd();
 
-	/* All entities */
-	dw->sectionEntities();
+    /* All entities */
+    dw->sectionEntities();
 
 #if (DL_VERSION_MAJOR == 3)
-	DL_Attributes *attr = new DL_Attributes("0", 0, -1, "ByLayer", 1.0);
+    DL_Attributes* attr = new DL_Attributes("0", 0, -1, "ByLayer", 1.0);
 #else
-	DL_Attributes *attr = new DL_Attributes("0", 0, -1, "ByLayer");
+    DL_Attributes* attr = new DL_Attributes("0", 0, -1, "ByLayer");
 #endif
 
-	for (net = img->netlist; net != NULL; net = net->next) {
-		apert = img->aperture[net->aperture];
-		if (!apert)
-			continue;
-
-		if (net->interpolation == GERBV_INTERPOLATION_PAREA_START) {
-			dxf->writePolyline(*dw,
-				DL_PolylineData(1, 0, 0, DL_CLOSED_PLINE),
-				*attr);
-
-			net = net->next;
-
-			while (net != NULL && net->interpolation !=
-					GERBV_INTERPOLATION_PAREA_END) {
-				if (net->aperture_state ==
-						GERBV_APERTURE_STATE_ON) {
-					dxf->writeVertex(*dw,
-						DL_VertexData(
-							COORD2INS(net->stop_x),
-							COORD2INS(net->stop_y),
-							0, 0));
-				}
-				net = net->next;
-			}
-
-			dxf->writePolylineEnd(*dw);
-
-			continue;
-		}
-
-		switch (net->aperture_state) {
-		case GERBV_APERTURE_STATE_FLASH:
-			switch (apert->type) {
-			case GERBV_APTYPE_CIRCLE:
-				x[0] = net->stop_x;
-				y[0] = net->stop_y;
-				r = apert->parameter[0]/2;
-				dxf->writeCircle(*dw,
-					DL_CircleData(x[0], y[0], 0.0, r),
-						*attr);
-				break;
-			case GERBV_APTYPE_RECTANGLE:
-				x[0] = net->stop_x + apert->parameter[0]/2;
-				y[0] = net->stop_y + apert->parameter[1]/2;
-				x[1] = x[0];
-				y[1] = y[0] - apert->parameter[1];
-				x[2] = x[1] - apert->parameter[0];
-				y[2] = y[1];
-				x[3] = x[2];
-				y[3] = y[0];
-				dxf->writePolyline(*dw,
-					DL_PolylineData(4, 0, 0, DL_CLOSED_PLINE),
-					*attr);
-				for (i = 0; i < 4; i++)
-					dxf->writeVertex(*dw,
-						DL_VertexData(x[i], y[i], 0, 0));
-				dxf->writePolylineEnd(*dw);
-				break;
-			case GERBV_APTYPE_OVAL:
-				if (apert->parameter[0] > apert->parameter[1]) {
-					/* Horizontal oval */
-					r = apert->parameter[1]/2;
-					dx = apert->parameter[0]/2 - r;
-
-					x[0] = net->stop_x - dx;
-					y[0] = net->stop_y + r;
-					x[1] = net->stop_x + dx;
-					y[1] = y[0];
-					x[2] = x[1];
-					y[2] = net->stop_y - r;
-					x[3] = x[0];
-					y[3] = y[2];
-				} else {
-					/* Vertical oval */
-					r = apert->parameter[0]/2;
-					dy = apert->parameter[1]/2 - r;
-
-					x[0] = net->stop_x - r;
-					y[0] = net->stop_y - dy;
-					x[1] = x[0];
-					y[1] = net->stop_y + dy;
-					x[2] = net->stop_x + r;
-					y[2] = y[1];
-					x[3] = x[2];
-					y[3] = y[0];
-				}
-
-				dxf->writePolyline(*dw,
-					DL_PolylineData(4, 0, 0, DL_CLOSED_PLINE),
-					*attr);
-				dxf->writeVertex(*dw,
-					DL_VertexData(x[3], y[3], 0, -1));
-				dxf->writeVertex(*dw,
-					DL_VertexData(x[0], y[0], 0, 0));
-				dxf->writeVertex(*dw,
-					DL_VertexData(x[1], y[1], 0, -1));
-				dxf->writeVertex(*dw,
-					DL_VertexData(x[2], y[2], 0, 0));
-
-				dxf->writePolylineEnd(*dw);
-				break;
-			case GERBV_APTYPE_MACRO:
-			default:
-/* TODO: other GERBV_APTYPE_ */
-				GERB_COMPILE_WARNING(
-						"%s:%d: aperture type %d is "
-						"not yet supported",
-						__func__, __LINE__,
-						apert->type);
-				break;
-			}
-			break;
-		case GERBV_APERTURE_STATE_ON:
-			/* Line or cut slot in drill file */
-			switch (apert->type) {
-			case GERBV_APTYPE_CIRCLE:
-				/* Calculate perpendicular vector */
-				dx = net->stop_x - net->start_x;
-				dy = net->stop_y - net->start_y;
-				nom = apert->parameter[0] /
-					(2*sqrt(dx*dx + dy*dy));
-				dx = dx * nom;
-				dy = dy * nom;
-
-				/* Line 1 of 2 */
-				x[0] = net->stop_x + dy;
-				y[0] = net->stop_y - dx;
-				x[1] = net->start_x + dy;
-				y[1] = net->start_y - dx;
-
-				/* Line 2 of 2 */
-				x[2] = net->start_x - dy;
-				y[2] = net->start_y + dx;
-				x[3] = net->stop_x - dy;
-				y[3] = net->stop_y + dx;
-
-				dxf->writePolyline(*dw,
-					DL_PolylineData(4, 0, 0, DL_CLOSED_PLINE),
-					*attr);
-				dxf->writeVertex(*dw,
-					DL_VertexData(x[3], y[3], 0, -1));
-				dxf->writeVertex(*dw,
-					DL_VertexData(x[0], y[0], 0, 0));
-				dxf->writeVertex(*dw,
-					DL_VertexData(x[1], y[1], 0, -1));
-				dxf->writeVertex(*dw,
-					DL_VertexData(x[2], y[2], 0, 0));
-
-				dxf->writePolylineEnd(*dw);
-				break;
-			default:
-				GERB_COMPILE_WARNING(
-						"%s:%d: aperture type %d is "
-						"not yet supported",
-						__func__, __LINE__,
-						apert->type);
-				break;
-			}
-			break;
-		default:
-			break;
-		}
-
-	}
-
-	gerbv_destroy_image(img);
-
-	dw->sectionEnd();
-
-	dxf->writeObjects(*dw);
-	dxf->writeObjectsEnd(*dw);
-	dw->dxfEOF();
-	dw->close();
-
-	delete attr;
-	delete dw;
-	delete dxf;
-
-	setlocale(LC_NUMERIC, "");	/* Return to the default locale */
-
-	return TRUE;
+    for (net = img->netlist; net != NULL; net = net->next) {
+        apert = img->aperture[net->aperture];
+        if (!apert)
+            continue;
+
+        if (net->interpolation == GERBV_INTERPOLATION_PAREA_START) {
+            dxf->writePolyline(*dw, DL_PolylineData(1, 0, 0, DL_CLOSED_PLINE), *attr);
+
+            net = net->next;
+
+            while (net != NULL && net->interpolation != GERBV_INTERPOLATION_PAREA_END) {
+                if (net->aperture_state == GERBV_APERTURE_STATE_ON) {
+                    dxf->writeVertex(*dw, DL_VertexData(COORD2INS(net->stop_x), COORD2INS(net->stop_y), 0, 0));
+                }
+                net = net->next;
+            }
+
+            dxf->writePolylineEnd(*dw);
+
+            continue;
+        }
+
+        switch (net->aperture_state) {
+            case GERBV_APERTURE_STATE_FLASH:
+                switch (apert->type) {
+                    case GERBV_APTYPE_CIRCLE:
+                        x[0] = net->stop_x;
+                        y[0] = net->stop_y;
+                        r    = apert->parameter[0] / 2;
+                        dxf->writeCircle(*dw, DL_CircleData(x[0], y[0], 0.0, r), *attr);
+                        break;
+                    case GERBV_APTYPE_RECTANGLE:
+                        x[0] = net->stop_x + apert->parameter[0] / 2;
+                        y[0] = net->stop_y + apert->parameter[1] / 2;
+                        x[1] = x[0];
+                        y[1] = y[0] - apert->parameter[1];
+                        x[2] = x[1] - apert->parameter[0];
+                        y[2] = y[1];
+                        x[3] = x[2];
+                        y[3] = y[0];
+                        dxf->writePolyline(*dw, DL_PolylineData(4, 0, 0, DL_CLOSED_PLINE), *attr);
+                        for (i = 0; i < 4; i++)
+                            dxf->writeVertex(*dw, DL_VertexData(x[i], y[i], 0, 0));
+                        dxf->writePolylineEnd(*dw);
+                        break;
+                    case GERBV_APTYPE_OVAL:
+                        if (apert->parameter[0] > apert->parameter[1]) {
+                            /* Horizontal oval */
+                            r  = apert->parameter[1] / 2;
+                            dx = apert->parameter[0] / 2 - r;
+
+                            x[0] = net->stop_x - dx;
+                            y[0] = net->stop_y + r;
+                            x[1] = net->stop_x + dx;
+                            y[1] = y[0];
+                            x[2] = x[1];
+                            y[2] = net->stop_y - r;
+                            x[3] = x[0];
+                            y[3] = y[2];
+                        } else {
+                            /* Vertical oval */
+                            r  = apert->parameter[0] / 2;
+                            dy = apert->parameter[1] / 2 - r;
+
+                            x[0] = net->stop_x - r;
+                            y[0] = net->stop_y - dy;
+                            x[1] = x[0];
+                            y[1] = net->stop_y + dy;
+                            x[2] = net->stop_x + r;
+                            y[2] = y[1];
+                            x[3] = x[2];
+                            y[3] = y[0];
+                        }
+
+                        dxf->writePolyline(*dw, DL_PolylineData(4, 0, 0, DL_CLOSED_PLINE), *attr);
+                        dxf->writeVertex(*dw, DL_VertexData(x[3], y[3], 0, -1));
+                        dxf->writeVertex(*dw, DL_VertexData(x[0], y[0], 0, 0));
+                        dxf->writeVertex(*dw, DL_VertexData(x[1], y[1], 0, -1));
+                        dxf->writeVertex(*dw, DL_VertexData(x[2], y[2], 0, 0));
+
+                        dxf->writePolylineEnd(*dw);
+                        break;
+                    case GERBV_APTYPE_MACRO:
+                    default:
+                        /* TODO: other GERBV_APTYPE_ */
+                        GERB_COMPILE_WARNING(
+                            "%s:%d: aperture type %d is "
+                            "not yet supported",
+                            __func__, __LINE__, apert->type
+                        );
+                        break;
+                }
+                break;
+            case GERBV_APERTURE_STATE_ON:
+                /* Line or cut slot in drill file */
+                switch (apert->type) {
+                    case GERBV_APTYPE_CIRCLE:
+                        /* Calculate perpendicular vector */
+                        dx  = net->stop_x - net->start_x;
+                        dy  = net->stop_y - net->start_y;
+                        nom = apert->parameter[0] / (2 * sqrt(dx * dx + dy * dy));
+                        dx  = dx * nom;
+                        dy  = dy * nom;
+
+                        /* Line 1 of 2 */
+                        x[0] = net->stop_x + dy;
+                        y[0] = net->stop_y - dx;
+                        x[1] = net->start_x + dy;
+                        y[1] = net->start_y - dx;
+
+                        /* Line 2 of 2 */
+                        x[2] = net->start_x - dy;
+                        y[2] = net->start_y + dx;
+                        x[3] = net->stop_x - dy;
+                        y[3] = net->stop_y + dx;
+
+                        dxf->writePolyline(*dw, DL_PolylineData(4, 0, 0, DL_CLOSED_PLINE), *attr);
+                        dxf->writeVertex(*dw, DL_VertexData(x[3], y[3], 0, -1));
+                        dxf->writeVertex(*dw, DL_VertexData(x[0], y[0], 0, 0));
+                        dxf->writeVertex(*dw, DL_VertexData(x[1], y[1], 0, -1));
+                        dxf->writeVertex(*dw, DL_VertexData(x[2], y[2], 0, 0));
+
+                        dxf->writePolylineEnd(*dw);
+                        break;
+                    default:
+                        GERB_COMPILE_WARNING(
+                            "%s:%d: aperture type %d is "
+                            "not yet supported",
+                            __func__, __LINE__, apert->type
+                        );
+                        break;
+                }
+                break;
+            default: break;
+        }
+    }
+
+    gerbv_destroy_image(img);
+
+    dw->sectionEnd();
+
+    dxf->writeObjects(*dw);
+    dxf->writeObjectsEnd(*dw);
+    dw->dxfEOF();
+    dw->close();
+
+    delete attr;
+    delete dw;
+    delete dxf;
+
+    setlocale(LC_NUMERIC, ""); /* Return to the default locale */
+
+    return TRUE;
 }
 } /* extern "C" */
diff --git a/src/export-geda-pcb.c b/src/export-geda-pcb.c
index 4daf471..f616b6b 100644
--- a/src/export-geda-pcb.c
+++ b/src/export-geda-pcb.c
@@ -30,254 +30,239 @@
 #include <glib/gstdio.h>
 
 static void
-write_line(FILE *fd, gerbv_net_t *net, double thick,
-		double dx_p, double dy_m, const char *sflags)
-{
-	dx_p = COORD2MILS(dx_p);
-	dy_m = COORD2MILS(dy_m);
-
-	fprintf(fd, "\tLine[%.2fmil %.2fmil %.2fmil %.2fmil "
-			"%.2fmil %.2fmil \"%s\"]\n",
-			dx_p + COORD2MILS(net->stop_x),
-			dy_m - COORD2MILS(net->stop_y),
-			dx_p + COORD2MILS(net->start_x),
-			dy_m - COORD2MILS(net->start_y),
-			COORD2MILS(thick), 100.0, sflags);
+write_line(FILE* fd, gerbv_net_t* net, double thick, double dx_p, double dy_m, const char* sflags) {
+    dx_p = COORD2MILS(dx_p);
+    dy_m = COORD2MILS(dy_m);
+
+    fprintf(
+        fd,
+        "\tLine[%.2fmil %.2fmil %.2fmil %.2fmil "
+        "%.2fmil %.2fmil \"%s\"]\n",
+        dx_p + COORD2MILS(net->stop_x), dy_m - COORD2MILS(net->stop_y), dx_p + COORD2MILS(net->start_x),
+        dy_m - COORD2MILS(net->start_y), COORD2MILS(thick), 100.0, sflags
+    );
 }
 
 static void
-write_element_with_pad(FILE *fd, gerbv_net_t *net, double thick,
-		double dx_p, double dy_m, const char *sflags)
-{
-	double xc, yc;
-	static unsigned int element_num = 1;
-
-	dx_p = COORD2MILS(dx_p);
-	dy_m = COORD2MILS(dy_m);
-
-	xc = COORD2MILS(net->stop_x + net->start_x)/2;
-	yc = COORD2MILS(net->stop_y + net->start_y)/2;
-
-	fprintf(fd, "Element[\"\" \"\" \"pad%d\" \"\" "
-			"%.2fmil %.2fmil 0mil 0mil 0 100 \"\"]\n(\n",
-			element_num++, dx_p + xc, dy_m - yc);
-	fprintf(fd, "\tPad[%.2fmil %.2fmil %.2fmil %.2fmil "
-			"%.2fmil 0mil %.2fmil "
-			"\"%s\" \"%s\" \"%s\"]\n)\n",
-			xc - COORD2MILS(net->stop_x),
-			yc - COORD2MILS(net->stop_y),
-			xc - COORD2MILS(net->start_x),
-			yc - COORD2MILS(net->start_y),
-			COORD2MILS(thick),	/* Thickness */
-			COORD2MILS(thick),	/* Mask */
-			"1",			/* Name */
-			"1",			/* Number */
-			sflags);		/* String flags */
+write_element_with_pad(FILE* fd, gerbv_net_t* net, double thick, double dx_p, double dy_m, const char* sflags) {
+    double              xc, yc;
+    static unsigned int element_num = 1;
+
+    dx_p = COORD2MILS(dx_p);
+    dy_m = COORD2MILS(dy_m);
+
+    xc = COORD2MILS(net->stop_x + net->start_x) / 2;
+    yc = COORD2MILS(net->stop_y + net->start_y) / 2;
+
+    fprintf(
+        fd,
+        "Element[\"\" \"\" \"pad%d\" \"\" "
+        "%.2fmil %.2fmil 0mil 0mil 0 100 \"\"]\n(\n",
+        element_num++, dx_p + xc, dy_m - yc
+    );
+    fprintf(
+        fd,
+        "\tPad[%.2fmil %.2fmil %.2fmil %.2fmil "
+        "%.2fmil 0mil %.2fmil "
+        "\"%s\" \"%s\" \"%s\"]\n)\n",
+        xc - COORD2MILS(net->stop_x), yc - COORD2MILS(net->stop_y), xc - COORD2MILS(net->start_x),
+        yc - COORD2MILS(net->start_y), COORD2MILS(thick), /* Thickness */
+        COORD2MILS(thick),                                /* Mask */
+        "1",                                              /* Name */
+        "1",                                              /* Number */
+        sflags
+    ); /* String flags */
 }
 
 static void
-write_polygon(FILE *fd, gerbv_net_t *net,
-		double dx_p, double dy_m, const char *sflags)
-{
-	dx_p = COORD2MILS(dx_p);
-	dy_m = COORD2MILS(dy_m);
-
-	fprintf(fd, "\tPolygon(\"%s\")\n\t(", sflags);
-	net = net->next;
-
-	unsigned int i = 0;
-	while (net != NULL
-		&& net->interpolation != GERBV_INTERPOLATION_PAREA_END) {
-		if (net->aperture_state == GERBV_APERTURE_STATE_ON) {
-			fprintf(fd, "%s[%.2fmil %.2fmil] ",
-				!(i%5)? "\n\t\t": "",
-				dx_p + COORD2MILS(net->stop_x),
-				dy_m - COORD2MILS(net->stop_y));
-				i++;
-		}
-		net = net->next;
-	}
-
-	fprintf(fd, "\n\t)\n");
+write_polygon(FILE* fd, gerbv_net_t* net, double dx_p, double dy_m, const char* sflags) {
+    dx_p = COORD2MILS(dx_p);
+    dy_m = COORD2MILS(dy_m);
+
+    fprintf(fd, "\tPolygon(\"%s\")\n\t(", sflags);
+    net = net->next;
+
+    unsigned int i = 0;
+    while (net != NULL && net->interpolation != GERBV_INTERPOLATION_PAREA_END) {
+        if (net->aperture_state == GERBV_APERTURE_STATE_ON) {
+            fprintf(
+                fd, "%s[%.2fmil %.2fmil] ", !(i % 5) ? "\n\t\t" : "", dx_p + COORD2MILS(net->stop_x),
+                dy_m - COORD2MILS(net->stop_y)
+            );
+            i++;
+        }
+        net = net->next;
+    }
+
+    fprintf(fd, "\n\t)\n");
 }
 
 gboolean
-gerbv_export_geda_pcb_file_from_image(const gchar *file_name,
-		gerbv_image_t *input_img,
-		gerbv_user_transformation_t *trans)
-{
-	gerbv_aperture_t *apert;
-	gerbv_image_t *img;
-	gerbv_net_t *net;
-	double dx_p, dy_m;
-	double thick, len;
-	FILE *fd;
-
-	if ((fd = g_fopen(file_name, "w")) == NULL) {
-		GERB_MESSAGE(_("Can't open file for writing: %s"), file_name);
-		return FALSE;
-	}
-
-	/* Output decimals as dots for all locales */
-	setlocale(LC_NUMERIC, "C");
-
-	/* Duplicate the image, cleaning it in the process */
-	img = gerbv_image_duplicate_image(input_img, trans);
-
-	/* Header */
-	fputs("# Generated with gerbv\n\n", fd);
-	fputs("FileVersion[20091103]\n", fd);
-
-	dx_p = (img->info->max_x - img->info->min_x) - img->info->min_x;
-	dy_m = 2*(img->info->max_y - img->info->min_y) + img->info->min_y;
-
-	/* Make board size is 3 times more than Gerber size */
-	fprintf(fd, "PCB[\"%s\" %.2fmil %.2fmil]\n",
-			img->info->name,
-			3*COORD2MILS(img->info->max_x - img->info->min_x),
-			3*COORD2MILS(img->info->max_y - img->info->min_y));
-
-	fputs("Grid[1000.000000 0.0000 0.0000 0]\n", fd);
-
-	/* Write all apertures as elements with single pad, before layer
-	 * definition */
-	for (net = img->netlist; net != NULL; net = net->next) {
-		apert = img->aperture[net->aperture];
-		if (!apert)
-			continue;
-
-		/* Skip polygon, it will be written in layer section */
-		if (net->interpolation == GERBV_INTERPOLATION_PAREA_START) {
-			/* Skip to the end for polygon */
-			do {
-				net = net->next;
-			} while (net != NULL && net->interpolation !=
-					GERBV_INTERPOLATION_PAREA_END);
-			continue;
-		}
-
-		switch (net->aperture_state) {
-		case GERBV_APERTURE_STATE_FLASH:
-			switch (apert->type) {
-			case GERBV_APTYPE_CIRCLE:
-				/* Set start to stop coords for Circle flash */
-				net->start_x = net->stop_x;
-				net->start_y = net->stop_y;
-				write_element_with_pad(fd, net,
-						apert->parameter[0],
-						dx_p, dy_m, "");
-				break;
-			case GERBV_APTYPE_OVAL:
-			case GERBV_APTYPE_RECTANGLE:
-
-				if (apert->parameter[0] > apert->parameter[1]) {
-					/* Horizontal */
-					len = apert->parameter[0];
-					thick = apert->parameter[1];
-
-					net->start_x = net->stop_x - len/2 +
-								thick/2;
-					net->stop_x += len/2 - thick/2;
-					net->start_y = net->stop_y;
-				} else {
-					/* Vertical */
-					len = apert->parameter[1];
-					thick = apert->parameter[0];
-
-					net->start_x = net->stop_x;
-					net->start_y = net->stop_y - len/2 +
-								thick/2;
-					net->stop_y += len/2 - thick/2;
-				}
-
-				write_element_with_pad(fd, net, thick,
-					dx_p, dy_m,
-					(apert->type == GERBV_APTYPE_RECTANGLE)?
-						"square": "");
-				break;
-			default:
-/* TODO */
-				GERB_COMPILE_WARNING(
-					"%s:%d: aperture type %d is "
-					"not yet supported",
-					__func__, __LINE__,
-					apert->type);
-				break;
-			}
-			break;
-		case GERBV_APERTURE_STATE_ON:
-			/* Will be done in layer section */
-			break;
-		default:
-/* TODO */
-			GERB_COMPILE_WARNING(
-					"%s:%d: aperture type %d is "
-					"not yet supported",
-					__func__, __LINE__,
-					apert->type);
-			break;
-		}
-	}
-
-	/* Write all lines in layer definition */
-	fputs("Layer(1 \"top\")\n(\n", fd);
-
-	for (net = img->netlist; net != NULL; net = net->next) {
-		apert = img->aperture[net->aperture];
-		if (!apert)
-			continue;
-
-		if (net->interpolation == GERBV_INTERPOLATION_PAREA_START) {
-			write_polygon(fd, net, dx_p, dy_m, "clearpoly");
-
-			/* Skip to the end for polygon */
-			do {
-				net = net->next;
-			} while (net != NULL && net->interpolation !=
-					GERBV_INTERPOLATION_PAREA_END);
-			continue;
-		}
-
-		switch (net->aperture_state) {
-		case GERBV_APERTURE_STATE_FLASH:
-			/* Already done in elements section */
-			break;
-
-		case GERBV_APERTURE_STATE_ON:
-			/* Trace (or cut slot in drill file) */
-			switch (apert->type) {
-			case GERBV_APTYPE_CIRCLE:
-				write_line(fd, net, apert->parameter[0],
-						dx_p, dy_m, "clearline");
-				break;
-			default:
-				GERB_COMPILE_WARNING(
-						"%s:%d: aperture type %d is "
-						"not yet supported",
-						__func__, __LINE__,
-						apert->type);
-				break;
-			}
-			break;
-		default:
-			GERB_COMPILE_WARNING(
-					"%s:%d: aperture state %d type %d is "
-					"not yet supported",
-					__func__, __LINE__,
-					net->aperture_state, apert->type);
-			break;
-		}
-	}
-
-	fputs(")\n", fd);	/* End of Layer 1 */
-
-	/* Necessary layer */
-	fputs("Layer(7 \"outline\")\n(\n)\n", fd);
-
-	gerbv_destroy_image (img);
-	fclose(fd);
-
-	setlocale(LC_NUMERIC, "");	/* Return to the default locale */
-
-	return TRUE;
+gerbv_export_geda_pcb_file_from_image(
+    const gchar* file_name, gerbv_image_t* input_img, gerbv_user_transformation_t* trans
+) {
+    gerbv_aperture_t* apert;
+    gerbv_image_t*    img;
+    gerbv_net_t*      net;
+    double            dx_p, dy_m;
+    double            thick, len;
+    FILE*             fd;
+
+    if ((fd = g_fopen(file_name, "w")) == NULL) {
+        GERB_MESSAGE(_("Can't open file for writing: %s"), file_name);
+        return FALSE;
+    }
+
+    /* Output decimals as dots for all locales */
+    setlocale(LC_NUMERIC, "C");
+
+    /* Duplicate the image, cleaning it in the process */
+    img = gerbv_image_duplicate_image(input_img, trans);
+
+    /* Header */
+    fputs("# Generated with gerbv\n\n", fd);
+    fputs("FileVersion[20091103]\n", fd);
+
+    dx_p = (img->info->max_x - img->info->min_x) - img->info->min_x;
+    dy_m = 2 * (img->info->max_y - img->info->min_y) + img->info->min_y;
+
+    /* Make board size is 3 times more than Gerber size */
+    fprintf(
+        fd, "PCB[\"%s\" %.2fmil %.2fmil]\n", img->info->name, 3 * COORD2MILS(img->info->max_x - img->info->min_x),
+        3 * COORD2MILS(img->info->max_y - img->info->min_y)
+    );
+
+    fputs("Grid[1000.000000 0.0000 0.0000 0]\n", fd);
+
+    /* Write all apertures as elements with single pad, before layer
+     * definition */
+    for (net = img->netlist; net != NULL; net = net->next) {
+        apert = img->aperture[net->aperture];
+        if (!apert)
+            continue;
+
+        /* Skip polygon, it will be written in layer section */
+        if (net->interpolation == GERBV_INTERPOLATION_PAREA_START) {
+            /* Skip to the end for polygon */
+            do {
+                net = net->next;
+            } while (net != NULL && net->interpolation != GERBV_INTERPOLATION_PAREA_END);
+            continue;
+        }
+
+        switch (net->aperture_state) {
+            case GERBV_APERTURE_STATE_FLASH:
+                switch (apert->type) {
+                    case GERBV_APTYPE_CIRCLE:
+                        /* Set start to stop coords for Circle flash */
+                        net->start_x = net->stop_x;
+                        net->start_y = net->stop_y;
+                        write_element_with_pad(fd, net, apert->parameter[0], dx_p, dy_m, "");
+                        break;
+                    case GERBV_APTYPE_OVAL:
+                    case GERBV_APTYPE_RECTANGLE:
+
+                        if (apert->parameter[0] > apert->parameter[1]) {
+                            /* Horizontal */
+                            len   = apert->parameter[0];
+                            thick = apert->parameter[1];
+
+                            net->start_x = net->stop_x - len / 2 + thick / 2;
+                            net->stop_x += len / 2 - thick / 2;
+                            net->start_y = net->stop_y;
+                        } else {
+                            /* Vertical */
+                            len   = apert->parameter[1];
+                            thick = apert->parameter[0];
+
+                            net->start_x = net->stop_x;
+                            net->start_y = net->stop_y - len / 2 + thick / 2;
+                            net->stop_y += len / 2 - thick / 2;
+                        }
+
+                        write_element_with_pad(
+                            fd, net, thick, dx_p, dy_m, (apert->type == GERBV_APTYPE_RECTANGLE) ? "square" : ""
+                        );
+                        break;
+                    default:
+                        /* TODO */
+                        GERB_COMPILE_WARNING(
+                            "%s:%d: aperture type %d is "
+                            "not yet supported",
+                            __func__, __LINE__, apert->type
+                        );
+                        break;
+                }
+                break;
+            case GERBV_APERTURE_STATE_ON:
+                /* Will be done in layer section */
+                break;
+            default:
+                /* TODO */
+                GERB_COMPILE_WARNING(
+                    "%s:%d: aperture type %d is "
+                    "not yet supported",
+                    __func__, __LINE__, apert->type
+                );
+                break;
+        }
+    }
+
+    /* Write all lines in layer definition */
+    fputs("Layer(1 \"top\")\n(\n", fd);
+
+    for (net = img->netlist; net != NULL; net = net->next) {
+        apert = img->aperture[net->aperture];
+        if (!apert)
+            continue;
+
+        if (net->interpolation == GERBV_INTERPOLATION_PAREA_START) {
+            write_polygon(fd, net, dx_p, dy_m, "clearpoly");
+
+            /* Skip to the end for polygon */
+            do {
+                net = net->next;
+            } while (net != NULL && net->interpolation != GERBV_INTERPOLATION_PAREA_END);
+            continue;
+        }
+
+        switch (net->aperture_state) {
+            case GERBV_APERTURE_STATE_FLASH:
+                /* Already done in elements section */
+                break;
+
+            case GERBV_APERTURE_STATE_ON:
+                /* Trace (or cut slot in drill file) */
+                switch (apert->type) {
+                    case GERBV_APTYPE_CIRCLE: write_line(fd, net, apert->parameter[0], dx_p, dy_m, "clearline"); break;
+                    default:
+                        GERB_COMPILE_WARNING(
+                            "%s:%d: aperture type %d is "
+                            "not yet supported",
+                            __func__, __LINE__, apert->type
+                        );
+                        break;
+                }
+                break;
+            default:
+                GERB_COMPILE_WARNING(
+                    "%s:%d: aperture state %d type %d is "
+                    "not yet supported",
+                    __func__, __LINE__, net->aperture_state, apert->type
+                );
+                break;
+        }
+    }
+
+    fputs(")\n", fd); /* End of Layer 1 */
+
+    /* Necessary layer */
+    fputs("Layer(7 \"outline\")\n(\n)\n", fd);
+
+    gerbv_destroy_image(img);
+    fclose(fd);
+
+    setlocale(LC_NUMERIC, ""); /* Return to the default locale */
+
+    return TRUE;
 }
diff --git a/src/export-image.c b/src/export-image.c
index b5b502a..11107e5 100644
--- a/src/export-image.c
+++ b/src/export-image.c
@@ -4,7 +4,7 @@
  *
  *   Copyright (C) 2000-2002 Stefan Petersen (spe@stacken.kth.se)
  *
- * Contributed by Dino Ghilardi <dino.ghilardi@ieee.org> 
+ * Contributed by Dino Ghilardi <dino.ghilardi@ieee.org>
  *
  * $Id$
  *
@@ -43,89 +43,102 @@
 #include <cairo-ps.h>
 #include <cairo-svg.h>
 
-void exportimage_render_to_surface_and_destroy (gerbv_project_t *gerbvProject,
-		cairo_surface_t *cSurface, gerbv_render_info_t *renderInfo, gchar const* filename) {
-      cairo_t *cairoTarget = cairo_create (cSurface);
-      
-      gerbv_render_all_layers_to_cairo_target_for_vector_output (gerbvProject, cairoTarget, renderInfo);
-	cairo_destroy (cairoTarget);
-	cairo_surface_destroy (cSurface);
+void
+exportimage_render_to_surface_and_destroy(
+    gerbv_project_t* gerbvProject, cairo_surface_t* cSurface, gerbv_render_info_t* renderInfo, const gchar* filename
+) {
+    cairo_t* cairoTarget = cairo_create(cSurface);
+
+    gerbv_render_all_layers_to_cairo_target_for_vector_output(gerbvProject, cairoTarget, renderInfo);
+    cairo_destroy(cairoTarget);
+    cairo_surface_destroy(cSurface);
 }
 
-gerbv_render_info_t gerbv_export_autoscale_project (gerbv_project_t *gerbvProject) {
-	gerbv_render_size_t bb;
-	gerbv_render_get_boundingbox(gerbvProject, &bb);
-	// add a border around the bounding box
-	gfloat tempWidth = bb.right  - bb.left;
-	gfloat tempHeight = bb.bottom - bb.top;
-	bb.right += (tempWidth*0.05);
-	bb.left -= (tempWidth*0.05);
-	bb.bottom += (tempHeight*0.05);
-	bb.top -= (tempHeight*0.05);
-	float width  = bb.right  - bb.left + 0.001;	// Plus a little extra to prevent from 
-	float height = bb.bottom - bb.top + 0.001; // missing items due to round-off errors
-
-	gerbv_render_info_t renderInfo = {72, 72, bb.left, bb.top,
-		GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY, width*72, height*72};
-	return renderInfo;
+gerbv_render_info_t
+gerbv_export_autoscale_project(gerbv_project_t* gerbvProject) {
+    gerbv_render_size_t bb;
+    gerbv_render_get_boundingbox(gerbvProject, &bb);
+    // add a border around the bounding box
+    gfloat tempWidth  = bb.right - bb.left;
+    gfloat tempHeight = bb.bottom - bb.top;
+    bb.right += (tempWidth * 0.05);
+    bb.left -= (tempWidth * 0.05);
+    bb.bottom += (tempHeight * 0.05);
+    bb.top -= (tempHeight * 0.05);
+    float width  = bb.right - bb.left + 0.001;  // Plus a little extra to prevent from
+    float height = bb.bottom - bb.top + 0.001;  // missing items due to round-off errors
+
+    gerbv_render_info_t renderInfo = { 72,         72,         bb.left, bb.top, GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY,
+                                       width * 72, height * 72 };
+    return renderInfo;
 }
 
-void gerbv_export_png_file_from_project_autoscaled (gerbv_project_t *gerbvProject, int widthInPixels,
-		int heightInPixels, gchar const* filename) {
-	gerbv_render_info_t renderInfo = {1, 1, 0, 0,
-		GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY,
-		widthInPixels, heightInPixels};
+void
+gerbv_export_png_file_from_project_autoscaled(
+    gerbv_project_t* gerbvProject, int widthInPixels, int heightInPixels, const gchar* filename
+) {
+    gerbv_render_info_t renderInfo = {
+        1, 1, 0, 0, GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY, widthInPixels, heightInPixels
+    };
 
-	gerbv_render_zoom_to_fit_display (gerbvProject, &renderInfo);
-	gerbv_export_png_file_from_project (gerbvProject, &renderInfo, filename);
+    gerbv_render_zoom_to_fit_display(gerbvProject, &renderInfo);
+    gerbv_export_png_file_from_project(gerbvProject, &renderInfo, filename);
 }
 
-void gerbv_export_png_file_from_project (gerbv_project_t *gerbvProject, gerbv_render_info_t *renderInfo, gchar const* filename) {
-	cairo_surface_t *cSurface = cairo_image_surface_create  (CAIRO_FORMAT_ARGB32,
-                                                         renderInfo->displayWidth, renderInfo->displayHeight);
-	cairo_t *cairoTarget = cairo_create (cSurface);
-	gerbv_render_all_layers_to_cairo_target (gerbvProject, cairoTarget, renderInfo);
-	if (CAIRO_STATUS_SUCCESS != cairo_surface_write_to_png (cSurface, filename)) {
-		GERB_COMPILE_ERROR (_("Exporting error to file \"%s\""), filename);
-	}
-	cairo_destroy (cairoTarget);
-	cairo_surface_destroy (cSurface);
+void
+gerbv_export_png_file_from_project(
+    gerbv_project_t* gerbvProject, gerbv_render_info_t* renderInfo, const gchar* filename
+) {
+    cairo_surface_t* cSurface =
+        cairo_image_surface_create(CAIRO_FORMAT_ARGB32, renderInfo->displayWidth, renderInfo->displayHeight);
+    cairo_t* cairoTarget = cairo_create(cSurface);
+    gerbv_render_all_layers_to_cairo_target(gerbvProject, cairoTarget, renderInfo);
+    if (CAIRO_STATUS_SUCCESS != cairo_surface_write_to_png(cSurface, filename)) {
+        GERB_COMPILE_ERROR(_("Exporting error to file \"%s\""), filename);
+    }
+    cairo_destroy(cairoTarget);
+    cairo_surface_destroy(cSurface);
 }
 
-void gerbv_export_pdf_file_from_project_autoscaled (gerbv_project_t *gerbvProject, gchar const* filename) {
-	gerbv_render_info_t renderInfo = gerbv_export_autoscale_project(gerbvProject);
-	gerbv_export_pdf_file_from_project (gerbvProject, &renderInfo, filename);
+void
+gerbv_export_pdf_file_from_project_autoscaled(gerbv_project_t* gerbvProject, const gchar* filename) {
+    gerbv_render_info_t renderInfo = gerbv_export_autoscale_project(gerbvProject);
+    gerbv_export_pdf_file_from_project(gerbvProject, &renderInfo, filename);
 }
 
-void gerbv_export_pdf_file_from_project (gerbv_project_t *gerbvProject, gerbv_render_info_t *renderInfo,
-		gchar const* filename) {
-	cairo_surface_t *cSurface = cairo_pdf_surface_create (filename, renderInfo->displayWidth,
-								renderInfo->displayHeight);
+void
+gerbv_export_pdf_file_from_project(
+    gerbv_project_t* gerbvProject, gerbv_render_info_t* renderInfo, const gchar* filename
+) {
+    cairo_surface_t* cSurface = cairo_pdf_surface_create(filename, renderInfo->displayWidth, renderInfo->displayHeight);
 
-      exportimage_render_to_surface_and_destroy (gerbvProject, cSurface, renderInfo, filename);
+    exportimage_render_to_surface_and_destroy(gerbvProject, cSurface, renderInfo, filename);
 }
 
-void gerbv_export_postscript_file_from_project_autoscaled (gerbv_project_t *gerbvProject, gchar const* filename) {
-	gerbv_render_info_t renderInfo = gerbv_export_autoscale_project(gerbvProject);
-	gerbv_export_postscript_file_from_project (gerbvProject, &renderInfo, filename);
+void
+gerbv_export_postscript_file_from_project_autoscaled(gerbv_project_t* gerbvProject, const gchar* filename) {
+    gerbv_render_info_t renderInfo = gerbv_export_autoscale_project(gerbvProject);
+    gerbv_export_postscript_file_from_project(gerbvProject, &renderInfo, filename);
 }
 
-void gerbv_export_postscript_file_from_project (gerbv_project_t *gerbvProject, gerbv_render_info_t *renderInfo,
-		gchar const* filename) {
-	cairo_surface_t *cSurface = cairo_ps_surface_create (filename, renderInfo->displayWidth,
-								renderInfo->displayHeight);
-      exportimage_render_to_surface_and_destroy (gerbvProject, cSurface, renderInfo, filename);
+void
+gerbv_export_postscript_file_from_project(
+    gerbv_project_t* gerbvProject, gerbv_render_info_t* renderInfo, const gchar* filename
+) {
+    cairo_surface_t* cSurface = cairo_ps_surface_create(filename, renderInfo->displayWidth, renderInfo->displayHeight);
+    exportimage_render_to_surface_and_destroy(gerbvProject, cSurface, renderInfo, filename);
 }
 
-void gerbv_export_svg_file_from_project_autoscaled (gerbv_project_t *gerbvProject, gchar const* filename) {
-	gerbv_render_info_t renderInfo = gerbv_export_autoscale_project(gerbvProject);
-	gerbv_export_svg_file_from_project (gerbvProject, &renderInfo, filename);
+void
+gerbv_export_svg_file_from_project_autoscaled(gerbv_project_t* gerbvProject, const gchar* filename) {
+    gerbv_render_info_t renderInfo = gerbv_export_autoscale_project(gerbvProject);
+    gerbv_export_svg_file_from_project(gerbvProject, &renderInfo, filename);
 }
 
-void gerbv_export_svg_file_from_project (gerbv_project_t *gerbvProject, gerbv_render_info_t *renderInfo,
-		gchar const* filename) {
-	cairo_surface_t *cSurface = cairo_svg_surface_create (filename, renderInfo->displayWidth,
-								renderInfo->displayHeight);
-      exportimage_render_to_surface_and_destroy (gerbvProject, cSurface, renderInfo, filename);
+void
+gerbv_export_svg_file_from_project(
+    gerbv_project_t* gerbvProject, gerbv_render_info_t* renderInfo, const gchar* filename
+) {
+    cairo_surface_t* cSurface = cairo_svg_surface_create(filename, renderInfo->displayWidth, renderInfo->displayHeight);
+    exportimage_render_to_surface_and_destroy(gerbvProject, cSurface, renderInfo, filename);
 }
-
diff --git a/src/export-isel-drill.c b/src/export-isel-drill.c
index 3575748..989ae8c 100644
--- a/src/export-isel-drill.c
+++ b/src/export-isel-drill.c
@@ -39,126 +39,125 @@
 #include "common.h"
 
 /* DEBUG printing.  #define DEBUG 1 in config.h to use this fcn. */
-#define dprintf if(DEBUG) printf
-#define round(x) floor(x+0.5)
+#define dprintf \
+    if (DEBUG)  \
+    printf
+#define round(x) floor(x + 0.5)
 
 gboolean
-gerbv_export_isel_drill_file_from_image (const gchar *filename, gerbv_image_t *inputImage,
-		gerbv_user_transformation_t *transform) {
-	FILE *fd;
-	GArray *apertureTable = g_array_new(FALSE,FALSE,sizeof(int));
-	gerbv_net_t *currentNet;
-
-	/* force gerbv to output decimals as dots (not commas for other locales) */
-	setlocale(LC_NUMERIC, "C");
-
-	if ((fd = g_fopen(filename, "w")) == NULL) {
-		GERB_COMPILE_ERROR(_("Can't open file for writing: %s"),
-				filename);
-
-		return FALSE;
-	}
-
-	/* duplicate the image, cleaning it in the process */
-	gerbv_image_t *image = gerbv_image_duplicate_image (inputImage, transform);
-
-	/* write header info */
-	fprintf(fd,
-		"IMF_PBL_V1.0\r\n"
-		"\r\n"
-		"; Please change this parameters to your needs\r\n"
-		"; Don't forget to change the drill depth to\r\n"
-		"; your PCB thickness\r\n"
-		"\r\n"
-		"; The normal movement velocity in 1/1000 mm/s\r\n"
-		"VEL 5000\r\n"
-		"\r\n"
-		"; The fast movement velocity in 1/1000 mm/s\r\n"
-		"FASTVEL 10000\r\n"
-		"; The safety height in mm over the PCB for movement\r\n"
-		"\r\n"
-		"DRILLDEF S2000\r\n"
-		"\r\n"
-		"; Drill velocity of downwards movement in 1/1000 mm/s\r\n"
-		"\r\n"
-		"DRILLDEF V1000\r\n"
-		"\r\n"
-		"; The drill depth in 1/1000 mm\r\n"
-		"\r\n"
-		"DRILLDEF D1800 ; 1.5mm material + 0.3mm break through\r\n"
-		"\r\n"
-		"; DO NOT CHANGE THESE PARAMETERS!!\r\n"
-		"\r\n"
-		"DRILLDEF C1 P0\r\n"
-		"\r\n");
-
-	/* define all apertures */
-	gerbv_aperture_t *currentAperture;
-
-	/* the image should already have been cleaned by a duplicate_image call, so we can safely
-	   assume the aperture range is correct */
-	for (int i=APERTURE_MIN; i<APERTURE_MAX; i++) {
-		currentAperture = image->aperture[i];
-
-		if (!currentAperture)
-			continue;
-
-		switch (currentAperture->type) {
-		case GERBV_APTYPE_CIRCLE:
-			/* add the "approved" aperture to our valid list */
-			fprintf(fd, "; TOOL %d - Diameter %1.3f mm\r\n",
-				i + 1,
-				COORD2MMS(currentAperture->parameter[0]));
-			g_array_append_val (apertureTable, i);
-
-			break;
-		default:
-			break;
-		}
-	}
-
-	/* write rest of image */
-
-	for (guint i=0; i<apertureTable->len; i++) {
-		int currentAperture=g_array_index (apertureTable, int, i);
-
-		/* write tool change */
-		fprintf(fd, "GETTOOL %d\r\n",currentAperture+1);
-
-		/* run through all nets and look for drills using this aperture */
-		for (currentNet = image->netlist; currentNet;
-				currentNet = currentNet->next) {
-
-			if (currentNet->aperture != currentAperture)
-				continue;
-
-			switch (currentNet->aperture_state) {
-			case GERBV_APERTURE_STATE_FLASH: {
-				long xVal,yVal;
-
-				xVal = (long) round(COORD2MMS(currentNet->stop_x)*1e3);
-				yVal = (long) round(COORD2MMS(currentNet->stop_y)*1e3);
-				fprintf(fd, "DRILL X%06ld Y%06ld\r\n",
-						xVal, yVal);
-				break;
-			}
-			default:
-				GERB_COMPILE_WARNING(
-					_("Skipped to export of unsupported state %d "
-					"interpolation \"%s\""),
-					currentNet->aperture_state,
-					gerbv_interpolation_name(
-						currentNet->interpolation));
-			}
-		}
-	}
-	g_array_free (apertureTable, TRUE);
-	/* write footer */
-	fprintf(fd, "PROGEND\r\n");
-	gerbv_destroy_image (image);
-	fclose(fd);
-
-	/* return to the default locale */
-	setlocale(LC_NUMERIC, "");
-	return TRUE;
+gerbv_export_isel_drill_file_from_image(
+    const gchar* filename, gerbv_image_t* inputImage, gerbv_user_transformation_t* transform
+) {
+    FILE*        fd;
+    GArray*      apertureTable = g_array_new(FALSE, FALSE, sizeof(int));
+    gerbv_net_t* currentNet;
+
+    /* force gerbv to output decimals as dots (not commas for other locales) */
+    setlocale(LC_NUMERIC, "C");
+
+    if ((fd = g_fopen(filename, "w")) == NULL) {
+        GERB_COMPILE_ERROR(_("Can't open file for writing: %s"), filename);
+
+        return FALSE;
+    }
+
+    /* duplicate the image, cleaning it in the process */
+    gerbv_image_t* image = gerbv_image_duplicate_image(inputImage, transform);
+
+    /* write header info */
+    fprintf(
+        fd,
+        "IMF_PBL_V1.0\r\n"
+        "\r\n"
+        "; Please change this parameters to your needs\r\n"
+        "; Don't forget to change the drill depth to\r\n"
+        "; your PCB thickness\r\n"
+        "\r\n"
+        "; The normal movement velocity in 1/1000 mm/s\r\n"
+        "VEL 5000\r\n"
+        "\r\n"
+        "; The fast movement velocity in 1/1000 mm/s\r\n"
+        "FASTVEL 10000\r\n"
+        "; The safety height in mm over the PCB for movement\r\n"
+        "\r\n"
+        "DRILLDEF S2000\r\n"
+        "\r\n"
+        "; Drill velocity of downwards movement in 1/1000 mm/s\r\n"
+        "\r\n"
+        "DRILLDEF V1000\r\n"
+        "\r\n"
+        "; The drill depth in 1/1000 mm\r\n"
+        "\r\n"
+        "DRILLDEF D1800 ; 1.5mm material + 0.3mm break through\r\n"
+        "\r\n"
+        "; DO NOT CHANGE THESE PARAMETERS!!\r\n"
+        "\r\n"
+        "DRILLDEF C1 P0\r\n"
+        "\r\n"
+    );
+
+    /* define all apertures */
+    gerbv_aperture_t* currentAperture;
+
+    /* the image should already have been cleaned by a duplicate_image call, so we can safely
+       assume the aperture range is correct */
+    for (int i = APERTURE_MIN; i < APERTURE_MAX; i++) {
+        currentAperture = image->aperture[i];
+
+        if (!currentAperture)
+            continue;
+
+        switch (currentAperture->type) {
+            case GERBV_APTYPE_CIRCLE:
+                /* add the "approved" aperture to our valid list */
+                fprintf(fd, "; TOOL %d - Diameter %1.3f mm\r\n", i + 1, COORD2MMS(currentAperture->parameter[0]));
+                g_array_append_val(apertureTable, i);
+
+                break;
+            default: break;
+        }
+    }
+
+    /* write rest of image */
+
+    for (guint i = 0; i < apertureTable->len; i++) {
+        int currentAperture = g_array_index(apertureTable, int, i);
+
+        /* write tool change */
+        fprintf(fd, "GETTOOL %d\r\n", currentAperture + 1);
+
+        /* run through all nets and look for drills using this aperture */
+        for (currentNet = image->netlist; currentNet; currentNet = currentNet->next) {
+
+            if (currentNet->aperture != currentAperture)
+                continue;
+
+            switch (currentNet->aperture_state) {
+                case GERBV_APERTURE_STATE_FLASH:
+                    {
+                        long xVal, yVal;
+
+                        xVal = (long)round(COORD2MMS(currentNet->stop_x) * 1e3);
+                        yVal = (long)round(COORD2MMS(currentNet->stop_y) * 1e3);
+                        fprintf(fd, "DRILL X%06ld Y%06ld\r\n", xVal, yVal);
+                        break;
+                    }
+                default:
+                    GERB_COMPILE_WARNING(
+                        _("Skipped to export of unsupported state %d "
+                          "interpolation \"%s\""),
+                        currentNet->aperture_state, gerbv_interpolation_name(currentNet->interpolation)
+                    );
+            }
+        }
+    }
+    g_array_free(apertureTable, TRUE);
+    /* write footer */
+    fprintf(fd, "PROGEND\r\n");
+    gerbv_destroy_image(image);
+    fclose(fd);
+
+    /* return to the default locale */
+    setlocale(LC_NUMERIC, "");
+    return TRUE;
 }
diff --git a/src/export-rs274x.c b/src/export-rs274x.c
index 6fb134e..c3d86b8 100644
--- a/src/export-rs274x.c
+++ b/src/export-rs274x.c
@@ -26,7 +26,6 @@
     \ingroup libgerbv
 */
 
-
 #include "gerbv.h"
 
 #include <math.h>
@@ -34,359 +33,350 @@
 
 #include "common.h"
 
-#define dprintf if(DEBUG) printf
+#define dprintf \
+    if (DEBUG)  \
+    printf
 
-#define round(x) floor(x+0.5)
+#define round(x) floor(x + 0.5)
 
 void
-export_rs274x_write_macro (FILE *fd, gerbv_aperture_t *currentAperture,
-			gint apertureNumber) {
-	gerbv_simplified_amacro_t *ls = currentAperture->simplified;
-
-	/* write the macro portion first */
-	fprintf(fd, "%%AMMACRO%d*\n",apertureNumber);
-	while (ls != NULL) {
-		if (ls->type == GERBV_APTYPE_MACRO_CIRCLE) {
-			fprintf(fd, "1,%d,%f,%f,%f*\n",(int) ls->parameter[CIRCLE_EXPOSURE],
-				ls->parameter[CIRCLE_DIAMETER],ls->parameter[CIRCLE_CENTER_X],
-				ls->parameter[CIRCLE_CENTER_Y]);
-		}
-		else if (ls->type == GERBV_APTYPE_MACRO_OUTLINE) {
-			int pointCounter;
-			int numberOfPoints = (int) ls->parameter[OUTLINE_NUMBER_OF_POINTS];
-			
-			/* for Flatcam no new line after this 3 digits */
-			fprintf(fd, "4,%d,%d,",(int) ls->parameter[OUTLINE_EXPOSURE],
-				numberOfPoints);
-			/* add 1 point for the starting point here */
-			for (pointCounter=0; pointCounter <= numberOfPoints; pointCounter++) {
-			    fprintf(fd, "%f,%f,",ls->parameter[pointCounter * 2 + OUTLINE_FIRST_X],
-					   ls->parameter[pointCounter * 2 + OUTLINE_FIRST_Y]);
-			}
-			fprintf(fd, "%f*\n",ls->parameter[pointCounter * 2 + OUTLINE_FIRST_X]);
-		}
-		else if (ls->type == GERBV_APTYPE_MACRO_POLYGON) {
-			fprintf(fd, "5,%d,%d,%f,%f,%f,%f*\n",(int) ls->parameter[POLYGON_EXPOSURE],
-				(int) ls->parameter[POLYGON_NUMBER_OF_POINTS],
-				ls->parameter[POLYGON_CENTER_X],ls->parameter[POLYGON_CENTER_Y],
-				ls->parameter[POLYGON_DIAMETER],ls->parameter[POLYGON_ROTATION]);
-		}
-		else if (ls->type == GERBV_APTYPE_MACRO_MOIRE) {
-			fprintf(fd, "6,%f,%f,%f,%f,%f,%d,%f,%f,%f*\n",ls->parameter[MOIRE_CENTER_X],
-				ls->parameter[MOIRE_CENTER_Y],ls->parameter[MOIRE_OUTSIDE_DIAMETER],
-				ls->parameter[MOIRE_CIRCLE_THICKNESS],ls->parameter[MOIRE_GAP_WIDTH],
-				(int) ls->parameter[MOIRE_NUMBER_OF_CIRCLES],ls->parameter[MOIRE_CROSSHAIR_THICKNESS],
-				ls->parameter[MOIRE_CROSSHAIR_LENGTH],ls->parameter[MOIRE_ROTATION]);
-		}
-		else if (ls->type == GERBV_APTYPE_MACRO_THERMAL) {
-			fprintf(fd, "7,%f,%f,%f,%f,%f,%f*\n",ls->parameter[THERMAL_CENTER_X],
-				ls->parameter[THERMAL_CENTER_Y],ls->parameter[THERMAL_OUTSIDE_DIAMETER],
-				ls->parameter[THERMAL_INSIDE_DIAMETER],ls->parameter[THERMAL_CROSSHAIR_THICKNESS],
-				ls->parameter[THERMAL_ROTATION]);
-		}
-		else if (ls->type == GERBV_APTYPE_MACRO_LINE20) {
-			fprintf(fd, "20,%d,%f,%f,%f,%f,%f,%f*\n",(int) ls->parameter[LINE20_EXPOSURE],
-				ls->parameter[LINE20_LINE_WIDTH],ls->parameter[LINE20_START_X],
-				ls->parameter[LINE20_START_Y],ls->parameter[LINE20_END_X],
-				ls->parameter[LINE20_END_Y],ls->parameter[LINE20_ROTATION]);
-		}
-		else if (ls->type == GERBV_APTYPE_MACRO_LINE21) {
-			fprintf(fd, "21,%d,%f,%f,%f,%f,%f*\n",(int) ls->parameter[LINE21_EXPOSURE],
-				ls->parameter[LINE21_WIDTH],ls->parameter[LINE21_HEIGHT],
-				ls->parameter[LINE21_CENTER_X],ls->parameter[LINE21_CENTER_Y],
-				ls->parameter[LINE21_ROTATION]);
-		}
-		else if (ls->type == GERBV_APTYPE_MACRO_LINE22) {
-			fprintf(fd, "22,%d,%f,%f,%f,%f,%f*\n",(int) ls->parameter[LINE22_EXPOSURE],
-				ls->parameter[LINE22_WIDTH],ls->parameter[LINE22_HEIGHT],
-				ls->parameter[LINE22_LOWER_LEFT_X],ls->parameter[LINE22_LOWER_LEFT_Y],
-				ls->parameter[LINE22_ROTATION]);
-		}
-		ls = ls->next;
-	}
-	fprintf(fd, "%%\n");
-	/* and finally create an aperture definition to use the macro */
-	fprintf(fd, "%%ADD%dMACRO%d*%%\n",apertureNumber,apertureNumber);
+export_rs274x_write_macro(FILE* fd, gerbv_aperture_t* currentAperture, gint apertureNumber) {
+    gerbv_simplified_amacro_t* ls = currentAperture->simplified;
+
+    /* write the macro portion first */
+    fprintf(fd, "%%AMMACRO%d*\n", apertureNumber);
+    while (ls != NULL) {
+        if (ls->type == GERBV_APTYPE_MACRO_CIRCLE) {
+            fprintf(
+                fd, "1,%d,%f,%f,%f*\n", (int)ls->parameter[CIRCLE_EXPOSURE], ls->parameter[CIRCLE_DIAMETER],
+                ls->parameter[CIRCLE_CENTER_X], ls->parameter[CIRCLE_CENTER_Y]
+            );
+        } else if (ls->type == GERBV_APTYPE_MACRO_OUTLINE) {
+            int pointCounter;
+            int numberOfPoints = (int)ls->parameter[OUTLINE_NUMBER_OF_POINTS];
+
+            /* for Flatcam no new line after this 3 digits */
+            fprintf(fd, "4,%d,%d,", (int)ls->parameter[OUTLINE_EXPOSURE], numberOfPoints);
+            /* add 1 point for the starting point here */
+            for (pointCounter = 0; pointCounter <= numberOfPoints; pointCounter++) {
+                fprintf(
+                    fd, "%f,%f,", ls->parameter[pointCounter * 2 + OUTLINE_FIRST_X],
+                    ls->parameter[pointCounter * 2 + OUTLINE_FIRST_Y]
+                );
+            }
+            fprintf(fd, "%f*\n", ls->parameter[pointCounter * 2 + OUTLINE_FIRST_X]);
+        } else if (ls->type == GERBV_APTYPE_MACRO_POLYGON) {
+            fprintf(
+                fd, "5,%d,%d,%f,%f,%f,%f*\n", (int)ls->parameter[POLYGON_EXPOSURE],
+                (int)ls->parameter[POLYGON_NUMBER_OF_POINTS], ls->parameter[POLYGON_CENTER_X],
+                ls->parameter[POLYGON_CENTER_Y], ls->parameter[POLYGON_DIAMETER], ls->parameter[POLYGON_ROTATION]
+            );
+        } else if (ls->type == GERBV_APTYPE_MACRO_MOIRE) {
+            fprintf(
+                fd, "6,%f,%f,%f,%f,%f,%d,%f,%f,%f*\n", ls->parameter[MOIRE_CENTER_X], ls->parameter[MOIRE_CENTER_Y],
+                ls->parameter[MOIRE_OUTSIDE_DIAMETER], ls->parameter[MOIRE_CIRCLE_THICKNESS],
+                ls->parameter[MOIRE_GAP_WIDTH], (int)ls->parameter[MOIRE_NUMBER_OF_CIRCLES],
+                ls->parameter[MOIRE_CROSSHAIR_THICKNESS], ls->parameter[MOIRE_CROSSHAIR_LENGTH],
+                ls->parameter[MOIRE_ROTATION]
+            );
+        } else if (ls->type == GERBV_APTYPE_MACRO_THERMAL) {
+            fprintf(
+                fd, "7,%f,%f,%f,%f,%f,%f*\n", ls->parameter[THERMAL_CENTER_X], ls->parameter[THERMAL_CENTER_Y],
+                ls->parameter[THERMAL_OUTSIDE_DIAMETER], ls->parameter[THERMAL_INSIDE_DIAMETER],
+                ls->parameter[THERMAL_CROSSHAIR_THICKNESS], ls->parameter[THERMAL_ROTATION]
+            );
+        } else if (ls->type == GERBV_APTYPE_MACRO_LINE20) {
+            fprintf(
+                fd, "20,%d,%f,%f,%f,%f,%f,%f*\n", (int)ls->parameter[LINE20_EXPOSURE], ls->parameter[LINE20_LINE_WIDTH],
+                ls->parameter[LINE20_START_X], ls->parameter[LINE20_START_Y], ls->parameter[LINE20_END_X],
+                ls->parameter[LINE20_END_Y], ls->parameter[LINE20_ROTATION]
+            );
+        } else if (ls->type == GERBV_APTYPE_MACRO_LINE21) {
+            fprintf(
+                fd, "21,%d,%f,%f,%f,%f,%f*\n", (int)ls->parameter[LINE21_EXPOSURE], ls->parameter[LINE21_WIDTH],
+                ls->parameter[LINE21_HEIGHT], ls->parameter[LINE21_CENTER_X], ls->parameter[LINE21_CENTER_Y],
+                ls->parameter[LINE21_ROTATION]
+            );
+        } else if (ls->type == GERBV_APTYPE_MACRO_LINE22) {
+            fprintf(
+                fd, "22,%d,%f,%f,%f,%f,%f*\n", (int)ls->parameter[LINE22_EXPOSURE], ls->parameter[LINE22_WIDTH],
+                ls->parameter[LINE22_HEIGHT], ls->parameter[LINE22_LOWER_LEFT_X], ls->parameter[LINE22_LOWER_LEFT_Y],
+                ls->parameter[LINE22_ROTATION]
+            );
+        }
+        ls = ls->next;
+    }
+    fprintf(fd, "%%\n");
+    /* and finally create an aperture definition to use the macro */
+    fprintf(fd, "%%ADD%dMACRO%d*%%\n", apertureNumber, apertureNumber);
 }
 
 void
-export_rs274x_write_apertures (FILE *fd, gerbv_image_t *image) {
-	gerbv_aperture_t *currentAperture;
-	gint numberOfRequiredParameters=0,numberOfOptionalParameters=0,i,j;
-	
-	/* the image should already have been cleaned by a duplicate_image call, so we can safely
-	   assume the aperture range is correct */
-	for (i=APERTURE_MIN; i<APERTURE_MAX; i++) {
-		gboolean writeAperture=TRUE;
-		
-		currentAperture = image->aperture[i];
-		
-		if (!currentAperture)
-			continue;
-		
-		switch (currentAperture->type) {
-			case GERBV_APTYPE_CIRCLE:
-				fprintf(fd, "%%ADD%d",i);
-				fprintf(fd, "C,");
-				numberOfRequiredParameters = 1;
-				numberOfOptionalParameters = 2;
-				break;
-			case GERBV_APTYPE_RECTANGLE:
-				fprintf(fd, "%%ADD%d",i);
-				fprintf(fd, "R,");
-				numberOfRequiredParameters = 2;
-				numberOfOptionalParameters = 2;
-				break;
-			case GERBV_APTYPE_OVAL:
-				fprintf(fd, "%%ADD%d",i);
-				fprintf(fd, "O,");
-				numberOfRequiredParameters = 2;
-				numberOfOptionalParameters = 2;
-				break;
-			case GERBV_APTYPE_POLYGON:
-				fprintf(fd, "%%ADD%d",i);
-				fprintf(fd, "P,");
-				numberOfRequiredParameters = 2;
-				numberOfOptionalParameters = 3;
-				break;
-			case GERBV_APTYPE_MACRO:
-				export_rs274x_write_macro (fd, currentAperture, i);
-				writeAperture=FALSE;
-				break;
-			default:
-				writeAperture=FALSE;
-				break;
-		}
-		if (writeAperture) {
-			/* write the parameter list */
-			for (j=0; j<(numberOfRequiredParameters + numberOfOptionalParameters); j++) {
-				if ((j < numberOfRequiredParameters) || (currentAperture->parameter[j] != 0)) {
-					/* print the "X" character to separate the parameters */
-					if (j>0)
-						fprintf(fd, "X");
-					fprintf(fd, "%.4f",currentAperture->parameter[j]);
-				}
-			}
-			fprintf(fd, "*%%\n");
-		}
-	}
+export_rs274x_write_apertures(FILE* fd, gerbv_image_t* image) {
+    gerbv_aperture_t* currentAperture;
+    gint              numberOfRequiredParameters = 0, numberOfOptionalParameters = 0, i, j;
+
+    /* the image should already have been cleaned by a duplicate_image call, so we can safely
+       assume the aperture range is correct */
+    for (i = APERTURE_MIN; i < APERTURE_MAX; i++) {
+        gboolean writeAperture = TRUE;
+
+        currentAperture = image->aperture[i];
+
+        if (!currentAperture)
+            continue;
+
+        switch (currentAperture->type) {
+            case GERBV_APTYPE_CIRCLE:
+                fprintf(fd, "%%ADD%d", i);
+                fprintf(fd, "C,");
+                numberOfRequiredParameters = 1;
+                numberOfOptionalParameters = 2;
+                break;
+            case GERBV_APTYPE_RECTANGLE:
+                fprintf(fd, "%%ADD%d", i);
+                fprintf(fd, "R,");
+                numberOfRequiredParameters = 2;
+                numberOfOptionalParameters = 2;
+                break;
+            case GERBV_APTYPE_OVAL:
+                fprintf(fd, "%%ADD%d", i);
+                fprintf(fd, "O,");
+                numberOfRequiredParameters = 2;
+                numberOfOptionalParameters = 2;
+                break;
+            case GERBV_APTYPE_POLYGON:
+                fprintf(fd, "%%ADD%d", i);
+                fprintf(fd, "P,");
+                numberOfRequiredParameters = 2;
+                numberOfOptionalParameters = 3;
+                break;
+            case GERBV_APTYPE_MACRO:
+                export_rs274x_write_macro(fd, currentAperture, i);
+                writeAperture = FALSE;
+                break;
+            default: writeAperture = FALSE; break;
+        }
+        if (writeAperture) {
+            /* write the parameter list */
+            for (j = 0; j < (numberOfRequiredParameters + numberOfOptionalParameters); j++) {
+                if ((j < numberOfRequiredParameters) || (currentAperture->parameter[j] != 0)) {
+                    /* print the "X" character to separate the parameters */
+                    if (j > 0)
+                        fprintf(fd, "X");
+                    fprintf(fd, "%.4f", currentAperture->parameter[j]);
+                }
+            }
+            fprintf(fd, "*%%\n");
+        }
+    }
 }
 
 void
-export_rs274x_write_layer_change (gerbv_layer_t *oldLayer, gerbv_layer_t *newLayer, FILE *fd) {
-	if (oldLayer->polarity != newLayer->polarity) {
-		/* polarity changed */
-		if ((newLayer->polarity == GERBV_POLARITY_CLEAR))
-			fprintf(fd, "%%LPC*%%\n");
-		else
-			fprintf(fd, "%%LPD*%%\n");
-	}
+export_rs274x_write_layer_change(gerbv_layer_t* oldLayer, gerbv_layer_t* newLayer, FILE* fd) {
+    if (oldLayer->polarity != newLayer->polarity) {
+        /* polarity changed */
+        if ((newLayer->polarity == GERBV_POLARITY_CLEAR))
+            fprintf(fd, "%%LPC*%%\n");
+        else
+            fprintf(fd, "%%LPD*%%\n");
+    }
 }
 
 void
-export_rs274x_write_state_change (gerbv_netstate_t *oldState, gerbv_netstate_t *newState, FILE *fd) {
+export_rs274x_write_state_change(gerbv_netstate_t* oldState, gerbv_netstate_t* newState, FILE* fd) {}
 
+gboolean
+gerbv_export_rs274x_file_from_image(
+    const gchar* filename, gerbv_image_t* inputImage, gerbv_user_transformation_t* transform
+) {
+    const double                 decimal_coeff = 1e6;
+    FILE*                        fd;
+    gerbv_netstate_t*            oldState;
+    gerbv_layer_t*               oldLayer;
+    gboolean                     insidePolygon = FALSE;
+    gerbv_user_transformation_t* thisTransform;
 
-}
+    // force gerbv to output decimals as dots (not commas for other locales)
+    setlocale(LC_NUMERIC, "C");
 
-gboolean
-gerbv_export_rs274x_file_from_image (const gchar *filename, gerbv_image_t *inputImage,
-		gerbv_user_transformation_t *transform)
-{
-	const double decimal_coeff = 1e6;
-	FILE *fd;
-	gerbv_netstate_t *oldState;
-	gerbv_layer_t *oldLayer;
-	gboolean insidePolygon=FALSE;
-	gerbv_user_transformation_t *thisTransform;
-
-	// force gerbv to output decimals as dots (not commas for other locales)
-	setlocale(LC_NUMERIC, "C");
-
-	if (transform != NULL) {
-		thisTransform = transform;
-	} else {
-		static gerbv_user_transformation_t identityTransform =
-						{0,0,1,1,0,FALSE,FALSE,FALSE};
-		thisTransform = &identityTransform;
-	}
-	if ((fd = g_fopen(filename, "w")) == NULL) {
-		GERB_COMPILE_ERROR(_("Can't open file for writing: %s"),
-				filename);
-		return FALSE;
-	}
-	
-	/* duplicate the image, cleaning it in the process */
-	gerbv_image_t *image = gerbv_image_duplicate_image (inputImage, thisTransform);
-	
-	/* write header info */
-	fprintf(fd, "G04 This is an RS-274x file exported by *\n");
-	fprintf(fd, "G04 gerbv version %s *\n",VERSION);
-	fprintf(fd, "G04 More information is available about gerbv at *\n");
-	fprintf(fd, "G04 https://gerbv.github.io/ *\n");
-	fprintf(fd, "G04 --End of header info--*\n");
-	fprintf(fd, "%%MOIN*%%\n");
-	fprintf(fd, "%%FSLAX36Y36*%%\n");
-	
-	/* check the image info struct for any non-default settings */
-	/* image offset */
-	if ((image->info->offsetA > 0.0) || (image->info->offsetB > 0.0))
-		fprintf(fd, "%%IOA%fB%f*%%\n",image->info->offsetA,image->info->offsetB);
-	/* image polarity */
-	if (image->info->polarity == GERBV_POLARITY_CLEAR)
-		fprintf(fd, "%%IPNEG*%%\n");
-	else
-		fprintf(fd, "%%IPPOS*%%\n");
-	/* image name */
-	if (image->info->name)
-		fprintf(fd, "%%IN%s*%%\n",image->info->name);
-	/* plotter film */
-	if (image->info->plotterFilm)
-		fprintf(fd, "%%PF%s*%%\n",image->info->plotterFilm);
-
-	/* image rotation */
-	if ((image->info->imageRotation != 0.0)
-	     ||  (thisTransform->rotation != 0.0))
-		fprintf(fd, "%%IR%d*%%\n",
-		        (int)round(RAD2DEG(image->info->imageRotation))%360);
-
-	if ((image->info->imageJustifyTypeA != GERBV_JUSTIFY_NOJUSTIFY)
-	||  (image->info->imageJustifyTypeB != GERBV_JUSTIFY_NOJUSTIFY)) {
-		fprintf(fd, "%%IJA");
-		if (image->info->imageJustifyTypeA == GERBV_JUSTIFY_CENTERJUSTIFY)
-			fprintf(fd, "C");
-		else 
-			fprintf(fd, "%.4f",image->info->imageJustifyOffsetA);
-		fprintf(fd, "B");
-		if (image->info->imageJustifyTypeB == GERBV_JUSTIFY_CENTERJUSTIFY)
-			fprintf(fd, "C");
-		else 
-			fprintf(fd, "%.4f",image->info->imageJustifyOffsetB);
-		fprintf(fd, "*%%\n");
-
-	}
-	/* handle scale user orientation transforms */
-	if (fabs(thisTransform->scaleX - 1) > GERBV_PRECISION_LINEAR_INCH
-	||  fabs(thisTransform->scaleY - 1) > GERBV_PRECISION_LINEAR_INCH) {
-		fprintf(fd, "%%SFA%.4fB%.4f*%%\n",thisTransform->scaleX,thisTransform->scaleY);
-	}
-	/* handle mirror image user orientation transform */
-	if ((thisTransform->mirrorAroundX)||(thisTransform->mirrorAroundY)) {
-		fprintf(fd, "%%MIA%dB%d*%%\n",thisTransform->mirrorAroundY,thisTransform->mirrorAroundX);
-	}
-	
-	/* define all apertures */
-	fprintf(fd, "G04 --Define apertures--*\n");
-	export_rs274x_write_apertures (fd, image);
-	
-	/* write rest of image */
-	fprintf(fd, "G04 --Start main section--*\n");
-	gint currentAperture = 0;
-	gerbv_net_t *currentNet;
-	
-	oldLayer = image->layers;
-	oldState = image->states;
-	/* skip the first net, since it's always zero due to the way we parse things */
-	for (currentNet = image->netlist->next; currentNet; currentNet = currentNet->next){
-		/* check for "layer" changes (RS274X commands) */
-		if (currentNet->layer != oldLayer)
-			export_rs274x_write_layer_change (oldLayer, currentNet->layer, fd);
-		
-		/* check for new "netstate" (more RS274X commands) */
-		if (currentNet->state != oldState)
-			export_rs274x_write_state_change (oldState, currentNet->state, fd);
-		
-		/* check for tool changes */
-		/* also, make sure the aperture number is a valid one, since sometimes
-		   the loaded file may refer to invalid apertures */
-		if ((currentNet->aperture != currentAperture)&&
-			(image->aperture[currentNet->aperture] != NULL)) {
-			fprintf(fd, "G54D%02d*\n",currentNet->aperture);
-			currentAperture = currentNet->aperture;
-		}
-		
-		oldLayer = currentNet->layer;
-		oldState = currentNet->state;
-		
-		long xVal,yVal,endX,endY,centerX,centerY;
-		switch (currentNet->interpolation) {
-			case GERBV_INTERPOLATION_LINEARx1 :
-			case GERBV_INTERPOLATION_LINEARx10 :
-			case GERBV_INTERPOLATION_LINEARx01 :
-			case GERBV_INTERPOLATION_LINEARx001 :
-				/* see if we need to write an "aperture off" line to get
-				   the pen to the right start point */
-				if ((!insidePolygon) && (currentNet->aperture_state == GERBV_APERTURE_STATE_ON)) {
-					xVal = (long) round(currentNet->start_x * decimal_coeff);
-					yVal = (long) round(currentNet->start_y * decimal_coeff);
-					fprintf(fd, "G01X%07ldY%07ldD02*\n",xVal,yVal);
-				}
-				xVal = (long) round(currentNet->stop_x * decimal_coeff);
-				yVal = (long) round(currentNet->stop_y * decimal_coeff);
-				fprintf(fd, "G01X%07ldY%07ld",xVal,yVal);
-				/* and finally, write the esposure value */
-				if (currentNet->aperture_state == GERBV_APERTURE_STATE_OFF)
-					fprintf(fd, "D02*\n");
-				else if (currentNet->aperture_state == GERBV_APERTURE_STATE_ON)
-					fprintf(fd, "D01*\n");
-				else
-					fprintf(fd, "D03*\n");
-				break;
-			case GERBV_INTERPOLATION_CW_CIRCULAR :
-			case GERBV_INTERPOLATION_CCW_CIRCULAR :
-				/* see if we need to write an "aperture off" line to get
-				   the pen to the right start point */
-				if ((!insidePolygon) && (currentNet->aperture_state == GERBV_APERTURE_STATE_ON)) {
-					xVal = (long) round(currentNet->start_x * decimal_coeff);
-					yVal = (long) round(currentNet->start_y * decimal_coeff);
-					fprintf(fd, "G01X%07ldY%07ldD02*\n",xVal,yVal);
-				}
-				centerX= (long) round((currentNet->cirseg->cp_x - currentNet->start_x) * decimal_coeff);
-				centerY= (long) round((currentNet->cirseg->cp_y - currentNet->start_y) * decimal_coeff);
-				endX = (long) round(currentNet->stop_x * decimal_coeff);
-				endY = (long) round(currentNet->stop_y * decimal_coeff);
-				
-				/* always use multi-quadrant, since it's much easier to export */
-				/*  and most all software should support it */
-				fprintf(fd, "G75*\n");
-
-				if (currentNet->interpolation == GERBV_INTERPOLATION_CW_CIRCULAR)
-					fprintf(fd, "G02");	/* Clockwise */
-				else
-					fprintf(fd, "G03");	/* Counter clockwise */
-
-				/* don't write the I and J values if the exposure is off */
-				if (currentNet->aperture_state == GERBV_APERTURE_STATE_ON)
-					fprintf(fd, "X%07ldY%07ldI%07ldJ%07ld",endX,endY,centerX,centerY);
-				else
-					fprintf(fd, "X%07ldY%07ld",endX,endY);
-				/* and finally, write the esposure value */
-				if (currentNet->aperture_state == GERBV_APERTURE_STATE_OFF)
-					fprintf(fd, "D02*\n");
-				else if (currentNet->aperture_state == GERBV_APERTURE_STATE_ON)
-					fprintf(fd, "D01*\n");
-				else
-					fprintf(fd, "D03*\n");
-				break;
-			case GERBV_INTERPOLATION_PAREA_START:
-				fprintf(fd, "G36*\n");
-				insidePolygon = TRUE;
-				break;
-			case GERBV_INTERPOLATION_PAREA_END:
-				fprintf(fd, "G37*\n");
-				insidePolygon = FALSE;
-				break;
-			default:
-				break;
-		}
-	}
-	
-	fprintf(fd, "M02*\n");
-	
-	gerbv_destroy_image (image);
-	fclose(fd);
-	
-	// return to the default locale
-	setlocale(LC_NUMERIC, "");
-	return TRUE;
+    if (transform != NULL) {
+        thisTransform = transform;
+    } else {
+        static gerbv_user_transformation_t identityTransform = { 0, 0, 1, 1, 0, FALSE, FALSE, FALSE };
+        thisTransform                                        = &identityTransform;
+    }
+    if ((fd = g_fopen(filename, "w")) == NULL) {
+        GERB_COMPILE_ERROR(_("Can't open file for writing: %s"), filename);
+        return FALSE;
+    }
+
+    /* duplicate the image, cleaning it in the process */
+    gerbv_image_t* image = gerbv_image_duplicate_image(inputImage, thisTransform);
+
+    /* write header info */
+    fprintf(fd, "G04 This is an RS-274x file exported by *\n");
+    fprintf(fd, "G04 gerbv version %s *\n", VERSION);
+    fprintf(fd, "G04 More information is available about gerbv at *\n");
+    fprintf(fd, "G04 https://gerbv.github.io/ *\n");
+    fprintf(fd, "G04 --End of header info--*\n");
+    fprintf(fd, "%%MOIN*%%\n");
+    fprintf(fd, "%%FSLAX36Y36*%%\n");
+
+    /* check the image info struct for any non-default settings */
+    /* image offset */
+    if ((image->info->offsetA > 0.0) || (image->info->offsetB > 0.0))
+        fprintf(fd, "%%IOA%fB%f*%%\n", image->info->offsetA, image->info->offsetB);
+    /* image polarity */
+    if (image->info->polarity == GERBV_POLARITY_CLEAR)
+        fprintf(fd, "%%IPNEG*%%\n");
+    else
+        fprintf(fd, "%%IPPOS*%%\n");
+    /* image name */
+    if (image->info->name)
+        fprintf(fd, "%%IN%s*%%\n", image->info->name);
+    /* plotter film */
+    if (image->info->plotterFilm)
+        fprintf(fd, "%%PF%s*%%\n", image->info->plotterFilm);
+
+    /* image rotation */
+    if ((image->info->imageRotation != 0.0) || (thisTransform->rotation != 0.0))
+        fprintf(fd, "%%IR%d*%%\n", (int)round(RAD2DEG(image->info->imageRotation)) % 360);
+
+    if ((image->info->imageJustifyTypeA != GERBV_JUSTIFY_NOJUSTIFY)
+        || (image->info->imageJustifyTypeB != GERBV_JUSTIFY_NOJUSTIFY)) {
+        fprintf(fd, "%%IJA");
+        if (image->info->imageJustifyTypeA == GERBV_JUSTIFY_CENTERJUSTIFY)
+            fprintf(fd, "C");
+        else
+            fprintf(fd, "%.4f", image->info->imageJustifyOffsetA);
+        fprintf(fd, "B");
+        if (image->info->imageJustifyTypeB == GERBV_JUSTIFY_CENTERJUSTIFY)
+            fprintf(fd, "C");
+        else
+            fprintf(fd, "%.4f", image->info->imageJustifyOffsetB);
+        fprintf(fd, "*%%\n");
+    }
+    /* handle scale user orientation transforms */
+    if (fabs(thisTransform->scaleX - 1) > GERBV_PRECISION_LINEAR_INCH
+        || fabs(thisTransform->scaleY - 1) > GERBV_PRECISION_LINEAR_INCH) {
+        fprintf(fd, "%%SFA%.4fB%.4f*%%\n", thisTransform->scaleX, thisTransform->scaleY);
+    }
+    /* handle mirror image user orientation transform */
+    if ((thisTransform->mirrorAroundX) || (thisTransform->mirrorAroundY)) {
+        fprintf(fd, "%%MIA%dB%d*%%\n", thisTransform->mirrorAroundY, thisTransform->mirrorAroundX);
+    }
+
+    /* define all apertures */
+    fprintf(fd, "G04 --Define apertures--*\n");
+    export_rs274x_write_apertures(fd, image);
+
+    /* write rest of image */
+    fprintf(fd, "G04 --Start main section--*\n");
+    gint         currentAperture = 0;
+    gerbv_net_t* currentNet;
+
+    oldLayer = image->layers;
+    oldState = image->states;
+    /* skip the first net, since it's always zero due to the way we parse things */
+    for (currentNet = image->netlist->next; currentNet; currentNet = currentNet->next) {
+        /* check for "layer" changes (RS274X commands) */
+        if (currentNet->layer != oldLayer)
+            export_rs274x_write_layer_change(oldLayer, currentNet->layer, fd);
+
+        /* check for new "netstate" (more RS274X commands) */
+        if (currentNet->state != oldState)
+            export_rs274x_write_state_change(oldState, currentNet->state, fd);
+
+        /* check for tool changes */
+        /* also, make sure the aperture number is a valid one, since sometimes
+           the loaded file may refer to invalid apertures */
+        if ((currentNet->aperture != currentAperture) && (image->aperture[currentNet->aperture] != NULL)) {
+            fprintf(fd, "G54D%02d*\n", currentNet->aperture);
+            currentAperture = currentNet->aperture;
+        }
+
+        oldLayer = currentNet->layer;
+        oldState = currentNet->state;
+
+        long xVal, yVal, endX, endY, centerX, centerY;
+        switch (currentNet->interpolation) {
+            case GERBV_INTERPOLATION_LINEARx1:
+            case GERBV_INTERPOLATION_LINEARx10:
+            case GERBV_INTERPOLATION_LINEARx01:
+            case GERBV_INTERPOLATION_LINEARx001:
+                /* see if we need to write an "aperture off" line to get
+                   the pen to the right start point */
+                if ((!insidePolygon) && (currentNet->aperture_state == GERBV_APERTURE_STATE_ON)) {
+                    xVal = (long)round(currentNet->start_x * decimal_coeff);
+                    yVal = (long)round(currentNet->start_y * decimal_coeff);
+                    fprintf(fd, "G01X%07ldY%07ldD02*\n", xVal, yVal);
+                }
+                xVal = (long)round(currentNet->stop_x * decimal_coeff);
+                yVal = (long)round(currentNet->stop_y * decimal_coeff);
+                fprintf(fd, "G01X%07ldY%07ld", xVal, yVal);
+                /* and finally, write the esposure value */
+                if (currentNet->aperture_state == GERBV_APERTURE_STATE_OFF)
+                    fprintf(fd, "D02*\n");
+                else if (currentNet->aperture_state == GERBV_APERTURE_STATE_ON)
+                    fprintf(fd, "D01*\n");
+                else
+                    fprintf(fd, "D03*\n");
+                break;
+            case GERBV_INTERPOLATION_CW_CIRCULAR:
+            case GERBV_INTERPOLATION_CCW_CIRCULAR:
+                /* see if we need to write an "aperture off" line to get
+                   the pen to the right start point */
+                if ((!insidePolygon) && (currentNet->aperture_state == GERBV_APERTURE_STATE_ON)) {
+                    xVal = (long)round(currentNet->start_x * decimal_coeff);
+                    yVal = (long)round(currentNet->start_y * decimal_coeff);
+                    fprintf(fd, "G01X%07ldY%07ldD02*\n", xVal, yVal);
+                }
+                centerX = (long)round((currentNet->cirseg->cp_x - currentNet->start_x) * decimal_coeff);
+                centerY = (long)round((currentNet->cirseg->cp_y - currentNet->start_y) * decimal_coeff);
+                endX    = (long)round(currentNet->stop_x * decimal_coeff);
+                endY    = (long)round(currentNet->stop_y * decimal_coeff);
+
+                /* always use multi-quadrant, since it's much easier to export */
+                /*  and most all software should support it */
+                fprintf(fd, "G75*\n");
+
+                if (currentNet->interpolation == GERBV_INTERPOLATION_CW_CIRCULAR)
+                    fprintf(fd, "G02"); /* Clockwise */
+                else
+                    fprintf(fd, "G03"); /* Counter clockwise */
+
+                /* don't write the I and J values if the exposure is off */
+                if (currentNet->aperture_state == GERBV_APERTURE_STATE_ON)
+                    fprintf(fd, "X%07ldY%07ldI%07ldJ%07ld", endX, endY, centerX, centerY);
+                else
+                    fprintf(fd, "X%07ldY%07ld", endX, endY);
+                /* and finally, write the esposure value */
+                if (currentNet->aperture_state == GERBV_APERTURE_STATE_OFF)
+                    fprintf(fd, "D02*\n");
+                else if (currentNet->aperture_state == GERBV_APERTURE_STATE_ON)
+                    fprintf(fd, "D01*\n");
+                else
+                    fprintf(fd, "D03*\n");
+                break;
+            case GERBV_INTERPOLATION_PAREA_START:
+                fprintf(fd, "G36*\n");
+                insidePolygon = TRUE;
+                break;
+            case GERBV_INTERPOLATION_PAREA_END:
+                fprintf(fd, "G37*\n");
+                insidePolygon = FALSE;
+                break;
+            default: break;
+        }
+    }
+
+    fprintf(fd, "M02*\n");
+
+    gerbv_destroy_image(image);
+    fclose(fd);
+
+    // return to the default locale
+    setlocale(LC_NUMERIC, "");
+    return TRUE;
 }
diff --git a/src/gerb_file.c b/src/gerb_file.c
index dbc2da1..75bc683 100644
--- a/src/gerb_file.c
+++ b/src/gerb_file.c
@@ -50,64 +50,64 @@
 #include "gerb_file.h"
 
 /* DEBUG printing.  #define DEBUG 1 in config.h to use this fcn. */
-#define dprintf if(DEBUG) printf
-
-gerb_file_t *
-gerb_fopen(char const * filename)
-{
-    gerb_file_t *fd;
-    struct stat statinfo;
-    
+#define dprintf \
+    if (DEBUG)  \
+    printf
+
+gerb_file_t*
+gerb_fopen(const char* filename) {
+    gerb_file_t* fd;
+    struct stat  statinfo;
+
     dprintf("---> Entering gerb_fopen, filename = %s\n", filename);
 
     fd = g_new(gerb_file_t, 1);
     if (fd == NULL) {
-	return NULL;
+        return NULL;
     }
 
     dprintf("     Doing fopen\n");
     /* fopen() can't open files with non ASCII filenames on windows */
     fd->fd = g_fopen(filename, "rb");
     if (fd->fd == NULL) {
-	g_free(fd);
-	return NULL;
+        g_free(fd);
+        return NULL;
     }
 
     dprintf("     Doing fstat\n");
-    fd->ptr = 0;
+    fd->ptr    = 0;
     fd->fileno = fileno(fd->fd);
     if (fstat(fd->fileno, &statinfo) < 0) {
-	fclose(fd->fd);
-	g_free(fd);
-	return NULL;
+        fclose(fd->fd);
+        g_free(fd);
+        return NULL;
     }
 
     dprintf("     Checking S_ISREG\n");
     if (!S_ISREG(statinfo.st_mode)) {
-	fclose(fd->fd);
-	g_free(fd);
-	errno = EISDIR;
-	return NULL;
+        fclose(fd->fd);
+        g_free(fd);
+        errno = EISDIR;
+        return NULL;
     }
 
     dprintf("     Checking statinfo.st_size\n");
     if ((int)statinfo.st_size == 0) {
-	fclose(fd->fd);
-	g_free(fd);
-	errno = EIO; /* More compatible with the world outside Linux */
-	return NULL;
+        fclose(fd->fd);
+        g_free(fd);
+        errno = EIO; /* More compatible with the world outside Linux */
+        return NULL;
     }
 
 #ifdef HAVE_SYS_MMAN_H
 
     dprintf("     Doing mmap\n");
     fd->datalen = (int)statinfo.st_size;
-    fd->data = (char *)mmap(0, statinfo.st_size, PROT_READ, MAP_PRIVATE, 
-			    fd->fileno, 0);
-    if(fd->data == MAP_FAILED) {
-	fclose(fd->fd);
-	g_free(fd);
-	fd = NULL;
+    fd->data    = (char*)mmap(0, statinfo.st_size, PROT_READ, MAP_PRIVATE, fd->fileno, 0);
+    if (fd->data == MAP_FAILED) {
+        fclose(fd->fd);
+        g_free(fd);
+        fd = NULL;
     }
 
 #else
@@ -115,7 +115,7 @@ gerb_fopen(char const * filename)
 
     dprintf("     Doing calloc\n");
     fd->datalen = (int)statinfo.st_size;
-    fd->data = calloc(1, statinfo.st_size + 1);
+    fd->data    = calloc(1, statinfo.st_size + 1);
     if (fd->data == NULL) {
         fclose(fd->fd);
         g_free(fd);
@@ -123,11 +123,11 @@ gerb_fopen(char const * filename)
     }
     if (fread((void*)fd->data, 1, statinfo.st_size, fd->fd) != statinfo.st_size) {
         fclose(fd->fd);
-	g_free(fd->data);
+        g_free(fd->data);
         g_free(fd);
-	return NULL;
+        return NULL;
     }
-    rewind (fd->fd);
+    rewind(fd->fd);
 
 #endif
 
@@ -138,55 +138,49 @@ gerb_fopen(char const * filename)
     return fd;
 } /* gerb_fopen */
 
-
 int
-gerb_fgetc(gerb_file_t *fd)
-{
+gerb_fgetc(gerb_file_t* fd) {
 
     if (fd->ptr >= fd->datalen)
-	return EOF;
+        return EOF;
 
-    return (int) fd->data[fd->ptr++];
+    return (int)fd->data[fd->ptr++];
 } /* gerb_fgetc */
 
-
 int
-gerb_fgetint(gerb_file_t *fd, int *len)
-{
+gerb_fgetint(gerb_file_t* fd, int* len) {
     long int result;
-    char *end;
-    
-    errno = 0;
+    char*    end;
+
+    errno  = 0;
     result = strtol(fd->data + fd->ptr, &end, 10);
     if (errno) {
-	GERB_COMPILE_ERROR(_("Failed to read integer"));
-	return 0;
+        GERB_COMPILE_ERROR(_("Failed to read integer"));
+        return 0;
     }
 
     if (len) {
-	*len = end - (fd->data + fd->ptr);
+        *len = end - (fd->data + fd->ptr);
     }
 
     fd->ptr = end - fd->data;
 
     if (len && (result < 0))
-	*len -= 1;
+        *len -= 1;
 
     return (int)result;
 } /* gerb_fgetint */
 
-
 double
-gerb_fgetdouble(gerb_file_t *fd)
-{
+gerb_fgetdouble(gerb_file_t* fd) {
     double result;
-    char *end;
+    char*  end;
 
-    errno = 0;    
+    errno  = 0;
     result = strtod(fd->data + fd->ptr, &end);
     if (errno) {
-	GERB_COMPILE_ERROR(_("Failed to read double"));
-	return 0.0;
+        GERB_COMPILE_ERROR(_("Failed to read double"));
+        return 0.0;
     }
 
     fd->ptr = end - fd->data;
@@ -194,31 +188,29 @@ gerb_fgetdouble(gerb_file_t *fd)
     return result;
 } /* gerb_fgetdouble */
 
-
-char *
-gerb_fgetstring(gerb_file_t *fd, char term)
-{
-    char *strend = NULL;
-    char *newstr;
+char*
+gerb_fgetstring(gerb_file_t* fd, char term) {
+    char* strend = NULL;
+    char* newstr;
     char *i, *iend;
-    int len;
+    int   len;
 
     iend = fd->data + fd->datalen;
     for (i = fd->data + fd->ptr; i < iend; i++) {
-	if (*i == term) {
-	    strend = i;
-	    break;
-	}
+        if (*i == term) {
+            strend = i;
+            break;
+        }
     }
 
     if (strend == NULL)
-	return NULL;
+        return NULL;
 
     len = strend - (fd->data + fd->ptr);
 
-    newstr = (char *)g_malloc(len + 1);
+    newstr = (char*)g_malloc(len + 1);
     if (newstr == NULL)
-	return NULL;
+        return NULL;
     strncpy(newstr, fd->data + fd->ptr, len);
     newstr[len] = '\0';
     fd->ptr += len;
@@ -226,47 +218,41 @@ gerb_fgetstring(gerb_file_t *fd, char term)
     return newstr;
 } /* gerb_fgetstring */
 
-
-void 
-gerb_ungetc(gerb_file_t *fd)
-{
+void
+gerb_ungetc(gerb_file_t* fd) {
     if (fd->ptr)
-	fd->ptr--;
+        fd->ptr--;
 
     return;
 } /* gerb_ungetc */
 
-
 void
-gerb_fclose(gerb_file_t *fd)
-{
+gerb_fclose(gerb_file_t* fd) {
     if (fd) {
         g_free(fd->filename);
 
 #ifdef HAVE_SYS_MMAN_H
-	if (munmap(fd->data, fd->datalen) < 0)
-	    GERB_FATAL_ERROR("munmap: %s", strerror(errno));
+        if (munmap(fd->data, fd->datalen) < 0)
+            GERB_FATAL_ERROR("munmap: %s", strerror(errno));
 #else
-	g_free(fd->data);
-#endif   
-	if (fclose(fd->fd) == EOF)
-	    GERB_FATAL_ERROR("fclose: %s", strerror(errno));
-	g_free(fd);
+        g_free(fd->data);
+#endif
+        if (fclose(fd->fd) == EOF)
+            GERB_FATAL_ERROR("fclose: %s", strerror(errno));
+        g_free(fd);
     }
 
     return;
 } /* gerb_fclose */
 
-
-char *
-gerb_find_file(char const * filename, char **paths)
-{
-    char *curr_path = NULL;
-    char *complete_path = NULL;
-    int	 i;
+char*
+gerb_find_file(const char* filename, char** paths) {
+    char* curr_path     = NULL;
+    char* complete_path = NULL;
+    int   i;
 
 #ifdef DEBUG
-    if( DEBUG > 0 ) {
+    if (DEBUG > 0) {
         for (i = 0; paths[i] != NULL; i++) {
             printf("%s():  paths[%d] = \"%s\"\n", __FUNCTION__, i, paths[i]);
         }
@@ -276,74 +262,75 @@ gerb_find_file(char const * filename, char **paths)
     for (i = 0; paths[i] != NULL; i++) {
         dprintf("%s():  Try paths[%d] = \"%s\"\n", __FUNCTION__, i, paths[i]);
 
-	/*
-	 * Environment variables start with a $ sign 
-	 */
-	if (paths[i][0] == '$') {
-	    char *env_name, *env_value, *tmp;
-	    int len;
-
-	    /* Extract environment name. Remember we start with a $ */
-        
-   	    tmp = strchr(paths[i], G_DIR_SEPARATOR);
-	    if (tmp == NULL) 
-		len = strlen(paths[i]) - 1;
-	    else
-		len = tmp - paths[i] - 1;
-	    env_name = (char *)g_malloc(len + 1);
-	    if (env_name == NULL)
-		return NULL;
-	    strncpy(env_name, (char *)(paths[i] + 1), len);
-	    env_name[len] = '\0';
-
-	    env_value = getenv(env_name);
-            dprintf("%s():  Trying \"%s\" = \"%s\" from the environment\n",
-                __FUNCTION__, env_name,
-                env_value == NULL ? "(null)" : env_value);
-
-	    if (env_value == NULL) {
-	      curr_path = NULL;
-	    } else {
-	      curr_path = (char *)g_malloc(strlen(env_value) + strlen(&paths[i][len + 1]) + 1);
-	      if (curr_path == NULL)
-		return NULL;
-	      strcpy(curr_path, env_value);
-	      strcat(curr_path, &paths[i][len + 1]);
-	      g_free(env_name);
-	    }
-	} else {
-	    curr_path = paths[i];
-	}
-
-	if (curr_path != NULL) {
-	  /*
-	   * Build complete path (inc. filename) and check if file exists.
-	   */
-	  complete_path = g_build_filename(curr_path, filename, NULL);
-	  if (complete_path == NULL)
-	    return NULL;
-	  
-	  if (paths[i][0] == '$') {
-	    g_free(curr_path);
-	    curr_path = NULL;
-	  }
-	  
-	  dprintf("%s():  Tring to access \"%s\"\n", __FUNCTION__,
-		  complete_path);
-	  
-	  if (access(complete_path, R_OK) != -1)
-	    break;
-	  
-	  g_free(complete_path);
-	  complete_path = NULL;
-	}
+        /*
+         * Environment variables start with a $ sign
+         */
+        if (paths[i][0] == '$') {
+            char *env_name, *env_value, *tmp;
+            int   len;
+
+            /* Extract environment name. Remember we start with a $ */
+
+            tmp = strchr(paths[i], G_DIR_SEPARATOR);
+            if (tmp == NULL)
+                len = strlen(paths[i]) - 1;
+            else
+                len = tmp - paths[i] - 1;
+            env_name = (char*)g_malloc(len + 1);
+            if (env_name == NULL)
+                return NULL;
+            strncpy(env_name, (char*)(paths[i] + 1), len);
+            env_name[len] = '\0';
+
+            env_value = getenv(env_name);
+            dprintf(
+                "%s():  Trying \"%s\" = \"%s\" from the environment\n", __FUNCTION__, env_name,
+                env_value == NULL ? "(null)" : env_value
+            );
+
+            if (env_value == NULL) {
+                curr_path = NULL;
+            } else {
+                curr_path = (char*)g_malloc(strlen(env_value) + strlen(&paths[i][len + 1]) + 1);
+                if (curr_path == NULL)
+                    return NULL;
+                strcpy(curr_path, env_value);
+                strcat(curr_path, &paths[i][len + 1]);
+                g_free(env_name);
+            }
+        } else {
+            curr_path = paths[i];
+        }
+
+        if (curr_path != NULL) {
+            /*
+             * Build complete path (inc. filename) and check if file exists.
+             */
+            complete_path = g_build_filename(curr_path, filename, NULL);
+            if (complete_path == NULL)
+                return NULL;
+
+            if (paths[i][0] == '$') {
+                g_free(curr_path);
+                curr_path = NULL;
+            }
+
+            dprintf("%s():  Tring to access \"%s\"\n", __FUNCTION__, complete_path);
+
+            if (access(complete_path, R_OK) != -1)
+                break;
+
+            g_free(complete_path);
+            complete_path = NULL;
+        }
     }
-	
+
     if (complete_path == NULL)
-      errno = ENOENT;
-    
-    dprintf("%s():  returning complete_path = \"%s\"\n", __FUNCTION__,
-	    complete_path == NULL ? "(null)" : complete_path);
-    
+        errno = ENOENT;
+
+    dprintf(
+        "%s():  returning complete_path = \"%s\"\n", __FUNCTION__, complete_path == NULL ? "(null)" : complete_path
+    );
+
     return complete_path;
 } /* gerb_find_file */
diff --git a/src/gerb_file.h b/src/gerb_file.h
index 7f5e05e..77f32ed 100644
--- a/src/gerb_file.h
+++ b/src/gerb_file.h
@@ -32,29 +32,28 @@
 #include <stdio.h>
 
 typedef struct file {
-    FILE *fd;     /* File descriptor */
-    int   fileno; /* The integer version of fd */
-    char *data;   /* Pointer to data mmaped in. May not be changed, use ptr */
-    int   datalen;/* Length of mmaped data ie file length */
-    int   ptr;    /* Index in data where we are reading */
-    char *filename;  /* File name */
+    FILE* fd;       /* File descriptor */
+    int   fileno;   /* The integer version of fd */
+    char* data;     /* Pointer to data mmaped in. May not be changed, use ptr */
+    int   datalen;  /* Length of mmaped data ie file length */
+    int   ptr;      /* Index in data where we are reading */
+    char* filename; /* File name */
 } gerb_file_t;
 
-
-gerb_file_t *gerb_fopen(char const* filename);
-int gerb_fgetc(gerb_file_t *fd);
-int gerb_fgetint(gerb_file_t *fd, int *len); /* If len != NULL, returns number
-						of chars parsed in len */
-double gerb_fgetdouble(gerb_file_t *fd);
-char *gerb_fgetstring(gerb_file_t *fd, char term);
-void gerb_ungetc(gerb_file_t *fd);
-void gerb_fclose(gerb_file_t *fd);
+gerb_file_t* gerb_fopen(const char* filename);
+int          gerb_fgetc(gerb_file_t* fd);
+int          gerb_fgetint(gerb_file_t* fd, int* len); /* If len != NULL, returns number
+                                 of chars parsed in len */
+double gerb_fgetdouble(gerb_file_t* fd);
+char*  gerb_fgetstring(gerb_file_t* fd, char term);
+void   gerb_ungetc(gerb_file_t* fd);
+void   gerb_fclose(gerb_file_t* fd);
 
 /** Search for files in directories pointed out by paths, a NULL terminated
  * list of directories to search. If a string in paths starts with a $, then
  * characters to / (or string end if no /) is interpreted as a environment
  * variable.
  */
-char *gerb_find_file(char const * filename, char **paths);
+char* gerb_find_file(const char* filename, char** paths);
 
 #endif /* GERB_FILE_H */
diff --git a/src/gerb_image.c b/src/gerb_image.c
index 88458e6..24f0fd1 100644
--- a/src/gerb_image.c
+++ b/src/gerb_image.c
@@ -42,27 +42,26 @@ typedef struct {
     int newAperture;
 } gerb_translation_entry_t;
 
-gerbv_image_t *
-gerbv_create_image(gerbv_image_t *image, const gchar *type)
-{
+gerbv_image_t*
+gerbv_create_image(gerbv_image_t* image, const gchar* type) {
     gerbv_destroy_image(image);
-    
+
     /* Malloc space for image */
     if (NULL == (image = g_new0(gerbv_image_t, 1))) {
-	return NULL;
+        return NULL;
     }
 
     /* Malloc space for image->netlist */
     if (NULL == (image->netlist = g_new0(gerbv_net_t, 1))) {
-	g_free(image);
-	return NULL;
+        g_free(image);
+        return NULL;
     }
 
     /* Malloc space for image->info */
     if (NULL == (image->info = g_new0(gerbv_image_info_t, 1))) {
-	g_free(image->netlist);
-	g_free(image);
-	return NULL;
+        g_free(image->netlist);
+        g_free(image);
+        return NULL;
     }
 
     /* Set aside position for stats struct */
@@ -75,112 +74,110 @@ gerbv_create_image(gerbv_image_t *image, const gchar *type)
     image->info->max_y = -HUGE_VAL;
 
     /* create our first layer and fill with non-zero default values */
-    image->layers = g_new0 (gerbv_layer_t, 1);
+    image->layers                  = g_new0(gerbv_layer_t, 1);
     image->layers->stepAndRepeat.X = 1;
     image->layers->stepAndRepeat.Y = 1;
-    image->layers->polarity = GERBV_POLARITY_DARK;
-    
+    image->layers->polarity        = GERBV_POLARITY_DARK;
+
     /* create our first netstate and fill with non-zero default values */
-    image->states = g_new0 (gerbv_netstate_t, 1);
+    image->states         = g_new0(gerbv_netstate_t, 1);
     image->states->scaleA = 1;
     image->states->scaleB = 1;
 
     /* fill in some values for our first net */
     image->netlist->layer = image->layers;
     image->netlist->state = image->states;
-    
+
     if (type == NULL)
-	image->info->type = g_strdup (_("unknown"));
+        image->info->type = g_strdup(_("unknown"));
     else
-	image->info->type = g_strdup (type);
+        image->info->type = g_strdup(type);
 
     /* the individual file parsers will have to set this. */
     image->info->attr_list = NULL;
-    image->info->n_attr = 0;
+    image->info->n_attr    = 0;
 
     return image;
 }
 
-
 void
-gerbv_destroy_image(gerbv_image_t *image)
-{
-    int i;
-    gerbv_net_t *net, *tmp;
-    gerbv_layer_t *layer;
-    gerbv_netstate_t *state;
-    gerbv_simplified_amacro_t *sam,*sam2;
-
-    if(image==NULL)
+gerbv_destroy_image(gerbv_image_t* image) {
+    int                        i;
+    gerbv_net_t *              net, *tmp;
+    gerbv_layer_t*             layer;
+    gerbv_netstate_t*          state;
+    gerbv_simplified_amacro_t *sam, *sam2;
+
+    if (image == NULL)
         return;
-        
+
     /*
      * Free apertures
      */
-    for (i = 0; i < APERTURE_MAX; i++) 
-	if (image->aperture[i] != NULL) {
-	    for (sam = image->aperture[i]->simplified; sam != NULL; ){
-	      sam2 = sam->next;
-	    	g_free (sam);
-	    	sam = sam2;
-	    }
-
-	    g_free(image->aperture[i]);
-	    image->aperture[i] = NULL;
-	}
+    for (i = 0; i < APERTURE_MAX; i++)
+        if (image->aperture[i] != NULL) {
+            for (sam = image->aperture[i]->simplified; sam != NULL;) {
+                sam2 = sam->next;
+                g_free(sam);
+                sam = sam2;
+            }
+
+            g_free(image->aperture[i]);
+            image->aperture[i] = NULL;
+        }
 
     /*
      * Free aperture macro
      */
-     
+
     if (image->amacro) {
-	free_amacro(image->amacro);
+        free_amacro(image->amacro);
     }
 
     /*
      * Free format
      */
     if (image->format)
-	g_free(image->format);
-    
+        g_free(image->format);
+
     /*
      * Free info
      */
     if (image->info) {
-	g_free(image->info->name);
-	g_free(image->info->type);
-	gerbv_attribute_destroy_HID_attribute (image->info->attr_list, image->info->n_attr);
-	g_free(image->info);
+        g_free(image->info->name);
+        g_free(image->info->type);
+        gerbv_attribute_destroy_HID_attribute(image->info->attr_list, image->info->n_attr);
+        g_free(image->info);
     }
-    
+
     /*
      * Free netlist
      */
-    for (net = image->netlist; net != NULL; ) {
-	tmp = net; 
-	net = net->next; 
-	if (tmp->cirseg != NULL) {
-	    g_free(tmp->cirseg);
-	    tmp->cirseg = NULL;
-	}
-	if (tmp->label) {
-		g_string_free (tmp->label, TRUE);
-	}
-	g_free(tmp);
-	tmp = NULL;
+    for (net = image->netlist; net != NULL;) {
+        tmp = net;
+        net = net->next;
+        if (tmp->cirseg != NULL) {
+            g_free(tmp->cirseg);
+            tmp->cirseg = NULL;
+        }
+        if (tmp->label) {
+            g_string_free(tmp->label, TRUE);
+        }
+        g_free(tmp);
+        tmp = NULL;
     }
-    for (layer = image->layers; layer != NULL; ) {
-    	gerbv_layer_t *tempLayer = layer;
-    	
-    	layer = layer->next;
-    	g_free (tempLayer->name);
-    	g_free (tempLayer);
+    for (layer = image->layers; layer != NULL;) {
+        gerbv_layer_t* tempLayer = layer;
+
+        layer = layer->next;
+        g_free(tempLayer->name);
+        g_free(tempLayer);
     }
-    for (state = image->states; state != NULL; ) {
-    	gerbv_netstate_t *tempState = state;
-    	
-    	state = state->next;
-    	g_free (tempState);
+    for (state = image->states; state != NULL;) {
+        gerbv_netstate_t* tempState = state;
+
+        state = state->next;
+        g_free(tempState);
     }
     gerbv_stats_destroy(image->gerbv_stats);
     gerbv_drill_stats_destroy(image->drill_stats);
@@ -190,11 +187,10 @@ gerbv_destroy_image(gerbv_image_t *image)
      */
     g_free(image);
     image = NULL;
-    
+
     return;
 }
 
-
 /*
  * Check that the parsed gerber image is complete.
  * Returned errorcodes are:
@@ -206,516 +202,434 @@ gerbv_destroy_image(gerbv_image_t *image)
  * It could be any of above or'ed together
  */
 gerb_verify_error_t
-gerbv_image_verify(gerbv_image_t const* image)
-{
+gerbv_image_verify(const gerbv_image_t* image) {
     gerb_verify_error_t error = GERB_IMAGE_OK;
-    int i, n_nets;;
-    gerbv_net_t *net;
+    int                 i, n_nets;
+    ;
+    gerbv_net_t* net;
 
-    if (image->netlist == NULL) error |= GERB_IMAGE_MISSING_NETLIST;
-    if (image->format == NULL)  error |= GERB_IMAGE_MISSING_FORMAT;
-    if (image->info == NULL)    error |= GERB_IMAGE_MISSING_INFO;
+    if (image->netlist == NULL)
+        error |= GERB_IMAGE_MISSING_NETLIST;
+    if (image->format == NULL)
+        error |= GERB_IMAGE_MISSING_FORMAT;
+    if (image->info == NULL)
+        error |= GERB_IMAGE_MISSING_INFO;
 
     /* Count how many nets we have */
     n_nets = 0;
     if (image->netlist != NULL) {
-      for (net = image->netlist->next ; net != NULL; net = net->next) {
-	n_nets++;
-      }
+        for (net = image->netlist->next; net != NULL; net = net->next) {
+            n_nets++;
+        }
     }
 
     /* If we have nets but no apertures are defined, then complain */
-    if( n_nets > 0) {
-      for (i = 0; i < APERTURE_MAX && image->aperture[i] == NULL; i++);
-      if (i == APERTURE_MAX) error |= GERB_IMAGE_MISSING_APERTURES;
+    if (n_nets > 0) {
+        for (i = 0; i < APERTURE_MAX && image->aperture[i] == NULL; i++)
+            ;
+        if (i == APERTURE_MAX)
+            error |= GERB_IMAGE_MISSING_APERTURES;
     }
 
     return error;
 } /* gerb_image_verify */
 
 static void
-gerbv_image_aperture_state(gerbv_aperture_state_t state)
-{
+gerbv_image_aperture_state(gerbv_aperture_state_t state) {
     switch (state) {
-    case GERBV_APERTURE_STATE_OFF:
-	printf(_("..state off"));
-	break;
-    case GERBV_APERTURE_STATE_ON:
-	printf(_("..state on"));
-	break;
-    case GERBV_APERTURE_STATE_FLASH:
-	printf(_("..state flash"));
-	break;
-    default:
-	printf(_("..state unknown"));
+        case GERBV_APERTURE_STATE_OFF: printf(_("..state off")); break;
+        case GERBV_APERTURE_STATE_ON: printf(_("..state on")); break;
+        case GERBV_APERTURE_STATE_FLASH: printf(_("..state flash")); break;
+        default: printf(_("..state unknown"));
     }
 }
 
 /* Dumps a written version of image to stdout */
-void 
-gerbv_image_dump(gerbv_image_t const* image)
-{
-    int i, j;
-    gerbv_aperture_t * const* aperture;
-    gerbv_net_t const * net;
+void
+gerbv_image_dump(const gerbv_image_t* image) {
+    int                      i, j;
+    gerbv_aperture_t* const* aperture;
+    const gerbv_net_t*       net;
 
     /* Apertures */
     printf(_("Apertures:\n"));
     aperture = image->aperture;
     for (i = 0; i < APERTURE_MAX; i++) {
-	if (aperture[i]) {
-	    printf(_(" Aperture no:%d is an "), i);
-	    switch(aperture[i]->type) {
-	    case GERBV_APTYPE_CIRCLE:
-		printf(_("circle"));
-		break;
-	    case GERBV_APTYPE_RECTANGLE:
-		printf(_("rectangle"));
-		break;
-	    case GERBV_APTYPE_OVAL:
-		printf(_("oval"));
-		break;
-	    case GERBV_APTYPE_POLYGON:
-		printf(_("polygon"));
-		break;
-	    case GERBV_APTYPE_MACRO:
-		printf(_("macro"));
-		break;
-	    default:
-		printf(_("unknown"));
-	    }
-	    for (j = 0; j < aperture[i]->nuf_parameters; j++) {
-		printf(" %f", aperture[i]->parameter[j]);
-	    }
-	    printf("\n");
-	}
+        if (aperture[i]) {
+            printf(_(" Aperture no:%d is an "), i);
+            switch (aperture[i]->type) {
+                case GERBV_APTYPE_CIRCLE: printf(_("circle")); break;
+                case GERBV_APTYPE_RECTANGLE: printf(_("rectangle")); break;
+                case GERBV_APTYPE_OVAL: printf(_("oval")); break;
+                case GERBV_APTYPE_POLYGON: printf(_("polygon")); break;
+                case GERBV_APTYPE_MACRO: printf(_("macro")); break;
+                default: printf(_("unknown"));
+            }
+            for (j = 0; j < aperture[i]->nuf_parameters; j++) {
+                printf(" %f", aperture[i]->parameter[j]);
+            }
+            printf("\n");
+        }
     }
 
     /* Netlist */
     net = image->netlist;
-    while (net){
-	printf(_("(%f,%f)->(%f,%f) with %d ("), net->start_x, net->start_y,
-	       net->stop_x, net->stop_y, net->aperture);
-	printf("%s", _(gerbv_interpolation_name(net->interpolation)));
-	gerbv_image_aperture_state(net->aperture_state);
-	printf(")\n");
-	net = net->next;
+    while (net) {
+        printf(_("(%f,%f)->(%f,%f) with %d ("), net->start_x, net->start_y, net->stop_x, net->stop_y, net->aperture);
+        printf("%s", _(gerbv_interpolation_name(net->interpolation)));
+        gerbv_image_aperture_state(net->aperture_state);
+        printf(")\n");
+        net = net->next;
     }
 } /* gerbv_image_dump */
 
+gerbv_layer_t*
+gerbv_image_return_new_layer(gerbv_layer_t* previousLayer) {
+    gerbv_layer_t* newLayer = g_new0(gerbv_layer_t, 1);
 
-gerbv_layer_t *
-gerbv_image_return_new_layer (gerbv_layer_t *previousLayer)
-{
-    gerbv_layer_t *newLayer = g_new0 (gerbv_layer_t, 1);
-    
-    *newLayer = *previousLayer;
+    *newLayer           = *previousLayer;
     previousLayer->next = newLayer;
     /* clear this boolean so we only draw the knockout once */
     newLayer->knockout.firstInstance = FALSE;
-    newLayer->name = NULL;
-    newLayer->next = NULL;
-    
+    newLayer->name                   = NULL;
+    newLayer->next                   = NULL;
+
     return newLayer;
 } /* gerbv_image_return_new_layer */
 
+gerbv_netstate_t*
+gerbv_image_return_new_netstate(gerbv_netstate_t* previousState) {
+    gerbv_netstate_t* newState = g_new0(gerbv_netstate_t, 1);
 
-gerbv_netstate_t *
-gerbv_image_return_new_netstate (gerbv_netstate_t *previousState)
-{
-    gerbv_netstate_t *newState = g_new0 (gerbv_netstate_t, 1);
-    
-    *newState = *previousState;
+    *newState           = *previousState;
     previousState->next = newState;
-    newState->scaleA = 1.0;
-    newState->scaleB = 1.0;
-    newState->next = NULL;
-    
+    newState->scaleA    = 1.0;
+    newState->scaleB    = 1.0;
+    newState->next      = NULL;
+
     return newState;
 } /* gerbv_image_return_new_netstate */
 
-gerbv_layer_t *
-gerbv_image_duplicate_layer (gerbv_layer_t *oldLayer) {
-    gerbv_layer_t *newLayer = g_new (gerbv_layer_t,1);
-    
-    *newLayer = *oldLayer;
-    newLayer->name = g_strdup (oldLayer->name);
+gerbv_layer_t*
+gerbv_image_duplicate_layer(gerbv_layer_t* oldLayer) {
+    gerbv_layer_t* newLayer = g_new(gerbv_layer_t, 1);
+
+    *newLayer      = *oldLayer;
+    newLayer->name = g_strdup(oldLayer->name);
     return newLayer;
 }
 
-static gerbv_netstate_t *
-gerbv_image_duplicate_state (gerbv_netstate_t *oldState)
-{
-	gerbv_netstate_t *newState = g_new (gerbv_netstate_t, 1);
+static gerbv_netstate_t*
+gerbv_image_duplicate_state(gerbv_netstate_t* oldState) {
+    gerbv_netstate_t* newState = g_new(gerbv_netstate_t, 1);
 
-	*newState = *oldState;
-	return newState;
+    *newState = *oldState;
+    return newState;
 }
 
-static gerbv_aperture_t *
-gerbv_image_duplicate_aperture (gerbv_aperture_t *oldAperture)
-{
-    gerbv_aperture_t *newAperture = g_new0 (gerbv_aperture_t,1);
+static gerbv_aperture_t*
+gerbv_image_duplicate_aperture(gerbv_aperture_t* oldAperture) {
+    gerbv_aperture_t*          newAperture = g_new0(gerbv_aperture_t, 1);
     gerbv_simplified_amacro_t *simplifiedMacro, *tempSimplified;
 
     *newAperture = *oldAperture;
 
     /* delete the amacro section, since we really don't need it anymore
     now that we have the simplified section */
-    newAperture->amacro = NULL;
+    newAperture->amacro     = NULL;
     newAperture->simplified = NULL;
 
     /* copy any simplified macros over */
     tempSimplified = NULL;
     for (simplifiedMacro = oldAperture->simplified; simplifiedMacro != NULL; simplifiedMacro = simplifiedMacro->next) {
-	gerbv_simplified_amacro_t *newSimplified = g_new0 (gerbv_simplified_amacro_t,1);
-	*newSimplified = *simplifiedMacro;
-	if (tempSimplified)
-	  tempSimplified->next = newSimplified;
-	else
-	  newAperture->simplified = newSimplified;
-	tempSimplified = newSimplified;
+        gerbv_simplified_amacro_t* newSimplified = g_new0(gerbv_simplified_amacro_t, 1);
+        *newSimplified                           = *simplifiedMacro;
+        if (tempSimplified)
+            tempSimplified->next = newSimplified;
+        else
+            newAperture->simplified = newSimplified;
+        tempSimplified = newSimplified;
     }
     return newAperture;
 }
 
 static void
-gerbv_image_copy_all_nets (gerbv_image_t *sourceImage,
-		gerbv_image_t *destImage, gerbv_layer_t *lastLayer,
-		gerbv_netstate_t *lastState, gerbv_net_t *lastNet,
-		gerbv_user_transformation_t *trans,
-		GArray *translationTable)
-{
-	/* NOTE: destImage already contains apertures and data,
-	 * latest data is: lastLayer, lastState, lastNet. */
-
-	gerbv_net_t *currentNet, *newNet;
-	gerbv_aperture_type_t aper_type;
-	gerbv_aperture_t *aper;
-	gerbv_simplified_amacro_t *sam;
-	int *trans_apers = NULL; /* Transformed apertures */
-	int aper_last_id = 0;
-	guint	err_scale_circle = 0,
-		err_scale_line_macro = 0,
-		err_scale_poly_macro = 0,
-		err_scale_thermo_macro = 0,
-		err_scale_moire_macro = 0,
-		err_unknown_aperture = 0,
-		err_unknown_macro_aperture = 0,
-		err_rotate_oval = 0,
-		err_rotate_rect = 0;
-
-	if (trans && (trans->mirrorAroundX || trans->mirrorAroundY)) {
-		if (sourceImage->layertype != GERBV_LAYERTYPE_DRILL) {
-			GERB_COMPILE_ERROR(_("Exporting mirrored file "
-						"is not supported!"));
-			return;
-		}
-	}
-
-	if (trans && trans->inverted) {
-		GERB_COMPILE_ERROR(_("Exporting inverted file "
-					"is not supported!"));
-		return;
-	}
-
-	if (trans) {
-		/* Find last used aperture to add transformed apertures if
-		 * needed */
-		for (aper_last_id = APERTURE_MAX - 1; aper_last_id > 0;
-						aper_last_id--) {
-			if (destImage->aperture[aper_last_id] != NULL)
-				break;
-		}
-
-		trans_apers = g_new (int, aper_last_id + 1);
-		/* Initialize trans_apers array */
-		for (int i = 0; i < aper_last_id + 1; i++)
-			trans_apers[i] = -1;
-	}
-
-	for (currentNet = sourceImage->netlist; currentNet != NULL;
-			currentNet = currentNet->next) {
-
-		/* Check for any new layers and duplicate them if needed */
-		if (currentNet->layer != lastLayer) {
-			lastLayer->next =
-				gerbv_image_duplicate_layer (currentNet->layer);
-			lastLayer = lastLayer->next;
-		}
-
-		/* Check for any new states and duplicate them if needed */
-		if (currentNet->state != lastState) {
-			lastState->next =
-				gerbv_image_duplicate_state (currentNet->state);
-			lastState = lastState->next;
-		}
-
-		/* Create and copy the actual net over */
-		newNet = g_new (gerbv_net_t, 1);
-		*newNet = *currentNet;
-
-		if (currentNet->cirseg) {
-			newNet->cirseg = g_new (gerbv_cirseg_t, 1);
-			*(newNet->cirseg) = *(currentNet->cirseg);
-		}
-
-		if (currentNet->label)
-			newNet->label = g_string_new (currentNet->label->str);
-		else
-			newNet->label = NULL;
-
-		newNet->state = lastState;
-		newNet->layer = lastLayer;
-
-		if (lastNet)
-			lastNet->next = newNet;
-		else
-			destImage->netlist = newNet;
-
-		lastNet = newNet;
-
-		/* Check if we need to translate the aperture number */
-		if (translationTable) {
-			for (guint i = 0; i < translationTable->len; i++) {
-				gerb_translation_entry_t translationEntry;
-
-				translationEntry =
-					g_array_index (translationTable,
-						gerb_translation_entry_t, i);
-
-				if (translationEntry.oldAperture ==
-						newNet->aperture) {
-					newNet->aperture =
-						translationEntry.newAperture;
-					break;
-				}
-			}
-		}
-
-		if (trans == NULL)
-			continue;
-
-		/* Transforming coords */
-		gerbv_transform_coord (&newNet->start_x,
-				&newNet->start_y, trans);
-		gerbv_transform_coord (&newNet->stop_x,
-				&newNet->stop_y, trans);
-
-		if (newNet->cirseg) {
-			/* Circular interpolation only exported by start, stop
-			 * end center coordinates. */
-			gerbv_transform_coord (&newNet->cirseg->cp_x,
-				&newNet->cirseg->cp_y, trans);
-		}
-
-		if (destImage->aperture[newNet->aperture] == NULL)
-			continue;
-
-		if (trans->scaleX == 1.0 && trans->scaleY == 1.0
-		&& fabs(trans->rotation) < GERBV_PRECISION_ANGLE_RAD)
-			continue;
-
-		/* Aperture is already transformed, use it */
-		if (trans_apers[newNet->aperture] != -1) {
-			newNet->aperture = trans_apers[newNet->aperture];
-			continue;
-		}
-
-		/* Transforming apertures */
-		aper_type = destImage->aperture[newNet->aperture]->type;
-		switch (aper_type) {
-		case GERBV_APTYPE_NONE:
-		case GERBV_APTYPE_POLYGON:
-			break;
-
-		case GERBV_APTYPE_CIRCLE:
-			if (trans->scaleX == trans->scaleY
-					&& trans->scaleX == 1.0) {
-				break;
-			}
-
-			if (trans->scaleX == trans->scaleY) {
-				aper = gerbv_image_duplicate_aperture (
-						destImage->aperture[
-							newNet->aperture]);
-				aper->parameter[0] *= trans->scaleX;
-
-				trans_apers[newNet->aperture] = ++aper_last_id;
-				destImage->aperture[aper_last_id] = aper;
-				newNet->aperture = aper_last_id;
-			} else {
-				err_scale_circle++;
-			}
-			break;
-
-		case GERBV_APTYPE_RECTANGLE:
-		case GERBV_APTYPE_OVAL:
-			if (trans->scaleX == 1.0 && trans->scaleY == 1.0
-			&&  fabs(fabs(trans->rotation) - M_PI)
-						< GERBV_PRECISION_ANGLE_RAD)
-				break;
-
-			aper = gerbv_image_duplicate_aperture (
-					destImage->aperture[newNet->aperture]);
-			aper->parameter[0] *= trans->scaleX;
-			aper->parameter[1] *= trans->scaleY;
-
-			if (fabs(fabs(trans->rotation) - M_PI_2)
-						< GERBV_PRECISION_ANGLE_RAD
-			||  fabs(fabs(trans->rotation) - (M_PI+M_PI_2))
-						< GERBV_PRECISION_ANGLE_RAD) {
-				double t = aper->parameter[0];
-				aper->parameter[0] = aper->parameter[1];
-				aper->parameter[1] = t;
-			} else {
-				if (aper_type == GERBV_APTYPE_RECTANGLE)
-					err_rotate_rect++;	/* TODO: make line21 macro */
-				else
-					err_rotate_oval++;
-
-				break;
-			}
-
-			trans_apers[newNet->aperture] = ++aper_last_id;
-			destImage->aperture[aper_last_id] = aper;
-			newNet->aperture = aper_last_id;
-
-			break;
-
-		case GERBV_APTYPE_MACRO:
-			aper = gerbv_image_duplicate_aperture (
-					destImage->aperture[newNet->aperture]);
-			sam = aper->simplified;
-
-			for (; sam != NULL; sam = sam->next) {
-				switch (sam->type) {
-				case GERBV_APTYPE_MACRO_CIRCLE:
-
-/* TODO: test circle macro center rotation */
-					sam->parameter[CIRCLE_CENTER_X] *=
-								trans->scaleX;
-					sam->parameter[CIRCLE_CENTER_Y] *=
-								trans->scaleY;
-					gerbv_rotate_coord(
-						sam->parameter +CIRCLE_CENTER_X,
-						sam->parameter +CIRCLE_CENTER_Y,
-						trans->rotation);
-
-					if (trans->scaleX != trans->scaleY) {
-						err_scale_circle++;
-						break;
-					}
-					sam->parameter[CIRCLE_DIAMETER] *=
-								trans->scaleX;
-					break;
-
-				case GERBV_APTYPE_MACRO_LINE20:
-					/* Vector line rectangle */
-					if (trans->scaleX == trans->scaleY) {
-						sam->parameter[LINE20_LINE_WIDTH] *=
-								trans->scaleX;
-					} else if (sam->parameter[LINE20_START_X] ==
-							sam->parameter[LINE20_END_X]) {
-						sam->parameter[LINE20_LINE_WIDTH] *=
-							trans->scaleX;	/* Vertical */
-					} else if (sam->parameter[LINE20_START_Y] ==
-							sam->parameter[LINE20_END_Y]) {
-						sam->parameter[LINE20_LINE_WIDTH] *=
-							trans->scaleY;	/* Horizontal */
-					} else {
-						/* TODO: make outline macro */
-						err_scale_line_macro++;
-						break;
-					}
-
-					sam->parameter[LINE20_START_X] *=
-							trans->scaleX;
-					sam->parameter[LINE20_START_Y] *=
-							trans->scaleY;
-					sam->parameter[LINE20_END_X] *=
-							trans->scaleX;
-					sam->parameter[LINE20_END_Y] *=
-							trans->scaleY;
-
-					/* LINE20_START_X, LINE20_START_Y,
-					 * LINE20_END_X, LINE20_END_Y are not
-					 * rotated, change only rotation angle */
-					sam->parameter[LINE20_ROTATION] +=
-						RAD2DEG(trans->rotation);
-					break;
+gerbv_image_copy_all_nets(
+    gerbv_image_t* sourceImage, gerbv_image_t* destImage, gerbv_layer_t* lastLayer, gerbv_netstate_t* lastState,
+    gerbv_net_t* lastNet, gerbv_user_transformation_t* trans, GArray* translationTable
+) {
+    /* NOTE: destImage already contains apertures and data,
+     * latest data is: lastLayer, lastState, lastNet. */
+
+    gerbv_net_t *              currentNet, *newNet;
+    gerbv_aperture_type_t      aper_type;
+    gerbv_aperture_t*          aper;
+    gerbv_simplified_amacro_t* sam;
+    int*                       trans_apers  = NULL; /* Transformed apertures */
+    int                        aper_last_id = 0;
+    guint err_scale_circle = 0, err_scale_line_macro = 0, err_scale_poly_macro = 0, err_scale_thermo_macro = 0,
+          err_scale_moire_macro = 0, err_unknown_aperture = 0, err_unknown_macro_aperture = 0, err_rotate_oval = 0,
+          err_rotate_rect = 0;
+
+    if (trans && (trans->mirrorAroundX || trans->mirrorAroundY)) {
+        if (sourceImage->layertype != GERBV_LAYERTYPE_DRILL) {
+            GERB_COMPILE_ERROR(
+                _("Exporting mirrored file "
+                  "is not supported!")
+            );
+            return;
+        }
+    }
+
+    if (trans && trans->inverted) {
+        GERB_COMPILE_ERROR(
+            _("Exporting inverted file "
+              "is not supported!")
+        );
+        return;
+    }
+
+    if (trans) {
+        /* Find last used aperture to add transformed apertures if
+         * needed */
+        for (aper_last_id = APERTURE_MAX - 1; aper_last_id > 0; aper_last_id--) {
+            if (destImage->aperture[aper_last_id] != NULL)
+                break;
+        }
+
+        trans_apers = g_new(int, aper_last_id + 1);
+        /* Initialize trans_apers array */
+        for (int i = 0; i < aper_last_id + 1; i++)
+            trans_apers[i] = -1;
+    }
+
+    for (currentNet = sourceImage->netlist; currentNet != NULL; currentNet = currentNet->next) {
+
+        /* Check for any new layers and duplicate them if needed */
+        if (currentNet->layer != lastLayer) {
+            lastLayer->next = gerbv_image_duplicate_layer(currentNet->layer);
+            lastLayer       = lastLayer->next;
+        }
+
+        /* Check for any new states and duplicate them if needed */
+        if (currentNet->state != lastState) {
+            lastState->next = gerbv_image_duplicate_state(currentNet->state);
+            lastState       = lastState->next;
+        }
+
+        /* Create and copy the actual net over */
+        newNet  = g_new(gerbv_net_t, 1);
+        *newNet = *currentNet;
+
+        if (currentNet->cirseg) {
+            newNet->cirseg    = g_new(gerbv_cirseg_t, 1);
+            *(newNet->cirseg) = *(currentNet->cirseg);
+        }
+
+        if (currentNet->label)
+            newNet->label = g_string_new(currentNet->label->str);
+        else
+            newNet->label = NULL;
+
+        newNet->state = lastState;
+        newNet->layer = lastLayer;
+
+        if (lastNet)
+            lastNet->next = newNet;
+        else
+            destImage->netlist = newNet;
+
+        lastNet = newNet;
+
+        /* Check if we need to translate the aperture number */
+        if (translationTable) {
+            for (guint i = 0; i < translationTable->len; i++) {
+                gerb_translation_entry_t translationEntry;
+
+                translationEntry = g_array_index(translationTable, gerb_translation_entry_t, i);
+
+                if (translationEntry.oldAperture == newNet->aperture) {
+                    newNet->aperture = translationEntry.newAperture;
+                    break;
+                }
+            }
+        }
+
+        if (trans == NULL)
+            continue;
+
+        /* Transforming coords */
+        gerbv_transform_coord(&newNet->start_x, &newNet->start_y, trans);
+        gerbv_transform_coord(&newNet->stop_x, &newNet->stop_y, trans);
+
+        if (newNet->cirseg) {
+            /* Circular interpolation only exported by start, stop
+             * end center coordinates. */
+            gerbv_transform_coord(&newNet->cirseg->cp_x, &newNet->cirseg->cp_y, trans);
+        }
+
+        if (destImage->aperture[newNet->aperture] == NULL)
+            continue;
+
+        if (trans->scaleX == 1.0 && trans->scaleY == 1.0 && fabs(trans->rotation) < GERBV_PRECISION_ANGLE_RAD)
+            continue;
+
+        /* Aperture is already transformed, use it */
+        if (trans_apers[newNet->aperture] != -1) {
+            newNet->aperture = trans_apers[newNet->aperture];
+            continue;
+        }
+
+        /* Transforming apertures */
+        aper_type = destImage->aperture[newNet->aperture]->type;
+        switch (aper_type) {
+            case GERBV_APTYPE_NONE:
+            case GERBV_APTYPE_POLYGON: break;
+
+            case GERBV_APTYPE_CIRCLE:
+                if (trans->scaleX == trans->scaleY && trans->scaleX == 1.0) {
+                    break;
+                }
+
+                if (trans->scaleX == trans->scaleY) {
+                    aper = gerbv_image_duplicate_aperture(destImage->aperture[newNet->aperture]);
+                    aper->parameter[0] *= trans->scaleX;
+
+                    trans_apers[newNet->aperture]     = ++aper_last_id;
+                    destImage->aperture[aper_last_id] = aper;
+                    newNet->aperture                  = aper_last_id;
+                } else {
+                    err_scale_circle++;
+                }
+                break;
+
+            case GERBV_APTYPE_RECTANGLE:
+            case GERBV_APTYPE_OVAL:
+                if (trans->scaleX == 1.0 && trans->scaleY == 1.0
+                    && fabs(fabs(trans->rotation) - M_PI) < GERBV_PRECISION_ANGLE_RAD)
+                    break;
+
+                aper = gerbv_image_duplicate_aperture(destImage->aperture[newNet->aperture]);
+                aper->parameter[0] *= trans->scaleX;
+                aper->parameter[1] *= trans->scaleY;
+
+                if (fabs(fabs(trans->rotation) - M_PI_2) < GERBV_PRECISION_ANGLE_RAD
+                    || fabs(fabs(trans->rotation) - (M_PI + M_PI_2)) < GERBV_PRECISION_ANGLE_RAD) {
+                    double t           = aper->parameter[0];
+                    aper->parameter[0] = aper->parameter[1];
+                    aper->parameter[1] = t;
+                } else {
+                    if (aper_type == GERBV_APTYPE_RECTANGLE)
+                        err_rotate_rect++; /* TODO: make line21 macro */
+                    else
+                        err_rotate_oval++;
+
+                    break;
+                }
+
+                trans_apers[newNet->aperture]     = ++aper_last_id;
+                destImage->aperture[aper_last_id] = aper;
+                newNet->aperture                  = aper_last_id;
+
+                break;
+
+            case GERBV_APTYPE_MACRO:
+                aper = gerbv_image_duplicate_aperture(destImage->aperture[newNet->aperture]);
+                sam  = aper->simplified;
+
+                for (; sam != NULL; sam = sam->next) {
+                    switch (sam->type) {
+                        case GERBV_APTYPE_MACRO_CIRCLE:
+
+                            /* TODO: test circle macro center rotation */
+                            sam->parameter[CIRCLE_CENTER_X] *= trans->scaleX;
+                            sam->parameter[CIRCLE_CENTER_Y] *= trans->scaleY;
+                            gerbv_rotate_coord(
+                                sam->parameter + CIRCLE_CENTER_X, sam->parameter + CIRCLE_CENTER_Y, trans->rotation
+                            );
+
+                            if (trans->scaleX != trans->scaleY) {
+                                err_scale_circle++;
+                                break;
+                            }
+                            sam->parameter[CIRCLE_DIAMETER] *= trans->scaleX;
+                            break;
+
+                        case GERBV_APTYPE_MACRO_LINE20:
+                            /* Vector line rectangle */
+                            if (trans->scaleX == trans->scaleY) {
+                                sam->parameter[LINE20_LINE_WIDTH] *= trans->scaleX;
+                            } else if (sam->parameter[LINE20_START_X] == sam->parameter[LINE20_END_X]) {
+                                sam->parameter[LINE20_LINE_WIDTH] *= trans->scaleX; /* Vertical */
+                            } else if (sam->parameter[LINE20_START_Y] == sam->parameter[LINE20_END_Y]) {
+                                sam->parameter[LINE20_LINE_WIDTH] *= trans->scaleY; /* Horizontal */
+                            } else {
+                                /* TODO: make outline macro */
+                                err_scale_line_macro++;
+                                break;
+                            }
+
+                            sam->parameter[LINE20_START_X] *= trans->scaleX;
+                            sam->parameter[LINE20_START_Y] *= trans->scaleY;
+                            sam->parameter[LINE20_END_X] *= trans->scaleX;
+                            sam->parameter[LINE20_END_Y] *= trans->scaleY;
+
+                            /* LINE20_START_X, LINE20_START_Y,
+                             * LINE20_END_X, LINE20_END_Y are not
+                             * rotated, change only rotation angle */
+                            sam->parameter[LINE20_ROTATION] += RAD2DEG(trans->rotation);
+                            break;
 
 /* Compile time check if LINE21 and LINE22 parameters indexes are equal */
-#if (LINE21_WIDTH != LINE22_WIDTH) \
- || (LINE21_HEIGHT != LINE22_HEIGHT) \
- || (LINE21_ROTATION != LINE22_ROTATION) \
- || (LINE21_CENTER_X != LINE22_LOWER_LEFT_X) \
- || (LINE21_CENTER_Y != LINE22_LOWER_LEFT_Y)
-# error "LINE21 and LINE22 indexes are not equal"
+#if (LINE21_WIDTH != LINE22_WIDTH) || (LINE21_HEIGHT != LINE22_HEIGHT) || (LINE21_ROTATION != LINE22_ROTATION) \
+    || (LINE21_CENTER_X != LINE22_LOWER_LEFT_X) || (LINE21_CENTER_Y != LINE22_LOWER_LEFT_Y)
+#error "LINE21 and LINE22 indexes are not equal"
 #endif
 
-				case GERBV_APTYPE_MACRO_LINE21:
-						/* Centered line rectangle */
-				case GERBV_APTYPE_MACRO_LINE22:
-						/* Lower left line rectangle */
-
-					/* Using LINE21 parameters array
-					 * indexes for LINE21 and LINE22, as
-					 * they are equal */
-					if (trans->scaleX == trans->scaleY) {
-						sam->parameter[LINE21_WIDTH] *=
-								trans->scaleX;
-						sam->parameter[LINE21_HEIGHT] *=
-								trans->scaleX;
-
-					} else if (fabs(sam->parameter[LINE21_ROTATION]) == 0
-					|| fabs(sam->parameter[LINE21_ROTATION]) == 180) {
-						sam->parameter[LINE21_WIDTH] *=
-								trans->scaleX;
-						sam->parameter[LINE21_HEIGHT] *=
-								trans->scaleY;
-
-					} else if (fabs(sam->parameter[LINE21_ROTATION]) == 90
-					|| fabs(sam->parameter[LINE21_ROTATION]) == 270) {
-						double t;
-						t = sam->parameter[LINE21_WIDTH];
-						sam->parameter[LINE21_WIDTH] =
-							trans->scaleY *
-							sam->parameter[
-								LINE21_HEIGHT];
-						sam->parameter[LINE21_HEIGHT] =
-							trans->scaleX * t;
-					} else {
-						/* TODO: make outline macro */
-						err_scale_line_macro++;
-						break;
-					}
-
-					sam->parameter[LINE21_CENTER_X] *=
-								trans->scaleX;
-					sam->parameter[LINE21_CENTER_Y] *=
-								trans->scaleY;
-
-					sam->parameter[LINE21_ROTATION] +=
-						RAD2DEG(trans->rotation);
-					gerbv_rotate_coord(
-						sam->parameter +LINE21_CENTER_X,
-						sam->parameter +LINE21_CENTER_Y,
-						trans->rotation);
-					break;
-
-				case GERBV_APTYPE_MACRO_OUTLINE:
-					for (int i = 0; i < 1 + sam->parameter[
-							OUTLINE_NUMBER_OF_POINTS]; i++) {
-						sam->parameter[OUTLINE_X_IDX_OF_POINT(i)] *=
-								trans->scaleX;
-						sam->parameter[OUTLINE_Y_IDX_OF_POINT(i)] *=
-								trans->scaleY;
-					}
-
-					sam->parameter[OUTLINE_ROTATION_IDX(sam->parameter)] +=
-								RAD2DEG(trans->rotation);
-					break;
+                        case GERBV_APTYPE_MACRO_LINE21:
+                            /* Centered line rectangle */
+                        case GERBV_APTYPE_MACRO_LINE22:
+                            /* Lower left line rectangle */
+
+                            /* Using LINE21 parameters array
+                             * indexes for LINE21 and LINE22, as
+                             * they are equal */
+                            if (trans->scaleX == trans->scaleY) {
+                                sam->parameter[LINE21_WIDTH] *= trans->scaleX;
+                                sam->parameter[LINE21_HEIGHT] *= trans->scaleX;
+
+                            } else if (fabs(sam->parameter[LINE21_ROTATION]) == 0 || fabs(sam->parameter[LINE21_ROTATION]) == 180) {
+                                sam->parameter[LINE21_WIDTH] *= trans->scaleX;
+                                sam->parameter[LINE21_HEIGHT] *= trans->scaleY;
+
+                            } else if (fabs(sam->parameter[LINE21_ROTATION]) == 90 || fabs(sam->parameter[LINE21_ROTATION]) == 270) {
+                                double t;
+                                t                             = sam->parameter[LINE21_WIDTH];
+                                sam->parameter[LINE21_WIDTH]  = trans->scaleY * sam->parameter[LINE21_HEIGHT];
+                                sam->parameter[LINE21_HEIGHT] = trans->scaleX * t;
+                            } else {
+                                /* TODO: make outline macro */
+                                err_scale_line_macro++;
+                                break;
+                            }
+
+                            sam->parameter[LINE21_CENTER_X] *= trans->scaleX;
+                            sam->parameter[LINE21_CENTER_Y] *= trans->scaleY;
+
+                            sam->parameter[LINE21_ROTATION] += RAD2DEG(trans->rotation);
+                            gerbv_rotate_coord(
+                                sam->parameter + LINE21_CENTER_X, sam->parameter + LINE21_CENTER_Y, trans->rotation
+                            );
+                            break;
+
+                        case GERBV_APTYPE_MACRO_OUTLINE:
+                            for (int i = 0; i < 1 + sam->parameter[OUTLINE_NUMBER_OF_POINTS]; i++) {
+                                sam->parameter[OUTLINE_X_IDX_OF_POINT(i)] *= trans->scaleX;
+                                sam->parameter[OUTLINE_Y_IDX_OF_POINT(i)] *= trans->scaleY;
+                            }
+
+                            sam->parameter[OUTLINE_ROTATION_IDX(sam->parameter)] += RAD2DEG(trans->rotation);
+                            break;
 #if 0
 {
 /* TODO */
@@ -725,649 +639,650 @@ selection_add_item (&screen.selectionInfo, &sItem);
 }
 #endif
 
-				case GERBV_APTYPE_MACRO_POLYGON:
-					if (trans->scaleX == trans->scaleY) {
-						sam->parameter[POLYGON_CENTER_X]
-							*= trans->scaleX;
-						sam->parameter[POLYGON_CENTER_Y]
-							*= trans->scaleX;
-						sam->parameter[POLYGON_DIAMETER]
-							*= trans->scaleX;
-					} else {
-						/* TODO: make outline macro */
-						err_scale_poly_macro++;
-						break;
-					}
-
-					sam->parameter[POLYGON_ROTATION] +=
-						RAD2DEG(trans->rotation);
-					break;
-
-				case GERBV_APTYPE_MACRO_MOIRE:
-					if (trans->scaleX == trans->scaleY) {
-						sam->parameter[MOIRE_CENTER_X]
-							*= trans->scaleX;
-						sam->parameter[MOIRE_CENTER_Y]
-							*= trans->scaleX;
-						sam->parameter[MOIRE_OUTSIDE_DIAMETER]
-							*= trans->scaleX;
-						sam->parameter[MOIRE_CIRCLE_THICKNESS]
-							*= trans->scaleX;
-						sam->parameter[MOIRE_GAP_WIDTH]
-							*= trans->scaleX;
-						sam->parameter[MOIRE_CROSSHAIR_THICKNESS]
-							*= trans->scaleX;
-						sam->parameter[MOIRE_CROSSHAIR_LENGTH]
-							*= trans->scaleX;
-					} else {
-						err_scale_moire_macro++;
-						break;
-					}
-
-					sam->parameter[MOIRE_ROTATION] +=
-						RAD2DEG(trans->rotation);
-					break;
-
-				case GERBV_APTYPE_MACRO_THERMAL:
-					if (trans->scaleX == trans->scaleY) {
-						sam->parameter[THERMAL_CENTER_X]
-							*= trans->scaleX;
-						sam->parameter[THERMAL_CENTER_Y]
-							*= trans->scaleX;
-						sam->parameter[THERMAL_INSIDE_DIAMETER]
-							*= trans->scaleX;
-						sam->parameter[THERMAL_OUTSIDE_DIAMETER]
-							*= trans->scaleX;
-						sam->parameter[THERMAL_CROSSHAIR_THICKNESS]
-							*= trans->scaleX;
-					} else {
-						err_scale_thermo_macro++;
-						break;
-					}
-
-					sam->parameter[THERMAL_ROTATION] +=
-						RAD2DEG(trans->rotation);
-					break;
-
-				default:
-					/* TODO: free aper if it is skipped (i.e. unused)? */
-					err_unknown_macro_aperture++;
-				}
-			}
-
-			trans_apers[newNet->aperture] = ++aper_last_id;
-			destImage->aperture[aper_last_id] = aper;
-			newNet->aperture = aper_last_id;
-
-			break;
-		default:
-			err_unknown_aperture++;
-		}
-	}
-
-	if (err_rotate_rect)
-		GERB_COMPILE_ERROR(ngettext(
-			"Can't rotate %u rectangular aperture to %.2f "
-			"degrees (non 90 multiply)!",
-			"Can't rotate %u rectangular apertures to %.2f "
-			"degrees (non 90 multiply)!", err_rotate_rect),
-			err_rotate_rect, RAD2DEG(trans->rotation));
-
-	if (err_scale_line_macro)
-		GERB_COMPILE_ERROR(ngettext(
-			"Can't scale %u line macro!",
-			"Can't scale %u line macros!",
-			err_scale_line_macro), err_scale_line_macro);
-
-	if (err_scale_poly_macro)
-		GERB_COMPILE_ERROR(ngettext(
-			"Can't scale %u polygon macro!",
-			"Can't scale %u polygon macros!",
-			err_scale_poly_macro), err_scale_poly_macro);
-
-	if (err_scale_thermo_macro)
-		GERB_COMPILE_ERROR(ngettext(
-			"Can't scale %u thermal macro!",
-			"Can't scale %u thermal macros!",
-			err_scale_poly_macro), err_scale_poly_macro);
-
-	if (err_scale_moire_macro)
-		GERB_COMPILE_ERROR(ngettext(
-			"Can't scale %u moire macro!",
-			"Can't scale %u moire macros!",
-			err_scale_poly_macro), err_scale_poly_macro);
-
-	if (err_rotate_oval)
-		GERB_COMPILE_ERROR(ngettext(
-			"Can't rotate %u oval aperture to %.2f "
-			"degrees (non 90 multiply)!",
-			"Can't rotate %u oval apertures to %.2f "
-			"degrees (non 90 multiply)!", err_rotate_oval),
-			err_rotate_oval, RAD2DEG(trans->rotation));
-
-	if (err_scale_circle)
-		GERB_COMPILE_ERROR(ngettext(
-			"Can't scale %u circle aperture to ellipse!",
-			"Can't scale %u circle apertures to ellipse!",
-			err_scale_circle), err_scale_circle);
-
-	if (err_unknown_aperture)
-		GERB_COMPILE_ERROR(ngettext(
-			"Skipped %u aperture with unknown type!",
-			"Skipped %u apertures with unknown type!",
-			err_unknown_aperture), err_unknown_aperture);
-
-	if (err_unknown_macro_aperture)
-		GERB_COMPILE_ERROR(ngettext(
-			"Skipped %u macro aperture!",
-			"Skipped %u macro apertures!",
-			err_unknown_macro_aperture),
-				err_unknown_macro_aperture);
-
-	g_free (trans_apers);
+                        case GERBV_APTYPE_MACRO_POLYGON:
+                            if (trans->scaleX == trans->scaleY) {
+                                sam->parameter[POLYGON_CENTER_X] *= trans->scaleX;
+                                sam->parameter[POLYGON_CENTER_Y] *= trans->scaleX;
+                                sam->parameter[POLYGON_DIAMETER] *= trans->scaleX;
+                            } else {
+                                /* TODO: make outline macro */
+                                err_scale_poly_macro++;
+                                break;
+                            }
+
+                            sam->parameter[POLYGON_ROTATION] += RAD2DEG(trans->rotation);
+                            break;
+
+                        case GERBV_APTYPE_MACRO_MOIRE:
+                            if (trans->scaleX == trans->scaleY) {
+                                sam->parameter[MOIRE_CENTER_X] *= trans->scaleX;
+                                sam->parameter[MOIRE_CENTER_Y] *= trans->scaleX;
+                                sam->parameter[MOIRE_OUTSIDE_DIAMETER] *= trans->scaleX;
+                                sam->parameter[MOIRE_CIRCLE_THICKNESS] *= trans->scaleX;
+                                sam->parameter[MOIRE_GAP_WIDTH] *= trans->scaleX;
+                                sam->parameter[MOIRE_CROSSHAIR_THICKNESS] *= trans->scaleX;
+                                sam->parameter[MOIRE_CROSSHAIR_LENGTH] *= trans->scaleX;
+                            } else {
+                                err_scale_moire_macro++;
+                                break;
+                            }
+
+                            sam->parameter[MOIRE_ROTATION] += RAD2DEG(trans->rotation);
+                            break;
+
+                        case GERBV_APTYPE_MACRO_THERMAL:
+                            if (trans->scaleX == trans->scaleY) {
+                                sam->parameter[THERMAL_CENTER_X] *= trans->scaleX;
+                                sam->parameter[THERMAL_CENTER_Y] *= trans->scaleX;
+                                sam->parameter[THERMAL_INSIDE_DIAMETER] *= trans->scaleX;
+                                sam->parameter[THERMAL_OUTSIDE_DIAMETER] *= trans->scaleX;
+                                sam->parameter[THERMAL_CROSSHAIR_THICKNESS] *= trans->scaleX;
+                            } else {
+                                err_scale_thermo_macro++;
+                                break;
+                            }
+
+                            sam->parameter[THERMAL_ROTATION] += RAD2DEG(trans->rotation);
+                            break;
+
+                        default:
+                            /* TODO: free aper if it is skipped (i.e. unused)? */
+                            err_unknown_macro_aperture++;
+                    }
+                }
+
+                trans_apers[newNet->aperture]     = ++aper_last_id;
+                destImage->aperture[aper_last_id] = aper;
+                newNet->aperture                  = aper_last_id;
+
+                break;
+            default: err_unknown_aperture++;
+        }
+    }
+
+    if (err_rotate_rect)
+        GERB_COMPILE_ERROR(
+            ngettext(
+                "Can't rotate %u rectangular aperture to %.2f "
+                "degrees (non 90 multiply)!",
+                "Can't rotate %u rectangular apertures to %.2f "
+                "degrees (non 90 multiply)!",
+                err_rotate_rect
+            ),
+            err_rotate_rect, RAD2DEG(trans->rotation)
+        );
+
+    if (err_scale_line_macro)
+        GERB_COMPILE_ERROR(
+            ngettext("Can't scale %u line macro!", "Can't scale %u line macros!", err_scale_line_macro),
+            err_scale_line_macro
+        );
+
+    if (err_scale_poly_macro)
+        GERB_COMPILE_ERROR(
+            ngettext("Can't scale %u polygon macro!", "Can't scale %u polygon macros!", err_scale_poly_macro),
+            err_scale_poly_macro
+        );
+
+    if (err_scale_thermo_macro)
+        GERB_COMPILE_ERROR(
+            ngettext("Can't scale %u thermal macro!", "Can't scale %u thermal macros!", err_scale_poly_macro),
+            err_scale_poly_macro
+        );
+
+    if (err_scale_moire_macro)
+        GERB_COMPILE_ERROR(
+            ngettext("Can't scale %u moire macro!", "Can't scale %u moire macros!", err_scale_poly_macro),
+            err_scale_poly_macro
+        );
+
+    if (err_rotate_oval)
+        GERB_COMPILE_ERROR(
+            ngettext(
+                "Can't rotate %u oval aperture to %.2f "
+                "degrees (non 90 multiply)!",
+                "Can't rotate %u oval apertures to %.2f "
+                "degrees (non 90 multiply)!",
+                err_rotate_oval
+            ),
+            err_rotate_oval, RAD2DEG(trans->rotation)
+        );
+
+    if (err_scale_circle)
+        GERB_COMPILE_ERROR(
+            ngettext(
+                "Can't scale %u circle aperture to ellipse!", "Can't scale %u circle apertures to ellipse!",
+                err_scale_circle
+            ),
+            err_scale_circle
+        );
+
+    if (err_unknown_aperture)
+        GERB_COMPILE_ERROR(
+            ngettext(
+                "Skipped %u aperture with unknown type!", "Skipped %u apertures with unknown type!",
+                err_unknown_aperture
+            ),
+            err_unknown_aperture
+        );
+
+    if (err_unknown_macro_aperture)
+        GERB_COMPILE_ERROR(
+            ngettext("Skipped %u macro aperture!", "Skipped %u macro apertures!", err_unknown_macro_aperture),
+            err_unknown_macro_aperture
+        );
+
+    g_free(trans_apers);
 }
 
 gint
-gerbv_image_find_existing_aperture_match (gerbv_aperture_t *checkAperture, gerbv_image_t *imageToSearch) {
-    int i,j;
+gerbv_image_find_existing_aperture_match(gerbv_aperture_t* checkAperture, gerbv_image_t* imageToSearch) {
+    int      i, j;
     gboolean isMatch;
-    
+
     for (i = 0; i < APERTURE_MAX; i++) {
-	if (imageToSearch->aperture[i] != NULL) {
-	  if ((imageToSearch->aperture[i]->type == checkAperture->type) &&
-	      (imageToSearch->aperture[i]->simplified == NULL) &&
-	      (imageToSearch->aperture[i]->unit == checkAperture->unit)) {
-	    /* check all parameters match too */
-	    isMatch=TRUE;
-	    for (j=0; j<APERTURE_PARAMETERS_MAX; j++){
-	      if (imageToSearch->aperture[i]->parameter[j] != checkAperture->parameter[j])
-	        isMatch = FALSE;
-	    }
-	    if (isMatch)
-	      return i;
-	  }	      
-	}
+        if (imageToSearch->aperture[i] != NULL) {
+            if ((imageToSearch->aperture[i]->type == checkAperture->type)
+                && (imageToSearch->aperture[i]->simplified == NULL)
+                && (imageToSearch->aperture[i]->unit == checkAperture->unit)) {
+                /* check all parameters match too */
+                isMatch = TRUE;
+                for (j = 0; j < APERTURE_PARAMETERS_MAX; j++) {
+                    if (imageToSearch->aperture[i]->parameter[j] != checkAperture->parameter[j])
+                        isMatch = FALSE;
+                }
+                if (isMatch)
+                    return i;
+            }
+        }
     }
     return 0;
 }
 
 int
-gerbv_image_find_unused_aperture_number (int startIndex, gerbv_image_t *image){
+gerbv_image_find_unused_aperture_number(int startIndex, gerbv_image_t* image) {
     int i;
-    
+
     for (i = startIndex; i < APERTURE_MAX; i++) {
-	if (image->aperture[i] == NULL) {
-	  return i;
-	}
+        if (image->aperture[i] == NULL) {
+            return i;
+        }
     }
     return -1;
 }
 
-gerbv_image_t *
-gerbv_image_duplicate_image (gerbv_image_t *sourceImage, gerbv_user_transformation_t *transform) {
-    gerbv_image_t *newImage = gerbv_create_image(NULL, sourceImage->info->type);
-    int i;
-    int lastUsedApertureNumber = APERTURE_MIN - 1;
-    GArray *apertureNumberTable = g_array_new(FALSE,FALSE,sizeof(gerb_translation_entry_t));
-    
+gerbv_image_t*
+gerbv_image_duplicate_image(gerbv_image_t* sourceImage, gerbv_user_transformation_t* transform) {
+    gerbv_image_t* newImage = gerbv_create_image(NULL, sourceImage->info->type);
+    int            i;
+    int            lastUsedApertureNumber = APERTURE_MIN - 1;
+    GArray*        apertureNumberTable    = g_array_new(FALSE, FALSE, sizeof(gerb_translation_entry_t));
+
     newImage->layertype = sourceImage->layertype;
     /* copy information layer over */
-    *(newImage->info) = *(sourceImage->info);
-    newImage->info->name = g_strdup (sourceImage->info->name);
-    newImage->info->type = g_strdup (sourceImage->info->type);
-    newImage->info->plotterFilm = g_strdup (sourceImage->info->plotterFilm);
-    newImage->info->attr_list = gerbv_attribute_dup (sourceImage->info->attr_list,
-    		 sourceImage->info->n_attr);
-    
+    *(newImage->info)           = *(sourceImage->info);
+    newImage->info->name        = g_strdup(sourceImage->info->name);
+    newImage->info->type        = g_strdup(sourceImage->info->type);
+    newImage->info->plotterFilm = g_strdup(sourceImage->info->plotterFilm);
+    newImage->info->attr_list   = gerbv_attribute_dup(sourceImage->info->attr_list, sourceImage->info->n_attr);
+
     /* copy apertures over, compressing all the numbers down for a cleaner output, and
        moving and apertures less than 10 up to the correct range */
     for (i = 0; i < APERTURE_MAX; i++) {
-	if (sourceImage->aperture[i] != NULL) {
-	  gerbv_aperture_t *newAperture = gerbv_image_duplicate_aperture (sourceImage->aperture[i]);
+        if (sourceImage->aperture[i] != NULL) {
+            gerbv_aperture_t* newAperture = gerbv_image_duplicate_aperture(sourceImage->aperture[i]);
 
-	  lastUsedApertureNumber = gerbv_image_find_unused_aperture_number (lastUsedApertureNumber + 1, newImage);
-	  /* store the aperture numbers (new and old) in the translation table */
-	  gerb_translation_entry_t translationEntry={i,lastUsedApertureNumber};
-	  g_array_append_val (apertureNumberTable,translationEntry);
+            lastUsedApertureNumber = gerbv_image_find_unused_aperture_number(lastUsedApertureNumber + 1, newImage);
+            /* store the aperture numbers (new and old) in the translation table */
+            gerb_translation_entry_t translationEntry = { i, lastUsedApertureNumber };
+            g_array_append_val(apertureNumberTable, translationEntry);
 
-	  newImage->aperture[lastUsedApertureNumber] = newAperture;
-	}
+            newImage->aperture[lastUsedApertureNumber] = newAperture;
+        }
     }
-    
+
     /* step through all nets and create new layers and states on the fly, since
        we really don't have any other way to figure out where states and layers are used */
-    gerbv_image_copy_all_nets (sourceImage, newImage, newImage->layers, newImage->states, NULL, transform, apertureNumberTable);
-    g_array_free (apertureNumberTable, TRUE);
+    gerbv_image_copy_all_nets(
+        sourceImage, newImage, newImage->layers, newImage->states, NULL, transform, apertureNumberTable
+    );
+    g_array_free(apertureNumberTable, TRUE);
     return newImage;
 }
 
 void
-gerbv_image_copy_image (gerbv_image_t *sourceImage, gerbv_user_transformation_t *transform, gerbv_image_t *destinationImage) {
-    int lastUsedApertureNumber = APERTURE_MIN - 1;
-    int i;
-    GArray *apertureNumberTable = g_array_new(FALSE,FALSE,sizeof(gerb_translation_entry_t));
-    
+gerbv_image_copy_image(
+    gerbv_image_t* sourceImage, gerbv_user_transformation_t* transform, gerbv_image_t* destinationImage
+) {
+    int     lastUsedApertureNumber = APERTURE_MIN - 1;
+    int     i;
+    GArray* apertureNumberTable = g_array_new(FALSE, FALSE, sizeof(gerb_translation_entry_t));
+
     /* copy apertures over */
     for (i = 0; i < APERTURE_MAX; i++) {
-	if (sourceImage->aperture[i] != NULL) {
-	  gint existingAperture = gerbv_image_find_existing_aperture_match (sourceImage->aperture[i], destinationImage);
-	  
-	  /* if we already have an existing aperture in the destination image that matches what
-	     we want, just use it instead */
-	  if (existingAperture > 0) {
-	  	gerb_translation_entry_t translationEntry={i,existingAperture};
-	 	g_array_append_val (apertureNumberTable,translationEntry);
-	  }
-	  /* else, create a new aperture and put it in the destination image */
-	  else {
-	  	gerbv_aperture_t *newAperture = gerbv_image_duplicate_aperture (sourceImage->aperture[i]);
-	  
-	  	lastUsedApertureNumber = gerbv_image_find_unused_aperture_number (lastUsedApertureNumber + 1, destinationImage);
-	  	/* store the aperture numbers (new and old) in the translation table */
-	  	gerb_translation_entry_t translationEntry={i,lastUsedApertureNumber};
-	  	g_array_append_val (apertureNumberTable,translationEntry);
-
-	  	destinationImage->aperture[lastUsedApertureNumber] = newAperture;
-	  }
-	}
+        if (sourceImage->aperture[i] != NULL) {
+            gint existingAperture =
+                gerbv_image_find_existing_aperture_match(sourceImage->aperture[i], destinationImage);
+
+            /* if we already have an existing aperture in the destination image that matches what
+               we want, just use it instead */
+            if (existingAperture > 0) {
+                gerb_translation_entry_t translationEntry = { i, existingAperture };
+                g_array_append_val(apertureNumberTable, translationEntry);
+            }
+            /* else, create a new aperture and put it in the destination image */
+            else {
+                gerbv_aperture_t* newAperture = gerbv_image_duplicate_aperture(sourceImage->aperture[i]);
+
+                lastUsedApertureNumber =
+                    gerbv_image_find_unused_aperture_number(lastUsedApertureNumber + 1, destinationImage);
+                /* store the aperture numbers (new and old) in the translation table */
+                gerb_translation_entry_t translationEntry = { i, lastUsedApertureNumber };
+                g_array_append_val(apertureNumberTable, translationEntry);
+
+                destinationImage->aperture[lastUsedApertureNumber] = newAperture;
+            }
+        }
     }
     /* find the last layer, state, and net in the linked chains */
-    gerbv_netstate_t *lastState;
-    gerbv_layer_t *lastLayer;
-    gerbv_net_t *lastNet;
-    
-    for (lastState = destinationImage->states; lastState->next; lastState=lastState->next){}
-    for (lastLayer = destinationImage->layers; lastLayer->next; lastLayer=lastLayer->next){}
-    for (lastNet = destinationImage->netlist; lastNet->next; lastNet=lastNet->next){}
-    
+    gerbv_netstate_t* lastState;
+    gerbv_layer_t*    lastLayer;
+    gerbv_net_t*      lastNet;
+
+    for (lastState = destinationImage->states; lastState->next; lastState = lastState->next) {}
+    for (lastLayer = destinationImage->layers; lastLayer->next; lastLayer = lastLayer->next) {}
+    for (lastNet = destinationImage->netlist; lastNet->next; lastNet = lastNet->next) {}
+
     /* and then copy them all to the destination image, using the aperture translation table we just built */
-    gerbv_image_copy_all_nets (sourceImage, destinationImage, lastLayer, lastState, lastNet, transform, apertureNumberTable);
-    g_array_free (apertureNumberTable, TRUE);
+    gerbv_image_copy_all_nets(
+        sourceImage, destinationImage, lastLayer, lastState, lastNet, transform, apertureNumberTable
+    );
+    g_array_free(apertureNumberTable, TRUE);
 }
 
 void
-gerbv_image_delete_net (gerbv_net_t *currentNet) {
-	gerbv_net_t *tempNet;
-	
-	g_assert (currentNet);
-	/* we have a match, so just zero out all the important data fields */
-	currentNet->aperture = 0;
-	currentNet->aperture_state = GERBV_APERTURE_STATE_OFF;
-	
-	/* if this is a polygon start, we need to erase all the rest of the
-		 nets in this polygon too */
-	if (currentNet->interpolation == GERBV_INTERPOLATION_PAREA_START){
-		for (tempNet = currentNet->next; tempNet; tempNet = tempNet->next){	
-			tempNet->aperture = 0;
-			tempNet->aperture_state = GERBV_APERTURE_STATE_OFF;
-			
-			if (tempNet->interpolation == GERBV_INTERPOLATION_PAREA_END) {
-				tempNet->interpolation = GERBV_INTERPOLATION_DELETED;
-				break;
-			}
-			/* make sure we don't leave a polygon interpolation in, since
-		  	 it will still draw if it is */
-			tempNet->interpolation = GERBV_INTERPOLATION_DELETED;
-		}
-	}
-	/* make sure we don't leave a polygon interpolation in, since
-	   it will still draw if it is */
-	currentNet->interpolation = GERBV_INTERPOLATION_DELETED;
+gerbv_image_delete_net(gerbv_net_t* currentNet) {
+    gerbv_net_t* tempNet;
+
+    g_assert(currentNet);
+    /* we have a match, so just zero out all the important data fields */
+    currentNet->aperture       = 0;
+    currentNet->aperture_state = GERBV_APERTURE_STATE_OFF;
+
+    /* if this is a polygon start, we need to erase all the rest of the
+         nets in this polygon too */
+    if (currentNet->interpolation == GERBV_INTERPOLATION_PAREA_START) {
+        for (tempNet = currentNet->next; tempNet; tempNet = tempNet->next) {
+            tempNet->aperture       = 0;
+            tempNet->aperture_state = GERBV_APERTURE_STATE_OFF;
+
+            if (tempNet->interpolation == GERBV_INTERPOLATION_PAREA_END) {
+                tempNet->interpolation = GERBV_INTERPOLATION_DELETED;
+                break;
+            }
+            /* make sure we don't leave a polygon interpolation in, since
+             it will still draw if it is */
+            tempNet->interpolation = GERBV_INTERPOLATION_DELETED;
+        }
+    }
+    /* make sure we don't leave a polygon interpolation in, since
+       it will still draw if it is */
+    currentNet->interpolation = GERBV_INTERPOLATION_DELETED;
 }
 
 void
-gerbv_image_create_rectangle_object (gerbv_image_t *image, gdouble coordinateX,
-		gdouble coordinateY, gdouble width, gdouble height) {
-	gerbv_net_t *currentNet;
-	
-	/* run through and find last net pointer */
-	for (currentNet = image->netlist; currentNet->next; currentNet = currentNet->next){}
-	
-	/* create the polygon start node */
-	currentNet = gerber_create_new_net (currentNet, NULL, NULL);
-	currentNet->interpolation = GERBV_INTERPOLATION_PAREA_START;
-	
-	/* go to start point (we need this to create correct RS274X export code) */
-	currentNet = gerber_create_new_net (currentNet, NULL, NULL);
-	currentNet->interpolation = GERBV_INTERPOLATION_LINEARx1;
-	currentNet->aperture_state = GERBV_APERTURE_STATE_OFF;
-	currentNet->start_x = coordinateX;
-	currentNet->start_y = coordinateY;
-	currentNet->stop_x = coordinateX;
-	currentNet->stop_y = coordinateY;
-	
-	/* draw the 4 corners */
-	currentNet = gerber_create_new_net (currentNet, NULL, NULL);
-	currentNet->interpolation = GERBV_INTERPOLATION_LINEARx1;
-	currentNet->aperture_state = GERBV_APERTURE_STATE_ON;
-	currentNet->start_x = coordinateX;
-	currentNet->start_y = coordinateY;
-	currentNet->stop_x = coordinateX + width;
-	currentNet->stop_y = coordinateY;
-	gerber_update_min_and_max (&currentNet->boundingBox,currentNet->stop_x,currentNet->stop_y, 
-		0,0,0,0);
-	gerber_update_image_min_max (&currentNet->boundingBox, 0, 0, image);
-		
-	currentNet = gerber_create_new_net (currentNet, NULL, NULL);
-	currentNet->interpolation = GERBV_INTERPOLATION_LINEARx1;
-	currentNet->aperture_state = GERBV_APERTURE_STATE_ON;
-	currentNet->stop_x = coordinateX + width;
-	currentNet->stop_y = coordinateY + height;
-	gerber_update_min_and_max (&currentNet->boundingBox,currentNet->stop_x,currentNet->stop_y, 
-		0,0,0,0);
-	gerber_update_image_min_max (&currentNet->boundingBox, 0, 0, image);
-	
-	currentNet = gerber_create_new_net (currentNet, NULL, NULL);
-	currentNet->interpolation = GERBV_INTERPOLATION_LINEARx1;
-	currentNet->aperture_state = GERBV_APERTURE_STATE_ON;
-	currentNet->stop_x = coordinateX;
-	currentNet->stop_y = coordinateY + height;
-	gerber_update_min_and_max (&currentNet->boundingBox,currentNet->stop_x,currentNet->stop_y, 
-		0,0,0,0);
-	gerber_update_image_min_max (&currentNet->boundingBox, 0, 0, image);
-	
-	currentNet = gerber_create_new_net (currentNet, NULL, NULL);
-	currentNet->interpolation = GERBV_INTERPOLATION_LINEARx1;
-	currentNet->aperture_state = GERBV_APERTURE_STATE_ON;
-	currentNet->stop_x = coordinateX;
-	currentNet->stop_y = coordinateY;
-	gerber_update_min_and_max (&currentNet->boundingBox,currentNet->stop_x,currentNet->stop_y, 
-		0,0,0,0);
-	gerber_update_image_min_max (&currentNet->boundingBox, 0, 0, image);
-	
-	/* create the polygon end node */
-	currentNet = gerber_create_new_net (currentNet, NULL, NULL);
-	currentNet->interpolation = GERBV_INTERPOLATION_PAREA_END;
-	
-	return;
+gerbv_image_create_rectangle_object(
+    gerbv_image_t* image, gdouble coordinateX, gdouble coordinateY, gdouble width, gdouble height
+) {
+    gerbv_net_t* currentNet;
+
+    /* run through and find last net pointer */
+    for (currentNet = image->netlist; currentNet->next; currentNet = currentNet->next) {}
+
+    /* create the polygon start node */
+    currentNet                = gerber_create_new_net(currentNet, NULL, NULL);
+    currentNet->interpolation = GERBV_INTERPOLATION_PAREA_START;
+
+    /* go to start point (we need this to create correct RS274X export code) */
+    currentNet                 = gerber_create_new_net(currentNet, NULL, NULL);
+    currentNet->interpolation  = GERBV_INTERPOLATION_LINEARx1;
+    currentNet->aperture_state = GERBV_APERTURE_STATE_OFF;
+    currentNet->start_x        = coordinateX;
+    currentNet->start_y        = coordinateY;
+    currentNet->stop_x         = coordinateX;
+    currentNet->stop_y         = coordinateY;
+
+    /* draw the 4 corners */
+    currentNet                 = gerber_create_new_net(currentNet, NULL, NULL);
+    currentNet->interpolation  = GERBV_INTERPOLATION_LINEARx1;
+    currentNet->aperture_state = GERBV_APERTURE_STATE_ON;
+    currentNet->start_x        = coordinateX;
+    currentNet->start_y        = coordinateY;
+    currentNet->stop_x         = coordinateX + width;
+    currentNet->stop_y         = coordinateY;
+    gerber_update_min_and_max(&currentNet->boundingBox, currentNet->stop_x, currentNet->stop_y, 0, 0, 0, 0);
+    gerber_update_image_min_max(&currentNet->boundingBox, 0, 0, image);
+
+    currentNet                 = gerber_create_new_net(currentNet, NULL, NULL);
+    currentNet->interpolation  = GERBV_INTERPOLATION_LINEARx1;
+    currentNet->aperture_state = GERBV_APERTURE_STATE_ON;
+    currentNet->stop_x         = coordinateX + width;
+    currentNet->stop_y         = coordinateY + height;
+    gerber_update_min_and_max(&currentNet->boundingBox, currentNet->stop_x, currentNet->stop_y, 0, 0, 0, 0);
+    gerber_update_image_min_max(&currentNet->boundingBox, 0, 0, image);
+
+    currentNet                 = gerber_create_new_net(currentNet, NULL, NULL);
+    currentNet->interpolation  = GERBV_INTERPOLATION_LINEARx1;
+    currentNet->aperture_state = GERBV_APERTURE_STATE_ON;
+    currentNet->stop_x         = coordinateX;
+    currentNet->stop_y         = coordinateY + height;
+    gerber_update_min_and_max(&currentNet->boundingBox, currentNet->stop_x, currentNet->stop_y, 0, 0, 0, 0);
+    gerber_update_image_min_max(&currentNet->boundingBox, 0, 0, image);
+
+    currentNet                 = gerber_create_new_net(currentNet, NULL, NULL);
+    currentNet->interpolation  = GERBV_INTERPOLATION_LINEARx1;
+    currentNet->aperture_state = GERBV_APERTURE_STATE_ON;
+    currentNet->stop_x         = coordinateX;
+    currentNet->stop_y         = coordinateY;
+    gerber_update_min_and_max(&currentNet->boundingBox, currentNet->stop_x, currentNet->stop_y, 0, 0, 0, 0);
+    gerber_update_image_min_max(&currentNet->boundingBox, 0, 0, image);
+
+    /* create the polygon end node */
+    currentNet                = gerber_create_new_net(currentNet, NULL, NULL);
+    currentNet->interpolation = GERBV_INTERPOLATION_PAREA_END;
+
+    return;
 }
 
-gerbv_net_t *
-gerb_image_return_aperture_index (gerbv_image_t *image, gdouble lineWidth, int *apertureIndex){
-	gerbv_net_t *currentNet;
-	gerbv_aperture_t *aperture=NULL;
-	int i;
-		
-	/* run through and find last net pointer */
-	for (currentNet = image->netlist; currentNet->next; currentNet = currentNet->next){}
-	
-	/* try to find an existing aperture that matches the requested width and type */
-	for (i = 0; i < APERTURE_MAX; i++) {
-		if (image->aperture[i] != NULL) {
-			if ((image->aperture[i]->type == GERBV_APTYPE_CIRCLE) && 
-				(fabs (image->aperture[i]->parameter[0] - lineWidth) < 0.001)){
-				aperture = image->aperture[i];
-				*apertureIndex = i;
-				break;
-			}
-		}
-	}
-
-	if (!aperture) {
-		/* we didn't find a useable old aperture, so create a new one */
-		if (!gerber_create_new_aperture (image, apertureIndex,
-				GERBV_APTYPE_CIRCLE, lineWidth, 0)) {
-			/* if we didn't succeed, then return */
-			return FALSE;
-		}
-	}
-	return currentNet;
+gerbv_net_t*
+gerb_image_return_aperture_index(gerbv_image_t* image, gdouble lineWidth, int* apertureIndex) {
+    gerbv_net_t*      currentNet;
+    gerbv_aperture_t* aperture = NULL;
+    int               i;
+
+    /* run through and find last net pointer */
+    for (currentNet = image->netlist; currentNet->next; currentNet = currentNet->next) {}
+
+    /* try to find an existing aperture that matches the requested width and type */
+    for (i = 0; i < APERTURE_MAX; i++) {
+        if (image->aperture[i] != NULL) {
+            if ((image->aperture[i]->type == GERBV_APTYPE_CIRCLE)
+                && (fabs(image->aperture[i]->parameter[0] - lineWidth) < 0.001)) {
+                aperture       = image->aperture[i];
+                *apertureIndex = i;
+                break;
+            }
+        }
+    }
+
+    if (!aperture) {
+        /* we didn't find a useable old aperture, so create a new one */
+        if (!gerber_create_new_aperture(image, apertureIndex, GERBV_APTYPE_CIRCLE, lineWidth, 0)) {
+            /* if we didn't succeed, then return */
+            return FALSE;
+        }
+    }
+    return currentNet;
 }
 
 void
-gerbv_image_create_arc_object (gerbv_image_t *image, gdouble centerX, gdouble centerY,
-		gdouble radius, gdouble startAngle, gdouble endAngle, gdouble lineWidth,
-		gerbv_aperture_type_t apertureType) {
-	int apertureIndex;
-	gerbv_net_t *currentNet;
-	gerbv_cirseg_t cirSeg = {centerX, centerY, radius, radius, startAngle, endAngle};
-	
-	currentNet = gerb_image_return_aperture_index(image, lineWidth, &apertureIndex);
-	
-	if (!currentNet)
-		return;
-	
-	/* draw the arc */
-	currentNet = gerber_create_new_net (currentNet, NULL, NULL);
-	currentNet->interpolation = GERBV_INTERPOLATION_CCW_CIRCULAR;
-	currentNet->aperture_state = GERBV_APERTURE_STATE_ON;
-	currentNet->aperture = apertureIndex;
-	currentNet->start_x = centerX + (cos(DEG2RAD(startAngle)) * radius);
-	currentNet->start_y = centerY + (sin(DEG2RAD(startAngle)) * radius);
-	currentNet->stop_x = centerX + (cos(DEG2RAD(endAngle)) * radius);
-	currentNet->stop_y = centerY + (sin(DEG2RAD(endAngle)) * radius);
-	currentNet->cirseg = g_new0 (gerbv_cirseg_t,1);
-	*(currentNet->cirseg) = cirSeg;
-	
-	gdouble angleDiff = currentNet->cirseg->angle2 - currentNet->cirseg->angle1;
-	gint i, steps = abs(angleDiff);
-	for (i=0; i<=steps; i++){
-		gdouble tempX = currentNet->cirseg->cp_x + currentNet->cirseg->width / 2.0 *
-				cos (DEG2RAD(currentNet->cirseg->angle1 +
-						(i*angleDiff)/steps));
-		gdouble tempY = currentNet->cirseg->cp_y + currentNet->cirseg->width / 2.0 *
-				sin (DEG2RAD(currentNet->cirseg->angle1 +
-						(i*angleDiff)/steps));
-		gerber_update_min_and_max (&currentNet->boundingBox,
-			       tempX, tempY, 
-			       lineWidth/2,lineWidth/2,
-			       lineWidth/2,lineWidth/2);
-	}
-	gerber_update_image_min_max (&currentNet->boundingBox, 0, 0, image);	
-	return;
+gerbv_image_create_arc_object(
+    gerbv_image_t* image, gdouble centerX, gdouble centerY, gdouble radius, gdouble startAngle, gdouble endAngle,
+    gdouble lineWidth, gerbv_aperture_type_t apertureType
+) {
+    int            apertureIndex;
+    gerbv_net_t*   currentNet;
+    gerbv_cirseg_t cirSeg = { centerX, centerY, radius, radius, startAngle, endAngle };
+
+    currentNet = gerb_image_return_aperture_index(image, lineWidth, &apertureIndex);
+
+    if (!currentNet)
+        return;
+
+    /* draw the arc */
+    currentNet                 = gerber_create_new_net(currentNet, NULL, NULL);
+    currentNet->interpolation  = GERBV_INTERPOLATION_CCW_CIRCULAR;
+    currentNet->aperture_state = GERBV_APERTURE_STATE_ON;
+    currentNet->aperture       = apertureIndex;
+    currentNet->start_x        = centerX + (cos(DEG2RAD(startAngle)) * radius);
+    currentNet->start_y        = centerY + (sin(DEG2RAD(startAngle)) * radius);
+    currentNet->stop_x         = centerX + (cos(DEG2RAD(endAngle)) * radius);
+    currentNet->stop_y         = centerY + (sin(DEG2RAD(endAngle)) * radius);
+    currentNet->cirseg         = g_new0(gerbv_cirseg_t, 1);
+    *(currentNet->cirseg)      = cirSeg;
+
+    gdouble angleDiff = currentNet->cirseg->angle2 - currentNet->cirseg->angle1;
+    gint    i, steps = abs(angleDiff);
+    for (i = 0; i <= steps; i++) {
+        gdouble tempX =
+            currentNet->cirseg->cp_x
+            + currentNet->cirseg->width / 2.0 * cos(DEG2RAD(currentNet->cirseg->angle1 + (i * angleDiff) / steps));
+        gdouble tempY =
+            currentNet->cirseg->cp_y
+            + currentNet->cirseg->width / 2.0 * sin(DEG2RAD(currentNet->cirseg->angle1 + (i * angleDiff) / steps));
+        gerber_update_min_and_max(
+            &currentNet->boundingBox, tempX, tempY, lineWidth / 2, lineWidth / 2, lineWidth / 2, lineWidth / 2
+        );
+    }
+    gerber_update_image_min_max(&currentNet->boundingBox, 0, 0, image);
+    return;
 }
 
 void
-gerbv_image_create_line_object (gerbv_image_t *image, gdouble startX, gdouble startY,
-		gdouble endX, gdouble endY, gdouble lineWidth, gerbv_aperture_type_t apertureType) {
-	int apertureIndex;
-	gerbv_net_t *currentNet;
-	
-	currentNet = gerb_image_return_aperture_index(image, lineWidth, &apertureIndex);
-	
-	if (!currentNet)
-		return;
-	
-	/* draw the line */
-	currentNet = gerber_create_new_net (currentNet, NULL, NULL);
-	currentNet->interpolation = GERBV_INTERPOLATION_LINEARx1;
-	
-	/* if the start and end coordinates are the same, use a "flash" aperture state */
-	if ((fabs(startX - endX) < 0.001) && (fabs(startY - endY) < 0.001))
-		currentNet->aperture_state = GERBV_APERTURE_STATE_FLASH;
-	else
-		currentNet->aperture_state = GERBV_APERTURE_STATE_ON;
-	currentNet->aperture = apertureIndex;
-	currentNet->start_x = startX;
-	currentNet->start_y = startY;
-	currentNet->stop_x = endX;
-	currentNet->stop_y = endY;
-
-	gerber_update_min_and_max (&currentNet->boundingBox,currentNet->stop_x,currentNet->stop_y, 
-		lineWidth/2,lineWidth/2,lineWidth/2,lineWidth/2);
-	gerber_update_min_and_max (&currentNet->boundingBox,currentNet->start_x,currentNet->start_y, 
-		lineWidth/2,lineWidth/2,lineWidth/2,lineWidth/2);
-	gerber_update_image_min_max (&currentNet->boundingBox, 0, 0, image);
-	return;
+gerbv_image_create_line_object(
+    gerbv_image_t* image, gdouble startX, gdouble startY, gdouble endX, gdouble endY, gdouble lineWidth,
+    gerbv_aperture_type_t apertureType
+) {
+    int          apertureIndex;
+    gerbv_net_t* currentNet;
+
+    currentNet = gerb_image_return_aperture_index(image, lineWidth, &apertureIndex);
+
+    if (!currentNet)
+        return;
+
+    /* draw the line */
+    currentNet                = gerber_create_new_net(currentNet, NULL, NULL);
+    currentNet->interpolation = GERBV_INTERPOLATION_LINEARx1;
+
+    /* if the start and end coordinates are the same, use a "flash" aperture state */
+    if ((fabs(startX - endX) < 0.001) && (fabs(startY - endY) < 0.001))
+        currentNet->aperture_state = GERBV_APERTURE_STATE_FLASH;
+    else
+        currentNet->aperture_state = GERBV_APERTURE_STATE_ON;
+    currentNet->aperture = apertureIndex;
+    currentNet->start_x  = startX;
+    currentNet->start_y  = startY;
+    currentNet->stop_x   = endX;
+    currentNet->stop_y   = endY;
+
+    gerber_update_min_and_max(
+        &currentNet->boundingBox, currentNet->stop_x, currentNet->stop_y, lineWidth / 2, lineWidth / 2, lineWidth / 2,
+        lineWidth / 2
+    );
+    gerber_update_min_and_max(
+        &currentNet->boundingBox, currentNet->start_x, currentNet->start_y, lineWidth / 2, lineWidth / 2, lineWidth / 2,
+        lineWidth / 2
+    );
+    gerber_update_image_min_max(&currentNet->boundingBox, 0, 0, image);
+    return;
 }
 
 void
-gerbv_image_create_window_pane_objects (gerbv_image_t *image, gdouble lowerLeftX,
-		gdouble lowerLeftY, gdouble width, gdouble height, gdouble areaReduction,
-		gint paneRows, gint paneColumns, gdouble paneSeparation){
-	int i,j;
-	gdouble startX,startY,boxWidth,boxHeight;
-	
-	startX = lowerLeftX + (areaReduction * width) / 2.0;
-	startY = lowerLeftY + (areaReduction * height) / 2.0;
-	boxWidth = (width * (1.0 - areaReduction) - (paneSeparation * (paneColumns - 1))) / paneColumns;
-	boxHeight = (height * (1.0 - areaReduction) - (paneSeparation * (paneRows - 1))) / paneRows;
-	
-	for (i=0; i<paneColumns; i++){
-		for (j=0; j<paneRows; j++) {
-			gerbv_image_create_rectangle_object (image, startX + (i * (boxWidth + paneSeparation)),
-				startY + (j * (boxHeight + paneSeparation)),boxWidth, boxHeight);
-		}
-	}
-
-	return;
+gerbv_image_create_window_pane_objects(
+    gerbv_image_t* image, gdouble lowerLeftX, gdouble lowerLeftY, gdouble width, gdouble height, gdouble areaReduction,
+    gint paneRows, gint paneColumns, gdouble paneSeparation
+) {
+    int     i, j;
+    gdouble startX, startY, boxWidth, boxHeight;
+
+    startX    = lowerLeftX + (areaReduction * width) / 2.0;
+    startY    = lowerLeftY + (areaReduction * height) / 2.0;
+    boxWidth  = (width * (1.0 - areaReduction) - (paneSeparation * (paneColumns - 1))) / paneColumns;
+    boxHeight = (height * (1.0 - areaReduction) - (paneSeparation * (paneRows - 1))) / paneRows;
+
+    for (i = 0; i < paneColumns; i++) {
+        for (j = 0; j < paneRows; j++) {
+            gerbv_image_create_rectangle_object(
+                image, startX + (i * (boxWidth + paneSeparation)), startY + (j * (boxHeight + paneSeparation)),
+                boxWidth, boxHeight
+            );
+        }
+    }
+
+    return;
 }
-		
+
 gboolean
-gerbv_image_reduce_area_of_selected_objects (GArray *selectionArray,
-		gdouble areaReduction, gint paneRows, gint paneColumns, gdouble paneSeparation){
-	gdouble minX,minY,maxX,maxY;
-	
-	for (guint i=0; i<selectionArray->len; i++) {
-		gerbv_selection_item_t sItem = g_array_index (selectionArray,gerbv_selection_item_t, i);
-		gerbv_image_t *image = sItem.image;
-		gerbv_net_t *currentNet = sItem.net;
-		
-		/* determine the object type first */
-		minX = HUGE_VAL;
-		maxX = -HUGE_VAL;
-		minY = HUGE_VAL;
-		maxY = -HUGE_VAL;
-		
-		switch (currentNet->interpolation) {
-		case GERBV_INTERPOLATION_PAREA_START:
-			/* if it's a polygon, just determine the overall area of it and delete it */
-			currentNet->interpolation = GERBV_INTERPOLATION_DELETED;
-			
-			for (currentNet = currentNet->next; currentNet; currentNet = currentNet->next){
-				if (currentNet->interpolation == GERBV_INTERPOLATION_PAREA_END)
-					break;
-				currentNet->interpolation = GERBV_INTERPOLATION_DELETED;
-				if (currentNet->stop_x < minX)
-					minX = currentNet->stop_x;
-				if (currentNet->stop_y < minY)
-					minY = currentNet->stop_y;
-				if (currentNet->stop_x > maxX)
-					maxX = currentNet->stop_x;
-				if (currentNet->stop_y > maxY)
-					maxY = currentNet->stop_y;
-			}
-			currentNet->interpolation = GERBV_INTERPOLATION_DELETED;
-
-			break;
-
-		case GERBV_INTERPOLATION_LINEARx1:
-		case GERBV_INTERPOLATION_LINEARx10:
-		case GERBV_INTERPOLATION_LINEARx01:
-		case GERBV_INTERPOLATION_LINEARx001: {
-			gdouble dx=0,dy=0;
-			gerbv_aperture_t *apert =
-				image->aperture[currentNet->aperture];
-
-			/* figure out the overall size of this element */
-			switch (apert->type) {
-			case GERBV_APTYPE_CIRCLE :
-			case GERBV_APTYPE_OVAL :
-			case GERBV_APTYPE_POLYGON :
-				dx = dy = apert->parameter[0];
-				break;
-			case GERBV_APTYPE_RECTANGLE :
-				dx = apert->parameter[0]/2;
-				dy = apert->parameter[1]/2;
-				break;
-			default :
-				break;
-			}
-			if (currentNet->start_x-dx < minX)
-				minX = currentNet->start_x-dx;
-			if (currentNet->start_y-dy < minY)
-				minY = currentNet->start_y-dy;
-			if (currentNet->start_x+dx > maxX)
-				maxX = currentNet->start_x+dx;
-			if (currentNet->start_y+dy > maxY)
-				maxY = currentNet->start_y+dy;
-				
-			if (currentNet->stop_x-dx < minX)
-				minX = currentNet->stop_x-dx;
-			if (currentNet->stop_y-dy < minY)
-				minY = currentNet->stop_y-dy;
-			if (currentNet->stop_x+dx > maxX)
-				maxX = currentNet->stop_x+dx;
-			if (currentNet->stop_y+dy > maxY)
-				maxY = currentNet->stop_y+dy;
-			
-			/* finally, delete node */
-			currentNet->interpolation = GERBV_INTERPOLATION_DELETED;
-
-			break;
-		}
-
-		default:
-			/* we don't current support arcs */
-			return FALSE;
-		}
-		
-		/* create new structures */
-		gerbv_image_create_window_pane_objects (image, minX, minY, maxX - minX, maxY - minY,
-			areaReduction, paneRows, paneColumns, paneSeparation);
-	}
-	return TRUE;
+gerbv_image_reduce_area_of_selected_objects(
+    GArray* selectionArray, gdouble areaReduction, gint paneRows, gint paneColumns, gdouble paneSeparation
+) {
+    gdouble minX, minY, maxX, maxY;
+
+    for (guint i = 0; i < selectionArray->len; i++) {
+        gerbv_selection_item_t sItem      = g_array_index(selectionArray, gerbv_selection_item_t, i);
+        gerbv_image_t*         image      = sItem.image;
+        gerbv_net_t*           currentNet = sItem.net;
+
+        /* determine the object type first */
+        minX = HUGE_VAL;
+        maxX = -HUGE_VAL;
+        minY = HUGE_VAL;
+        maxY = -HUGE_VAL;
+
+        switch (currentNet->interpolation) {
+            case GERBV_INTERPOLATION_PAREA_START:
+                /* if it's a polygon, just determine the overall area of it and delete it */
+                currentNet->interpolation = GERBV_INTERPOLATION_DELETED;
+
+                for (currentNet = currentNet->next; currentNet; currentNet = currentNet->next) {
+                    if (currentNet->interpolation == GERBV_INTERPOLATION_PAREA_END)
+                        break;
+                    currentNet->interpolation = GERBV_INTERPOLATION_DELETED;
+                    if (currentNet->stop_x < minX)
+                        minX = currentNet->stop_x;
+                    if (currentNet->stop_y < minY)
+                        minY = currentNet->stop_y;
+                    if (currentNet->stop_x > maxX)
+                        maxX = currentNet->stop_x;
+                    if (currentNet->stop_y > maxY)
+                        maxY = currentNet->stop_y;
+                }
+                currentNet->interpolation = GERBV_INTERPOLATION_DELETED;
+
+                break;
+
+            case GERBV_INTERPOLATION_LINEARx1:
+            case GERBV_INTERPOLATION_LINEARx10:
+            case GERBV_INTERPOLATION_LINEARx01:
+            case GERBV_INTERPOLATION_LINEARx001:
+                {
+                    gdouble           dx = 0, dy = 0;
+                    gerbv_aperture_t* apert = image->aperture[currentNet->aperture];
+
+                    /* figure out the overall size of this element */
+                    switch (apert->type) {
+                        case GERBV_APTYPE_CIRCLE:
+                        case GERBV_APTYPE_OVAL:
+                        case GERBV_APTYPE_POLYGON: dx = dy = apert->parameter[0]; break;
+                        case GERBV_APTYPE_RECTANGLE:
+                            dx = apert->parameter[0] / 2;
+                            dy = apert->parameter[1] / 2;
+                            break;
+                        default: break;
+                    }
+                    if (currentNet->start_x - dx < minX)
+                        minX = currentNet->start_x - dx;
+                    if (currentNet->start_y - dy < minY)
+                        minY = currentNet->start_y - dy;
+                    if (currentNet->start_x + dx > maxX)
+                        maxX = currentNet->start_x + dx;
+                    if (currentNet->start_y + dy > maxY)
+                        maxY = currentNet->start_y + dy;
+
+                    if (currentNet->stop_x - dx < minX)
+                        minX = currentNet->stop_x - dx;
+                    if (currentNet->stop_y - dy < minY)
+                        minY = currentNet->stop_y - dy;
+                    if (currentNet->stop_x + dx > maxX)
+                        maxX = currentNet->stop_x + dx;
+                    if (currentNet->stop_y + dy > maxY)
+                        maxY = currentNet->stop_y + dy;
+
+                    /* finally, delete node */
+                    currentNet->interpolation = GERBV_INTERPOLATION_DELETED;
+
+                    break;
+                }
+
+            default:
+                /* we don't current support arcs */
+                return FALSE;
+        }
+
+        /* create new structures */
+        gerbv_image_create_window_pane_objects(
+            image, minX, minY, maxX - minX, maxY - minY, areaReduction, paneRows, paneColumns, paneSeparation
+        );
+    }
+    return TRUE;
 }
 
 gboolean
-gerbv_image_move_selected_objects (GArray *selectionArray, gdouble translationX,
-		gdouble translationY)
-{
-	for (guint i=0; i<selectionArray->len; i++) {
-		gerbv_selection_item_t sItem = g_array_index (selectionArray,gerbv_selection_item_t, i);
-		gerbv_net_t *currentNet = sItem.net;
-
-		if (currentNet->interpolation == GERBV_INTERPOLATION_PAREA_START) {
-			/* if it's a polygon, step through every vertex and translate the point */
-			for (currentNet = currentNet->next; currentNet; currentNet = currentNet->next){
-				if (currentNet->interpolation == GERBV_INTERPOLATION_PAREA_END)
-					break;
-				currentNet->start_x += translationX;
-				currentNet->start_y += translationY;
-				currentNet->stop_x += translationX;
-				currentNet->stop_y += translationY;
-			}
-		}
-		else {
-			/* otherwise, just move the single element */
-			currentNet->start_x += translationX;
-			currentNet->start_y += translationY;
-			currentNet->stop_x += translationX;
-			currentNet->stop_y += translationY;
-		}
-	}
-	return TRUE;
+gerbv_image_move_selected_objects(GArray* selectionArray, gdouble translationX, gdouble translationY) {
+    for (guint i = 0; i < selectionArray->len; i++) {
+        gerbv_selection_item_t sItem      = g_array_index(selectionArray, gerbv_selection_item_t, i);
+        gerbv_net_t*           currentNet = sItem.net;
+
+        if (currentNet->interpolation == GERBV_INTERPOLATION_PAREA_START) {
+            /* if it's a polygon, step through every vertex and translate the point */
+            for (currentNet = currentNet->next; currentNet; currentNet = currentNet->next) {
+                if (currentNet->interpolation == GERBV_INTERPOLATION_PAREA_END)
+                    break;
+                currentNet->start_x += translationX;
+                currentNet->start_y += translationY;
+                currentNet->stop_x += translationX;
+                currentNet->stop_y += translationY;
+            }
+        } else {
+            /* otherwise, just move the single element */
+            currentNet->start_x += translationX;
+            currentNet->start_y += translationY;
+            currentNet->stop_x += translationX;
+            currentNet->stop_y += translationY;
+        }
+    }
+    return TRUE;
 }
 
-gerbv_net_t *
-gerbv_image_return_next_renderable_object (gerbv_net_t *oldNet) {
-	gerbv_net_t *currentNet=oldNet;
-	
-	if (currentNet->interpolation == GERBV_INTERPOLATION_PAREA_START) {
-		/* if it's a polygon, step to the next non-polygon net */
-		for (currentNet = currentNet->next; currentNet; currentNet = currentNet->next){
-			if (currentNet->interpolation == GERBV_INTERPOLATION_PAREA_END) {
-				return currentNet->next;
-			}
-		}
-		return NULL;
-	}
-	else {
-		return currentNet->next;
-	}
+gerbv_net_t*
+gerbv_image_return_next_renderable_object(gerbv_net_t* oldNet) {
+    gerbv_net_t* currentNet = oldNet;
+
+    if (currentNet->interpolation == GERBV_INTERPOLATION_PAREA_START) {
+        /* if it's a polygon, step to the next non-polygon net */
+        for (currentNet = currentNet->next; currentNet; currentNet = currentNet->next) {
+            if (currentNet->interpolation == GERBV_INTERPOLATION_PAREA_END) {
+                return currentNet->next;
+            }
+        }
+        return NULL;
+    } else {
+        return currentNet->next;
+    }
 }
 
 void
-gerbv_image_create_dummy_apertures (gerbv_image_t *parsed_image) {
-	gerbv_net_t *currentNet;
-		
-	/* run through and find last net pointer */
-	for (currentNet = parsed_image->netlist; currentNet->next; currentNet = currentNet->next){
-		if (parsed_image->aperture[currentNet->aperture] == NULL) {
-			parsed_image->aperture[currentNet->aperture] = g_new0 (gerbv_aperture_t, 1);
-			parsed_image->aperture[currentNet->aperture]->type = GERBV_APTYPE_CIRCLE;
-			parsed_image->aperture[currentNet->aperture]->parameter[0] = 0;
-			parsed_image->aperture[currentNet->aperture]->parameter[1] = 0;
-		}
-	}
+gerbv_image_create_dummy_apertures(gerbv_image_t* parsed_image) {
+    gerbv_net_t* currentNet;
+
+    /* run through and find last net pointer */
+    for (currentNet = parsed_image->netlist; currentNet->next; currentNet = currentNet->next) {
+        if (parsed_image->aperture[currentNet->aperture] == NULL) {
+            parsed_image->aperture[currentNet->aperture]               = g_new0(gerbv_aperture_t, 1);
+            parsed_image->aperture[currentNet->aperture]->type         = GERBV_APTYPE_CIRCLE;
+            parsed_image->aperture[currentNet->aperture]->parameter[0] = 0;
+            parsed_image->aperture[currentNet->aperture]->parameter[1] = 0;
+        }
+    }
 }
diff --git a/src/gerb_image.h b/src/gerb_image.h
index ad4e815..607733b 100644
--- a/src/gerb_image.h
+++ b/src/gerb_image.h
@@ -50,25 +50,22 @@ extern "C" {
  * 8: Missing info
  * It could be any of above or'ed together
  */
-typedef enum { 
-    GERB_IMAGE_OK = 0,
-    GERB_IMAGE_MISSING_NETLIST = 1,
-    GERB_IMAGE_MISSING_FORMAT = 2, 
+typedef enum {
+    GERB_IMAGE_OK                = 0,
+    GERB_IMAGE_MISSING_NETLIST   = 1,
+    GERB_IMAGE_MISSING_FORMAT    = 2,
     GERB_IMAGE_MISSING_APERTURES = 4,
-    GERB_IMAGE_MISSING_INFO = 8,
+    GERB_IMAGE_MISSING_INFO      = 8,
 } gerb_verify_error_t;
 
-gerb_verify_error_t gerbv_image_verify(gerbv_image_t const* image);
+gerb_verify_error_t gerbv_image_verify(const gerbv_image_t* image);
 
 /* Dumps a written version of image to stdout */
-void gerbv_image_dump(gerbv_image_t const* image);
+void gerbv_image_dump(const gerbv_image_t* image);
 
-gerbv_layer_t *
-gerbv_image_return_new_layer (gerbv_layer_t *previousLayer);
-
-gerbv_netstate_t *
-gerbv_image_return_new_netstate (gerbv_netstate_t *previousState);
+gerbv_layer_t* gerbv_image_return_new_layer(gerbv_layer_t* previousLayer);
 
+gerbv_netstate_t* gerbv_image_return_new_netstate(gerbv_netstate_t* previousState);
 
 #ifdef __cplusplus
 }
diff --git a/src/gerb_stats.c b/src/gerb_stats.c
index cebfded..03550fd 100644
--- a/src/gerb_stats.c
+++ b/src/gerb_stats.c
@@ -35,18 +35,20 @@
 #include "common.h"
 #include "gerb_stats.h"
 
-#define dprintf if(DEBUG) printf
+#define dprintf \
+    if (DEBUG)  \
+    printf
 
 /* ------------------------------------------------------- */
 /** Allocates a new gerbv_stats structure
    @return gerbv_stats pointer on success, NULL on ERROR */
-gerbv_stats_t *
+gerbv_stats_t*
 gerbv_stats_new(void) {
 
-    gerbv_stats_t *stats;
-    gerbv_error_list_t *error_list;
-    gerbv_aperture_list_t *aperture_list;
-    gerbv_aperture_list_t *D_code_list;
+    gerbv_stats_t*         stats;
+    gerbv_error_list_t*    error_list;
+    gerbv_aperture_list_t* aperture_list;
+    gerbv_aperture_list_t* D_code_list;
 
     /* Malloc space for new stats struct.  Return NULL if error. */
     if (NULL == (stats = g_new0(gerbv_stats_t, 1))) {
@@ -57,75 +59,72 @@ gerbv_stats_new(void) {
     error_list = gerbv_stats_new_error_list();
     if (error_list == NULL)
         GERB_FATAL_ERROR("malloc error_list failed in %s()", __FUNCTION__);
-    stats->error_list = (gerbv_error_list_t *) error_list;
+    stats->error_list = (gerbv_error_list_t*)error_list;
 
     /* Initialize aperture list */
     aperture_list = gerbv_stats_new_aperture_list();
     if (aperture_list == NULL)
         GERB_FATAL_ERROR("malloc aperture_list failed in %s()", __FUNCTION__);
-    stats->aperture_list = (gerbv_aperture_list_t *) aperture_list;
+    stats->aperture_list = (gerbv_aperture_list_t*)aperture_list;
 
     /* Initialize D codes list */
     D_code_list = gerbv_stats_new_aperture_list();
     if (D_code_list == NULL)
         GERB_FATAL_ERROR("malloc D_code_list failed in %s()", __FUNCTION__);
-    stats->D_code_list = (gerbv_aperture_list_t *) D_code_list;
+    stats->D_code_list = (gerbv_aperture_list_t*)D_code_list;
 
     return stats;
 }
 
 void
-gerbv_destroy_error_list (gerbv_error_list_t *errorList) {
-	gerbv_error_list_t *nextError=errorList,*tempError;
-	
-	while (nextError) {
-		tempError = nextError->next;
-		g_free (nextError->error_text);
-		g_free (nextError);
-		nextError = tempError;
-	}
+gerbv_destroy_error_list(gerbv_error_list_t* errorList) {
+    gerbv_error_list_t *nextError = errorList, *tempError;
+
+    while (nextError) {
+        tempError = nextError->next;
+        g_free(nextError->error_text);
+        g_free(nextError);
+        nextError = tempError;
+    }
 }
 
 void
-gerbv_destroy_aperture_list (gerbv_aperture_list_t *apertureList) {
-	gerbv_aperture_list_t *nextAperture=apertureList,*tempAperture;
-	
-	while (nextAperture) {
-		tempAperture = nextAperture->next;
-		g_free (nextAperture);
-		nextAperture = tempAperture;
-	}
+gerbv_destroy_aperture_list(gerbv_aperture_list_t* apertureList) {
+    gerbv_aperture_list_t *nextAperture = apertureList, *tempAperture;
+
+    while (nextAperture) {
+        tempAperture = nextAperture->next;
+        g_free(nextAperture);
+        nextAperture = tempAperture;
+    }
 }
 
 /* ------------------------------------------------------- */
 void
-gerbv_stats_destroy(gerbv_stats_t *stats) {
-	if (stats == NULL)
-		return;
-	gerbv_destroy_error_list (stats->error_list);
-	gerbv_destroy_aperture_list (stats->aperture_list);
-	gerbv_destroy_aperture_list (stats->D_code_list);
-	g_free (stats);
-}	
-
+gerbv_stats_destroy(gerbv_stats_t* stats) {
+    if (stats == NULL)
+        return;
+    gerbv_destroy_error_list(stats->error_list);
+    gerbv_destroy_aperture_list(stats->aperture_list);
+    gerbv_destroy_aperture_list(stats->D_code_list);
+    g_free(stats);
+}
 
 /* ------------------------------------------------------- */
 /*! This fcn is called with a two gerbv_stats_t structs:
- * accum_stats and input_stats.  Accum_stats holds 
+ * accum_stats and input_stats.  Accum_stats holds
  * a list of stats accumulated for
  * all layers.  This will be reported in the report window.
  * Input_stats holds a list of the stats for one particular layer
  * to be added to the accumulated list.  */
 void
-gerbv_stats_add_layer(gerbv_stats_t *accum_stats, 
-		     gerbv_stats_t *input_stats,
-		     int this_layer) {
-    
+gerbv_stats_add_layer(gerbv_stats_t* accum_stats, gerbv_stats_t* input_stats, int this_layer) {
+
     dprintf("---> Entering gerbv_stats_add_layer ... \n");
 
-    gerbv_error_list_t *error;
-    gerbv_aperture_list_t *aperture;
-    gerbv_aperture_list_t *D_code;
+    gerbv_error_list_t*    error;
+    gerbv_aperture_list_t* aperture;
+    gerbv_aperture_list_t* D_code;
 
     accum_stats->layer_count++;
     accum_stats->G0 += input_stats->G0;
@@ -152,21 +151,21 @@ gerbv_stats_add_layer(gerbv_stats_t *accum_stats,
     accum_stats->D2 += input_stats->D2;
     accum_stats->D3 += input_stats->D3;
     /* Create list of user-defined D codes from aperture list */
-    for (D_code = input_stats->D_code_list;
-         D_code != NULL;
-         D_code = D_code->next) {
+    for (D_code = input_stats->D_code_list; D_code != NULL; D_code = D_code->next) {
         if (D_code->number != -1) {
-	  dprintf("     .... In gerbv_stats_add_layer, D code section, adding number = %d to accum_stats D list ...\n",
-		  D_code->number);
-	  gerbv_stats_add_to_D_list(accum_stats->D_code_list,
-				   D_code->number);
-	  dprintf("     .... In gerbv_stats_add_layer, D code section, calling increment_D_count with count %d ...\n", 
-		  D_code->count);
-	  gerbv_stats_increment_D_list_count(accum_stats->D_code_list,
-					    D_code->number,
-					    D_code->count,
-					    accum_stats->error_list);
-      }
+            dprintf(
+                "     .... In gerbv_stats_add_layer, D code section, adding number = %d to accum_stats D list ...\n",
+                D_code->number
+            );
+            gerbv_stats_add_to_D_list(accum_stats->D_code_list, D_code->number);
+            dprintf(
+                "     .... In gerbv_stats_add_layer, D code section, calling increment_D_count with count %d ...\n",
+                D_code->count
+            );
+            gerbv_stats_increment_D_list_count(
+                accum_stats->D_code_list, D_code->number, D_code->count, accum_stats->error_list
+            );
+        }
     }
     accum_stats->D_unknown += input_stats->D_unknown;
     accum_stats->D_error += input_stats->D_error;
@@ -185,27 +184,18 @@ gerbv_stats_add_layer(gerbv_stats_t *accum_stats,
     accum_stats->unknown += input_stats->unknown;
 
     /* ==== Now deal with the error list ==== */
-    for (error = input_stats->error_list;
-         error != NULL;
-         error = error->next) {
+    for (error = input_stats->error_list; error != NULL; error = error->next) {
         if (error->error_text != NULL) {
-            gerbv_stats_add_error(accum_stats->error_list,
-                                  this_layer,
-                                  error->error_text,
-                                  error->type);
+            gerbv_stats_add_error(accum_stats->error_list, this_layer, error->error_text, error->type);
         }
     }
 
     /* ==== Now deal with the aperture list ==== */
-    for (aperture = input_stats->aperture_list;
-         aperture != NULL;
-         aperture = aperture->next) {
+    for (aperture = input_stats->aperture_list; aperture != NULL; aperture = aperture->next) {
         if (aperture->number != -1) {
-            gerbv_stats_add_aperture(accum_stats->aperture_list,
-				    this_layer,
-				    aperture->number,
-				    aperture->type,
-				    aperture->parameter);
+            gerbv_stats_add_aperture(
+                accum_stats->aperture_list, this_layer, aperture->number, aperture->type, aperture->parameter
+            );
         }
     }
 
@@ -215,27 +205,25 @@ gerbv_stats_add_layer(gerbv_stats_t *accum_stats,
 }
 
 /* ------------------------------------------------------- */
-gerbv_error_list_t *
+gerbv_error_list_t*
 gerbv_stats_new_error_list() {
-    gerbv_error_list_t *error_list;
+    gerbv_error_list_t* error_list;
 
     /* Malloc space for new error_list struct.  Return NULL if error. */
     if (NULL == (error_list = g_new(gerbv_error_list_t, 1))) {
         return NULL;
     }
 
-    error_list->layer = -1;
+    error_list->layer      = -1;
     error_list->error_text = NULL;
-    error_list->next = NULL;
+    error_list->next       = NULL;
     return error_list;
 }
 
 /* ------------------------------------------------------- */
 void
-gerbv_stats_printf(gerbv_error_list_t *list, gerbv_message_type_t type,
-			int layer, const char *text, ...)
-{
-    gchar *str;
+gerbv_stats_printf(gerbv_error_list_t* list, gerbv_message_type_t type, int layer, const char* text, ...) {
+    gchar*  str;
     va_list args;
 
     va_start(args, text);
@@ -251,92 +239,60 @@ gerbv_stats_printf(gerbv_error_list_t *list, gerbv_message_type_t type,
  */
 /* ------------------------------------------------------- */
 int
-gerbv_escape_char_return_int(char c)
-{
-	int i = 0;
-	char *ec = (char *)&i;
-
-	ec[0] = '\\';
-
-	switch (c) {
-	case '\0':
-		ec[1] = '0';
-		break;
-	case '\a':
-		ec[1] = 'a';
-		break;
-	case '\b':
-		ec[1] = 'b';
-		break;
-	case '\f':
-		ec[1] = 'f';
-		break;
-	case '\n':
-		ec[1] = 'n';
-		break;
-	case '\r':
-		ec[1] = 'r';
-		break;
-	case '\t':
-		ec[1] = 't';
-		break;
-	case '\v':
-		ec[1] = 'v';
-		break;
-	case '\\':
-		ec[1] = '\\';
-		break;
-	case '"':
-		ec[1] = '"';
-		break;
-	default:
-		ec[0] = c;
-	}
-
-	return i;
+gerbv_escape_char_return_int(char c) {
+    int   i  = 0;
+    char* ec = (char*)&i;
+
+    ec[0] = '\\';
+
+    switch (c) {
+        case '\0': ec[1] = '0'; break;
+        case '\a': ec[1] = 'a'; break;
+        case '\b': ec[1] = 'b'; break;
+        case '\f': ec[1] = 'f'; break;
+        case '\n': ec[1] = 'n'; break;
+        case '\r': ec[1] = 'r'; break;
+        case '\t': ec[1] = 't'; break;
+        case '\v': ec[1] = 'v'; break;
+        case '\\': ec[1] = '\\'; break;
+        case '"': ec[1] = '"'; break;
+        default: ec[0] = c;
+    }
+
+    return i;
 }
 
 /* ------------------------------------------------------- */
 void
-gerbv_stats_add_error(gerbv_error_list_t *error_list_in,
-                      int layer, const char *error_text,
-                      gerbv_message_type_t type) {
+gerbv_stats_add_error(gerbv_error_list_t* error_list_in, int layer, const char* error_text, gerbv_message_type_t type) {
 
-    gerbv_error_list_t *error_list_new;
-    gerbv_error_list_t *error_last = NULL;
-    gerbv_error_list_t *error;
+    gerbv_error_list_t* error_list_new;
+    gerbv_error_list_t* error_last = NULL;
+    gerbv_error_list_t* error;
 
     /* Replace embedded error messages */
     switch (type) {
-        case GERBV_MESSAGE_FATAL:
-            GERB_FATAL_ERROR("%s",error_text);
-            break;
-        case GERBV_MESSAGE_ERROR:
-            GERB_COMPILE_ERROR("%s",error_text);
-            break;
-        case GERBV_MESSAGE_WARNING:
-            GERB_COMPILE_WARNING("%s",error_text);
-            break;
-        case GERBV_MESSAGE_NOTE:
-            break;
+        case GERBV_MESSAGE_FATAL: GERB_FATAL_ERROR("%s", error_text); break;
+        case GERBV_MESSAGE_ERROR: GERB_COMPILE_ERROR("%s", error_text); break;
+        case GERBV_MESSAGE_WARNING: GERB_COMPILE_WARNING("%s", error_text); break;
+        case GERBV_MESSAGE_NOTE: break;
     }
 
     /* First handle case where this is the first list element */
     if (error_list_in->error_text == NULL) {
-        error_list_in->layer = layer;
+        error_list_in->layer      = layer;
         error_list_in->error_text = g_strdup_printf("%s", error_text);
-        error_list_in->type = type;
-        error_list_in->next = NULL;
+        error_list_in->type       = type;
+        error_list_in->next       = NULL;
         return;
     }
 
     /* Next check to see if this error is already in the list */
-    for(error = error_list_in; error != NULL; error = error->next) {
-        if ((strcmp(error->error_text, error_text) == 0) &&
-            (error->layer == layer) ) {
-            return;  /* This error text is already in the error list */
+    for (error = error_list_in; error != NULL; error = error->next) {
+        if ((strcmp(error->error_text, error_text) == 0) && (error->layer == layer)) {
+            return; /* This error text is already in the error list */
         }
-        error_last = error;  /* point to last element in error list */
+        error_last = error; /* point to last element in error list */
     }
     /* This error text is unique.  Therefore, add it to the list */
 
@@ -346,20 +302,20 @@ gerbv_stats_add_error(gerbv_error_list_t *error_list_in,
     }
 
     /* Set member elements */
-    error_list_new->layer = layer;
+    error_list_new->layer      = layer;
     error_list_new->error_text = g_strdup_printf("%s", error_text);
-    error_list_new->type = type;
-    error_list_new->next = NULL;
-    error_last->next = error_list_new;
+    error_list_new->type       = type;
+    error_list_new->next       = NULL;
+    error_last->next           = error_list_new;
 
     return;
 }
 
 /* ------------------------------------------------------- */
-gerbv_aperture_list_t *
+gerbv_aperture_list_t*
 gerbv_stats_new_aperture_list() {
-    gerbv_aperture_list_t *aperture_list;
-    int i;
+    gerbv_aperture_list_t* aperture_list;
+    int                    i;
 
     dprintf("Mallocing new gerb aperture list\n");
     /* Malloc space for new aperture_list struct.  Return NULL if error. */
@@ -370,117 +326,110 @@ gerbv_stats_new_aperture_list() {
 
     dprintf("   Placing values in certain structs.\n");
     aperture_list->number = -1;
-    aperture_list->count = 0;
-    aperture_list->type = 0;
-    for (i = 0; i<5; i++) {
-	aperture_list->parameter[i] = 0.0;
+    aperture_list->count  = 0;
+    aperture_list->type   = 0;
+    for (i = 0; i < 5; i++) {
+        aperture_list->parameter[i] = 0.0;
     }
     aperture_list->next = NULL;
     return aperture_list;
 }
 
-
 /* ------------------------------------------------------- */
 void
-gerbv_stats_add_aperture(gerbv_aperture_list_t *aperture_list_in,
-			int layer, int number, gerbv_aperture_type_t type,
-			double parameter[5]) {
+gerbv_stats_add_aperture(
+    gerbv_aperture_list_t* aperture_list_in, int layer, int number, gerbv_aperture_type_t type, double parameter[5]
+) {
 
-    gerbv_aperture_list_t *aperture_list_new;
-    gerbv_aperture_list_t *aperture_last = NULL;
-    gerbv_aperture_list_t *aperture;
-    int i;
+    gerbv_aperture_list_t* aperture_list_new;
+    gerbv_aperture_list_t* aperture_last = NULL;
+    gerbv_aperture_list_t* aperture;
+    int                    i;
 
-    dprintf("   --->  Entering gerbv_stats_add_aperture ....\n"); 
+    dprintf("   --->  Entering gerbv_stats_add_aperture ....\n");
 
     /* First handle case where this is the first list element */
     if (aperture_list_in->number == -1) {
-	dprintf("     .... Adding first aperture to aperture list ... \n"); 
-	dprintf("     .... Aperture type = %d ... \n", type); 
+        dprintf("     .... Adding first aperture to aperture list ... \n");
+        dprintf("     .... Aperture type = %d ... \n", type);
         aperture_list_in->number = number;
-        aperture_list_in->type = type;
-	aperture_list_in->layer = layer;
-	for(i=0; i<5; i++) { 
-	    aperture_list_in->parameter[i] = parameter[i];
-	}
+        aperture_list_in->type   = type;
+        aperture_list_in->layer  = layer;
+        for (i = 0; i < 5; i++) {
+            aperture_list_in->parameter[i] = parameter[i];
+        }
         aperture_list_in->next = NULL;
-	dprintf("   <---  .... Leaving gerbv_stats_add_aperture.\n"); 
+        dprintf("   <---  .... Leaving gerbv_stats_add_aperture.\n");
         return;
     }
 
     /* Next check to see if this aperture is already in the list */
-    for(aperture = aperture_list_in; 
-	aperture != NULL; 
-	aperture = aperture->next) {
-        if ((aperture->number == number) &&
-            (aperture->layer == layer) ) {
-	  dprintf("     .... This aperture is already in the list ... \n"); 
-	    dprintf("   <---  .... Leaving gerbv_stats_add_aperture.\n"); 
-            return;  
+    for (aperture = aperture_list_in; aperture != NULL; aperture = aperture->next) {
+        if ((aperture->number == number) && (aperture->layer == layer)) {
+            dprintf("     .... This aperture is already in the list ... \n");
+            dprintf("   <---  .... Leaving gerbv_stats_add_aperture.\n");
+            return;
         }
-        aperture_last = aperture;  /* point to last element in list */
+        aperture_last = aperture; /* point to last element in list */
     }
     /* This aperture number is unique.  Therefore, add it to the list */
-    dprintf("     .... Adding another aperture to list ... \n"); 
-    dprintf("     .... Aperture type = %d ... \n", type); 
-	
+    dprintf("     .... Adding another aperture to list ... \n");
+    dprintf("     .... Aperture type = %d ... \n", type);
+
     /* Now malloc space for new aperture list element */
     if (NULL == (aperture_list_new = g_new(gerbv_aperture_list_t, 1))) {
         GERB_FATAL_ERROR("malloc aperture_list failed in %s()", __FUNCTION__);
     }
 
     /* Set member elements */
-    aperture_list_new->layer = layer;
+    aperture_list_new->layer  = layer;
     aperture_list_new->number = number;
-    aperture_list_new->type = type;
-    aperture_list_new->next = NULL;
-    for(i=0; i<5; i++) { 
-	aperture_list_new->parameter[i] = parameter[i];
+    aperture_list_new->type   = type;
+    aperture_list_new->next   = NULL;
+    for (i = 0; i < 5; i++) {
+        aperture_list_new->parameter[i] = parameter[i];
     }
     aperture_last->next = aperture_list_new;
 
-    dprintf("   <---  .... Leaving gerbv_stats_add_aperture.\n"); 
+    dprintf("   <---  .... Leaving gerbv_stats_add_aperture.\n");
 
     return;
 }
 
 /* ------------------------------------------------------- */
 void
-gerbv_stats_add_to_D_list(gerbv_aperture_list_t *D_list_in,
-			 int number) {
-  
-  gerbv_aperture_list_t *D_list;
-  gerbv_aperture_list_t *D_list_last=NULL;
-  gerbv_aperture_list_t *D_list_new;
+gerbv_stats_add_to_D_list(gerbv_aperture_list_t* D_list_in, int number) {
+
+    gerbv_aperture_list_t* D_list;
+    gerbv_aperture_list_t* D_list_last = NULL;
+    gerbv_aperture_list_t* D_list_new;
 
     dprintf("   ----> Entering add_to_D_list, numbr = %d\n", number);
 
     /* First handle case where this is the first list element */
     if (D_list_in->number == -1) {
-	dprintf("     .... Adding first D code to D code list ... \n"); 
-	dprintf("     .... Aperture number = %d ... \n", number); 
+        dprintf("     .... Adding first D code to D code list ... \n");
+        dprintf("     .... Aperture number = %d ... \n", number);
         D_list_in->number = number;
-	D_list_in->count = 0;
-        D_list_in->next = NULL;
-	dprintf("   <---  .... Leaving add_to_D_list.\n"); 
+        D_list_in->count  = 0;
+        D_list_in->next   = NULL;
+        dprintf("   <---  .... Leaving add_to_D_list.\n");
         return;
     }
 
     /* Look to see if this is already in list */
-    for(D_list = D_list_in; 
-	D_list != NULL; 
-	D_list = D_list->next) {
+    for (D_list = D_list_in; D_list != NULL; D_list = D_list->next) {
         if (D_list->number == number) {
-  	    dprintf("    .... Found in D list .... \n");
-	    dprintf("   <---  .... Leaving add_to_D_list.\n"); 
-            return;  
+            dprintf("    .... Found in D list .... \n");
+            dprintf("   <---  .... Leaving add_to_D_list.\n");
+            return;
         }
-        D_list_last = D_list;  /* point to last element in list */
+        D_list_last = D_list; /* point to last element in list */
     }
 
     /* This aperture number is unique.  Therefore, add it to the list */
-    dprintf("     .... Adding another D code to D code list ... \n"); 
-	
+    dprintf("     .... Adding another D code to D code list ... \n");
+
     /* Malloc space for new aperture list element */
     if (NULL == (D_list_new = g_new(gerbv_aperture_list_t, 1))) {
         GERB_FATAL_ERROR("malloc D_list failed in %s()", __FUNCTION__);
@@ -488,45 +437,38 @@ gerbv_stats_add_to_D_list(gerbv_aperture_list_t *D_list_in,
 
     /* Set member elements */
     D_list_new->number = number;
-    D_list_new->count = 0;
-    D_list_new->next = NULL;
-    D_list_last->next = D_list_new;
+    D_list_new->count  = 0;
+    D_list_new->next   = NULL;
+    D_list_last->next  = D_list_new;
 
-    dprintf("   <---  .... Leaving add_to_D_list.\n"); 
+    dprintf("   <---  .... Leaving add_to_D_list.\n");
 
     return;
 }
 
 /* ------------------------------------------------------- */
-int 
-gerbv_stats_increment_D_list_count(gerbv_aperture_list_t *D_list_in,
-				    int number, 
-				    int count,
-				    gerbv_error_list_t *error) {
-  
-    gerbv_aperture_list_t *D_list;
+int
+gerbv_stats_increment_D_list_count(gerbv_aperture_list_t* D_list_in, int number, int count, gerbv_error_list_t* error) {
+
+    gerbv_aperture_list_t* D_list;
 
     dprintf("   Entering inc_D_list_count, code = D%d, input count to add = %d\n", number, count);
 
     /* Find D code in list and increment it */
-    for(D_list = D_list_in; 
-	D_list != NULL; 
-	D_list = D_list->next) {
+    for (D_list = D_list_in; D_list != NULL; D_list = D_list->next) {
         if (D_list->number == number) {
-	    dprintf("    old count = %d\n", D_list->count);
-	    D_list->count += count;  /* Add to this aperture count, then return */
-	    dprintf("    updated count = %d\n", D_list->count);
-            return 0;  /* Return 0 for success */  
+            dprintf("    old count = %d\n", D_list->count);
+            D_list->count += count; /* Add to this aperture count, then return */
+            dprintf("    updated count = %d\n", D_list->count);
+            return 0; /* Return 0 for success */
         }
     }
 
     /* This D number is not defined.  Therefore, flag error */
     dprintf("    .... Didn't find this D code in defined list .... \n");
-    dprintf("   <---  .... Leaving inc_D_list_count.\n"); 
+    dprintf("   <---  .... Leaving inc_D_list_count.\n");
 
-    gerbv_stats_printf(error, GERBV_MESSAGE_ERROR, -1,
-	    _("Undefined aperture number called out in D code"));
+    gerbv_stats_printf(error, GERBV_MESSAGE_ERROR, -1, _("Undefined aperture number called out in D code"));
 
-    return -1;  /* Return -1 for failure */
+    return -1; /* Return -1 for failure */
 }
-
diff --git a/src/gerb_stats.h b/src/gerb_stats.h
index d20de2c..1adb43f 100644
--- a/src/gerb_stats.h
+++ b/src/gerb_stats.h
@@ -29,29 +29,21 @@
 #ifndef gerb_stats_H
 #define gerb_stats_H
 
-
-
 /* ===================  Prototypes ================ */
-gerbv_error_list_t *gerbv_stats_new_error_list(void);
-void gerbv_stats_printf(gerbv_error_list_t *list, gerbv_message_type_t type,
-			int layer, const char *text, ...)
-					__attribute__ ((format (printf, 4, 5)));
-void gerbv_stats_add_error(gerbv_error_list_t *error_list_in,
-                           int layer, const char *error_text,
-                           gerbv_message_type_t type);
-#define gerbv_escape_char(c) \
-	((char*)(int[]){gerbv_escape_char_return_int((c))})
+gerbv_error_list_t* gerbv_stats_new_error_list(void);
+void gerbv_stats_printf(gerbv_error_list_t* list, gerbv_message_type_t type, int layer, const char* text, ...)
+    __attribute__((format(printf, 4, 5)));
+void
+gerbv_stats_add_error(gerbv_error_list_t* error_list_in, int layer, const char* error_text, gerbv_message_type_t type);
+#define gerbv_escape_char(c) ((char*)(int[]) { gerbv_escape_char_return_int((c)) })
 int gerbv_escape_char_return_int(char c);
 
-gerbv_aperture_list_t *gerbv_stats_new_aperture_list(void);
-void gerbv_stats_add_aperture(gerbv_aperture_list_t *aperture_list_in,
-			     int layer, int number, gerbv_aperture_type_t type,
-			     double parameter[5]);
-void gerbv_stats_add_to_D_list(gerbv_aperture_list_t *D_list_in,
-			      int number);
-int gerbv_stats_increment_D_list_count(gerbv_aperture_list_t *D_list_in,
-				       int number, 
-				       int count,
-				       gerbv_error_list_t *error); 
+gerbv_aperture_list_t* gerbv_stats_new_aperture_list(void);
+void                   gerbv_stats_add_aperture(
+                      gerbv_aperture_list_t* aperture_list_in, int layer, int number, gerbv_aperture_type_t type, double parameter[5]
+                  );
+void gerbv_stats_add_to_D_list(gerbv_aperture_list_t* D_list_in, int number);
+int
+gerbv_stats_increment_D_list_count(gerbv_aperture_list_t* D_list_in, int number, int count, gerbv_error_list_t* error);
 
 #endif /* gerb_stats_H */
diff --git a/src/gerber.c b/src/gerber.c
index 1a608ab..e15e388 100644
--- a/src/gerber.c
+++ b/src/gerber.c
@@ -32,7 +32,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <limits.h>
-#include <math.h>  /* pow() */
+#include <math.h> /* pow() */
 #include <errno.h>
 #include <ctype.h>
 
@@ -43,90 +43,83 @@
 #include "amacro.h"
 
 #undef AMACRO_DEBUG
-#define dprintf if(DEBUG) printf
+#define dprintf \
+    if (DEBUG)  \
+    printf
 
-#define A2I(a,b) (((a & 0xff) << 8) + (b & 0xff))
+#define A2I(a, b) (((a & 0xff) << 8) + (b & 0xff))
 
 #define MAXL 200
 
 /* Local function prototypes */
-static void parse_G_code(gerb_file_t *fd, gerb_state_t *state, 
-			 gerbv_image_t *image, long int *line_num_p);
-static void parse_D_code(gerb_file_t *fd, gerb_state_t *state, 
-			 gerbv_image_t *image, long int *line_num_p);
-static int parse_M_code(gerb_file_t *fd, gerbv_image_t *image,
-			long int *line_num_p);
-static void parse_rs274x(gint levelOfRecursion, gerb_file_t *fd, 
-			 gerbv_image_t *image, gerb_state_t *state, 
-			 gerbv_net_t *curr_net, gerbv_stats_t *stats, 
-			 gchar *directoryPath, long int *line_num_p);
-static int parse_aperture_definition(gerb_file_t *fd, 
-				     gerbv_aperture_t *aperture,
-				     gerbv_image_t *image, gdouble scale,
-				     long int *line_num_p);
-static void calc_cirseg_sq(struct gerbv_net *net, int cw, 
-			   double delta_cp_x, double delta_cp_y);
-static void calc_cirseg_mq(struct gerbv_net *net, int cw, 
-			   double delta_cp_x, double delta_cp_y);
-static void calc_cirseg_bbox(const gerbv_cirseg_t *cirseg,
-			double apert_size_x, double apert_size_y,
-			gerbv_render_size_t *bbox);
-
-static void gerber_update_any_running_knockout_measurements(
-							gerbv_image_t *image);
-
-static void gerber_calculate_final_justify_effects (gerbv_image_t *image);
-
-static gboolean add_trailing_zeros_if_omitted(int *coord, int omitted_num,
-						gerbv_format_t *format);
-
-gboolean knockoutMeasure = FALSE;
-gdouble knockoutLimitXmin, knockoutLimitYmin,
-	knockoutLimitXmax, knockoutLimitYmax;
-gerbv_layer_t *knockoutLayer = NULL;
+static void parse_G_code(gerb_file_t* fd, gerb_state_t* state, gerbv_image_t* image, long int* line_num_p);
+static void parse_D_code(gerb_file_t* fd, gerb_state_t* state, gerbv_image_t* image, long int* line_num_p);
+static int  parse_M_code(gerb_file_t* fd, gerbv_image_t* image, long int* line_num_p);
+static void parse_rs274x(
+    gint levelOfRecursion, gerb_file_t* fd, gerbv_image_t* image, gerb_state_t* state, gerbv_net_t* curr_net,
+    gerbv_stats_t* stats, gchar* directoryPath, long int* line_num_p
+);
+static int parse_aperture_definition(
+    gerb_file_t* fd, gerbv_aperture_t* aperture, gerbv_image_t* image, gdouble scale, long int* line_num_p
+);
+static void calc_cirseg_sq(struct gerbv_net* net, int cw, double delta_cp_x, double delta_cp_y);
+static void calc_cirseg_mq(struct gerbv_net* net, int cw, double delta_cp_x, double delta_cp_y);
+static void
+calc_cirseg_bbox(const gerbv_cirseg_t* cirseg, double apert_size_x, double apert_size_y, gerbv_render_size_t* bbox);
+
+static void gerber_update_any_running_knockout_measurements(gerbv_image_t* image);
+
+static void gerber_calculate_final_justify_effects(gerbv_image_t* image);
+
+static gboolean add_trailing_zeros_if_omitted(int* coord, int omitted_num, gerbv_format_t* format);
+
+gboolean       knockoutMeasure = FALSE;
+gdouble        knockoutLimitXmin, knockoutLimitYmin, knockoutLimitXmax, knockoutLimitYmax;
+gerbv_layer_t* knockoutLayer = NULL;
 cairo_matrix_t currentMatrix;
 
 /* --------------------------------------------------------- */
-gerbv_net_t *
-gerber_create_new_net (gerbv_net_t *currentNet, gerbv_layer_t *layer, gerbv_netstate_t *state){
-	gerbv_net_t *newNet = g_new0 (gerbv_net_t, 1);
-	
-	currentNet->next = newNet;
-	if (layer)
-		newNet->layer = layer;
-	else
-		newNet->layer = currentNet->layer;
-	if (state)
-		newNet->state = state;
-	else
-		newNet->state = currentNet->state;
-	return newNet;
+gerbv_net_t*
+gerber_create_new_net(gerbv_net_t* currentNet, gerbv_layer_t* layer, gerbv_netstate_t* state) {
+    gerbv_net_t* newNet = g_new0(gerbv_net_t, 1);
+
+    currentNet->next = newNet;
+    if (layer)
+        newNet->layer = layer;
+    else
+        newNet->layer = currentNet->layer;
+    if (state)
+        newNet->state = state;
+    else
+        newNet->state = currentNet->state;
+    return newNet;
 }
 
 /* --------------------------------------------------------- */
 gboolean
-gerber_create_new_aperture (gerbv_image_t *image, int *indexNumber,
-		gerbv_aperture_type_t apertureType, gdouble parameter1, gdouble parameter2){
-	int i;
-	
-	/* search for an available aperture spot */
-	for (i = 0; i <= APERTURE_MAX; i++) {
-		if (image->aperture[i] == NULL) {
-			image->aperture[i] = g_new0 (gerbv_aperture_t, 1);
-			image->aperture[i]->type = apertureType;
-			image->aperture[i]->parameter[0] = parameter1;
-			image->aperture[i]->parameter[1] = parameter2;
-			*indexNumber = i;
-			return TRUE;
-		}
-	}
-	return FALSE;
+gerber_create_new_aperture(
+    gerbv_image_t* image, int* indexNumber, gerbv_aperture_type_t apertureType, gdouble parameter1, gdouble parameter2
+) {
+    int i;
+
+    /* search for an available aperture spot */
+    for (i = 0; i <= APERTURE_MAX; i++) {
+        if (image->aperture[i] == NULL) {
+            image->aperture[i]               = g_new0(gerbv_aperture_t, 1);
+            image->aperture[i]->type         = apertureType;
+            image->aperture[i]->parameter[0] = parameter1;
+            image->aperture[i]->parameter[1] = parameter2;
+            *indexNumber                     = i;
+            return TRUE;
+        }
+    }
+    return FALSE;
 }
 
 /* --------------------------------------------------------- */
 /*! This function reads the Gerber file char by char, looking
- *  for various Gerber codes (e.g. G, D, etc).  Once it reads 
- *  a code, it then dispatches control to one or another 
+ *  for various Gerber codes (e.g. G, D, etc).  Once it reads
+ *  a code, it then dispatches control to one or another
  *  bits of code which parse the individual code.
  *  It also updates the state struct, which holds info about
  *  the current state of the hypothetical photoplotter
@@ -134,632 +127,604 @@ gerber_create_new_aperture (gerbv_image_t *image, int *indexNumber,
  *  any other parameters, like units, offsets, apertures, etc.)
  */
 gboolean
-gerber_parse_file_segment (gint levelOfRecursion, gerbv_image_t *image, 
-			   gerb_state_t *state,	gerbv_net_t *curr_net, 
-			   gerbv_stats_t *stats, gerb_file_t *fd, 
-			   gchar *directoryPath)
-{
-    int read, coord, len, polygonPoints=0;
-    double x_scale = 0.0, y_scale = 0.0;
-    double delta_cp_x = 0.0, delta_cp_y = 0.0;
-    double aperture_sizeX, aperture_sizeY;
-    double scale;
-    gboolean foundEOF = FALSE;
-    gerbv_render_size_t boundingBoxNew = {HUGE_VAL,-HUGE_VAL,HUGE_VAL,-HUGE_VAL},
-			boundingBox = boundingBoxNew;
-    gerbv_error_list_t *error_list = stats->error_list;
-    long int line_num = 1;
+gerber_parse_file_segment(
+    gint levelOfRecursion, gerbv_image_t* image, gerb_state_t* state, gerbv_net_t* curr_net, gerbv_stats_t* stats,
+    gerb_file_t* fd, gchar* directoryPath
+) {
+    int                 read, coord, len, polygonPoints = 0;
+    double              x_scale = 0.0, y_scale = 0.0;
+    double              delta_cp_x = 0.0, delta_cp_y = 0.0;
+    double              aperture_sizeX, aperture_sizeY;
+    double              scale;
+    gboolean            foundEOF       = FALSE;
+    gerbv_render_size_t boundingBoxNew = { HUGE_VAL, -HUGE_VAL, HUGE_VAL, -HUGE_VAL }, boundingBox = boundingBoxNew;
+    gerbv_error_list_t* error_list = stats->error_list;
+    long int            line_num   = 1;
 
     while ((read = gerb_fgetc(fd)) != EOF) {
-        /* figure out the scale, since we need to normalize 
-	   all dimensions to inches */
+        /* figure out the scale, since we need to normalize
+       all dimensions to inches */
         if (state->state->unit == GERBV_UNIT_MM)
             scale = 25.4;
         else
             scale = 1.0;
-	switch ((char)(read & 0xff)) {
-	case 'G':
-	    dprintf("... Found G code at line %ld\n", line_num);
-	    parse_G_code(fd, state, image, &line_num);
-	    break;
-	case 'D':
-	    dprintf("... Found D code at line %ld\n", line_num);
-	    parse_D_code(fd, state, image, &line_num);
-	    break;
-	case 'M':
-	    dprintf("... Found M code at line %ld\n", line_num);
-
-	    switch(parse_M_code(fd, image, &line_num)) {
-	    case 1 :
-	    case 2 :
-	    case 3 :
-		foundEOF = TRUE;
-		break;
-	    default:
-		gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Unknown M code found at line %ld in file \"%s\""),
-			line_num, fd->filename);
-	    } /* switch(parse_M_code) */
-	    break;
-	case 'X':
-	    stats->X++;
-	    coord = gerb_fgetint(fd, &len);
-	    if (image->format)
-		    add_trailing_zeros_if_omitted(&coord,
-			    image->format->x_int + image->format->x_dec - len,
-			    image->format);
-	    dprintf("... Found X code %d at line %ld\n", coord, line_num);
-	    if (image->format
-	    &&  image->format->coordinate==GERBV_COORDINATE_INCREMENTAL)
-	        state->curr_x += coord;
-	    else
-	        state->curr_x = coord;
-
-	    state->changed = 1;
-	    break;
-
-	case 'Y':
-	    stats->Y++;
-	    coord = gerb_fgetint(fd, &len);
-	    if (image->format)
-		    add_trailing_zeros_if_omitted(&coord,
-			    image->format->y_int + image->format->y_dec - len,
-			    image->format);
-	    dprintf("... Found Y code %d at line %ld\n", coord, line_num);
-	    if (image->format
-	    &&  image->format->coordinate==GERBV_COORDINATE_INCREMENTAL)
-	        state->curr_y += coord;
-	    else
-	        state->curr_y = coord;
-
-	    state->changed = 1;
-	    break;
-
-	case 'I':
-	    stats->I++;
-	    coord = gerb_fgetint(fd, &len);
-	    if (image->format)
-		    add_trailing_zeros_if_omitted(&coord,
-			    image->format->x_int + image->format->x_dec - len,
-			    image->format);
-	    dprintf("... Found I code %d at line %ld\n", coord, line_num);
-	    state->delta_cp_x = coord;
-	    state->changed = 1;
-	    break;
-
-	case 'J':
-	    stats->J++;
-	    coord = gerb_fgetint(fd, &len);
-	    if (image->format)
-		    add_trailing_zeros_if_omitted(&coord,
-			    image->format->y_int + image->format->y_dec - len,
-			    image->format);
-	    dprintf("... Found J code %d at line %ld\n", coord, line_num);
-	    state->delta_cp_y = coord;
-	    state->changed = 1;
-	    break;
-
-	case '%':
-	    dprintf("... Found %% code at line %ld\n", line_num);
-	    while (1) {
-	    	parse_rs274x(levelOfRecursion, fd, image, state, curr_net,
-				stats, directoryPath, &line_num);
-
-	    	/* advance past any whitespace here */
-		int c;
-		while (1) {
-		    c = gerb_fgetc(fd);
-
-		    switch (c) {
-		    case '\0': case '\t': case ' ':
-
-			continue;
-
-		    case '\n':
-			line_num++;
-
-			/* Get <CR> char, if any, from <LF><CR> pair */
-			read = gerb_fgetc(fd);
-			if (read != '\r' && read != EOF)
-			    gerb_ungetc(fd);
-
-			continue;
-
-		    case '\r':
-			line_num++;
-
-			/* Get <LF> char, if any, from <CR><LF> pair */
-			read = gerb_fgetc(fd);
-			if (read != '\n' && read != EOF)
-			    gerb_ungetc(fd);
-
-			continue;
-		    }
-
-		    break; /* break while(1) */
-		};
-
-		if(c == EOF || c == '%')
-		    break;
-
-		/* Loop again to catch multiple blocks on the same line
-		 * (separated by * char) */
-		gerb_ungetc(fd);
-	    }
-	    break;
-	case '*':  
-	    dprintf("... Found * code at line %ld\n", line_num);
-	    stats->star++;
-	    if (state->changed == 0) break;
-	    state->changed = 0;
-	    
-	    /* don't even bother saving the net if the aperture state is GERBV_APERTURE_STATE_OFF and we
-	       aren't starting a polygon fill (where we need it to get to the start point) */
-	    if ((state->aperture_state == GERBV_APERTURE_STATE_OFF)&&(!state->in_parea_fill)&&
-	    		(state->interpolation != GERBV_INTERPOLATION_PAREA_START)) {
-		/* save the coordinate so the next net can use it for a start point */
-		state->prev_x = state->curr_x;
-		state->prev_y = state->curr_y;
-		break;
-	    }
-	    curr_net = gerber_create_new_net (curr_net, state->layer, state->state);
-	    /*
-	     * Scale to given coordinate format
-	     * XXX only "omit leading zeros".
-	     */
-	    if (image && image->format ){
-		x_scale = pow(10.0, (double)image->format->x_dec);
-		y_scale = pow(10.0, (double)image->format->y_dec);
-	    }
-	    x_scale *= scale;
-	    y_scale *= scale;
-	    curr_net->start_x = (double)state->prev_x / x_scale;
-	    curr_net->start_y = (double)state->prev_y / y_scale;
-	    curr_net->stop_x = (double)state->curr_x / x_scale;
-	    curr_net->stop_y = (double)state->curr_y / y_scale;
-	    delta_cp_x = (double)state->delta_cp_x / x_scale;
-	    delta_cp_y = (double)state->delta_cp_y / y_scale;
-
-	    switch (state->interpolation) {
-	    case GERBV_INTERPOLATION_CW_CIRCULAR :
-	    case GERBV_INTERPOLATION_CCW_CIRCULAR : {
-		int cw = (state->interpolation == GERBV_INTERPOLATION_CW_CIRCULAR);
-
-		curr_net->cirseg = g_new0 (gerbv_cirseg_t, 1);
-		if (state->mq_on) {
-		    calc_cirseg_mq(curr_net, cw, delta_cp_x, delta_cp_y);
-		} else {
-		    calc_cirseg_sq(curr_net, cw, delta_cp_x, delta_cp_y);
-
-		    /*
-		     * In single quadrant circular interpolation Ix and Jy
-		     * incremental distance must be unsigned.
-		     */
-		    if (delta_cp_x < 0 || delta_cp_y < 0) {
-			gerbv_stats_printf(error_list,
-				GERBV_MESSAGE_ERROR, -1, 
-				_("Signed incremental distance IxJy "
-				    "in single quadrant %s circular "
-				    "interpolation %s at line %ld "
-				    "in file \"%s\""),
-				cw? _("CW"): _("CCW"), cw? "G02": "G03",
-				line_num, fd->filename);
-		    }
-
-		}
-		break;
-	    }
-	    case GERBV_INTERPOLATION_PAREA_START :
-		/* 
-		 * To be able to get back and fill in number of polygon corners
-		 */
-		state->parea_start_node = curr_net;
-		state->in_parea_fill = 1;
-		polygonPoints = 0;
-		boundingBox = boundingBoxNew;
-		break;
-	    case GERBV_INTERPOLATION_PAREA_END :
-		/* save the calculated bounding box to the master node */
-		if (state->parea_start_node != NULL) {
-		    state->parea_start_node->boundingBox = boundingBox;
-		} else {
-		    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			    _("End of polygon without start "
-				"at line %ld in file \"%s\""),
-			    line_num, fd->filename);
-		}
-
-		/* close out the polygon */
-		state->parea_start_node = NULL;
-		state->in_parea_fill = 0;
-		polygonPoints = 0;
-		break;
-	    default :
-		break;
-	    }  /* switch(state->interpolation) */
-
-	    /* 
-	     * Count number of points in Polygon Area 
-	     */
-	    if (state->in_parea_fill && state->parea_start_node) {
-		/* 
-		 * "...all lines drawn with D01 are considered edges of the
-		 * polygon. D02 closes and fills the polygon."
-		 * p.49 rs274xrevd_e.pdf
-		 * D02 -> state->aperture_state == GERBV_APERTURE_STATE_OFF
-		 */
-		 
-		 /* UPDATE: only end the polygon during a D02 call if we've already
-		    drawn a polygon edge (with D01) */
-		   
-		if (state->aperture_state == GERBV_APERTURE_STATE_OFF
-		&&  state->interpolation  != GERBV_INTERPOLATION_PAREA_START
-		&&  polygonPoints > 0) {
-		    curr_net->interpolation = GERBV_INTERPOLATION_PAREA_END;
-		    curr_net = gerber_create_new_net (curr_net, state->layer, state->state);
-		    curr_net->interpolation = GERBV_INTERPOLATION_PAREA_START;
-		    state->parea_start_node->boundingBox = boundingBox;
-		    state->parea_start_node = curr_net;
-		    polygonPoints = 0;
-		    curr_net = gerber_create_new_net (curr_net, state->layer, state->state);		    
-		    curr_net->start_x = (double)state->prev_x / x_scale;
-		    curr_net->start_y = (double)state->prev_y / y_scale;
-		    curr_net->stop_x = (double)state->curr_x / x_scale;
-		    curr_net->stop_y = (double)state->curr_y / y_scale;
-		    boundingBox = boundingBoxNew;
-		}
-		else if (state->interpolation != GERBV_INTERPOLATION_PAREA_START)
-		    polygonPoints++;
-		
-	    }  /* if (state->in_parea_fill && state->parea_start_node) */
-	    
-	    curr_net->interpolation = state->interpolation;
-
-	    /* 
-	     * Override circular interpolation if no center was given.
-	     * This should be a safe hack, since a good file should always 
-	     * include I or J.  And even if the radius is zero, the endpoint 
-	     * should be the same as the start point, creating no line 
-	     */
-	    if (((state->interpolation == GERBV_INTERPOLATION_CW_CIRCULAR) || 
-		 (state->interpolation == GERBV_INTERPOLATION_CCW_CIRCULAR)) && 
-		((state->delta_cp_x == 0.0) && (state->delta_cp_y == 0.0)))
-		curr_net->interpolation = GERBV_INTERPOLATION_LINEARx1;
-	    
-	    /*
-	     * If we detected the end of Polygon Area Fill we go back to
-	     * the interpolation we had before that.
-	     * Also if we detected any of the quadrant flags, since some
-	     * gerbers don't reset the interpolation (EagleCad again).
-	     */
-	    if ((state->interpolation == GERBV_INTERPOLATION_PAREA_START
-	    ||   state->interpolation == GERBV_INTERPOLATION_PAREA_END)
-	    && state->prev_interpolation != GERBV_INTERPOLATION_PAREA_END) {
-		state->interpolation = state->prev_interpolation;
-	    }
-
-	    /*
-	     * Save layer polarity and unit
-	     */
-	    curr_net->layer = state->layer;  
-	    
-	    state->delta_cp_x = 0.0;
-	    state->delta_cp_y = 0.0;
-	    curr_net->aperture = state->curr_aperture;
-	    curr_net->aperture_state = state->aperture_state;
-
-	    /*
-	     * For next round we save the current position as
-	     * the previous position
-	     */
-	    state->prev_x = state->curr_x;
-	    state->prev_y = state->curr_y;
-
-	    /*
-	     * If we have an aperture defined at the moment we find 
-	     * min and max of image with compensation for mm.
-	     */
-	    if ((curr_net->aperture == 0) && !state->in_parea_fill) 
-		break;
-	    
-	    /* only update the min/max values and aperture stats if we are drawing */
-	    if ((curr_net->aperture_state != GERBV_APERTURE_STATE_OFF)&&
-	    		(curr_net->interpolation != GERBV_INTERPOLATION_PAREA_START)){
-		double repeat_off_X = 0.0, repeat_off_Y = 0.0;
-
-		/* Update stats with current aperture number if not in polygon */
-		if (!state->in_parea_fill) {
-			dprintf("     In %s(), adding 1 to D_list ...\n",
-					__func__);
-			int retcode = gerbv_stats_increment_D_list_count(
-				stats->D_code_list, curr_net->aperture,
-				1, error_list);
-			if (retcode == -1) {
-			    gerbv_stats_printf(error_list,
-				    GERBV_MESSAGE_ERROR, -1,
-				    _("Found undefined D code D%02d "
-					"at line %ld in file \"%s\""),
-				    curr_net->aperture, line_num, fd->filename);
-			    stats->D_unknown++;
-			}
-		}
-
-		/*
-		 * If step_and_repeat (%SR%) is used, check min_x,max_y etc for
-		 * the ends of the step_and_repeat lattice. This goes wrong in 
-		 * the case of negative dist_X or dist_Y, in which case we 
-		 * should compare against the startpoints of the lines, not 
-		 * the stoppoints, but that seems an uncommon case (and the 
-		 * error isn't very big any way).
-		 */
-		repeat_off_X = (state->layer->stepAndRepeat.X - 1) *
-		    state->layer->stepAndRepeat.dist_X;
-		repeat_off_Y = (state->layer->stepAndRepeat.Y - 1) *
-		    state->layer->stepAndRepeat.dist_Y;
-		
-		cairo_matrix_init (&currentMatrix, 1, 0, 0, 1, 0, 0);
-		/* offset image */
-		cairo_matrix_translate (&currentMatrix, image->info->offsetA, 
-					image->info->offsetB);
-		/* do image rotation */
-		cairo_matrix_rotate (&currentMatrix, image->info->imageRotation);
-		/* it's a new layer, so recalculate the new transformation 
-		 * matrix for it */
-		/* do any rotations */
-		cairo_matrix_rotate (&currentMatrix, state->layer->rotation);
-			
-		/* calculate current layer and state transformation matrices */
-		/* apply scale factor */
-		cairo_matrix_scale (&currentMatrix, state->state->scaleA, 
-				    state->state->scaleB);
-		/* apply offset */
-		cairo_matrix_translate (&currentMatrix, state->state->offsetA,
-					state->state->offsetB);
-		/* apply mirror */
-		switch (state->state->mirrorState) {
-		case GERBV_MIRROR_STATE_FLIPA:
-		    cairo_matrix_scale (&currentMatrix, -1, 1);
-		    break;
-		case GERBV_MIRROR_STATE_FLIPB:
-		    cairo_matrix_scale (&currentMatrix, 1, -1);
-		    break;
-		case GERBV_MIRROR_STATE_FLIPAB:
-		    cairo_matrix_scale (&currentMatrix, -1, -1);
-		    break;
-		default:
-		    break;
-		}
-		/* finally, apply axis select */
-		if (state->state->axisSelect == GERBV_AXIS_SELECT_SWAPAB) {
-		    /* we do this by rotating 270 (counterclockwise, then 
-		     *  mirroring the Y axis 
-		     */
-		    cairo_matrix_rotate (&currentMatrix, M_PI + M_PI_2);
-		    cairo_matrix_scale (&currentMatrix, 1, -1);
-		}
-		/* if it's a macro, step through all the primitive components
-		   and calculate the true bounding box */
-		if ((image->aperture[curr_net->aperture] != NULL) &&
-		    (image->aperture[curr_net->aperture]->type == GERBV_APTYPE_MACRO)) {
-		    gerbv_simplified_amacro_t *ls = image->aperture[curr_net->aperture]->simplified;
-	      
-		    while (ls != NULL) {
-			gdouble offsetx = 0, offsety = 0, widthx = 0, widthy = 0;
-			gboolean calculatedAlready = FALSE;
-			
-			if (ls->type == GERBV_APTYPE_MACRO_CIRCLE) {
-			    offsetx=ls->parameter[CIRCLE_CENTER_X];
-			    offsety=ls->parameter[CIRCLE_CENTER_Y];
-			    widthx=widthy=ls->parameter[CIRCLE_DIAMETER];
-			} else if (ls->type == GERBV_APTYPE_MACRO_OUTLINE) {
-			    int pointCounter,numberOfPoints;
-			    numberOfPoints = ls->parameter[OUTLINE_NUMBER_OF_POINTS] + 1;
-		
-			    for (pointCounter = 0; pointCounter < numberOfPoints; pointCounter++) {
-				gerber_update_min_and_max (&boundingBox,
-							   curr_net->stop_x +
-							   ls->parameter[OUTLINE_X_IDX_OF_POINT(pointCounter)],
-							   curr_net->stop_y +
-							   ls->parameter[OUTLINE_Y_IDX_OF_POINT(pointCounter)], 
-							   0,0,0,0);
-			    }
-			    calculatedAlready = TRUE;
-			} else if (ls->type == GERBV_APTYPE_MACRO_POLYGON) {
-			    offsetx = ls->parameter[POLYGON_CENTER_X];
-			    offsety = ls->parameter[POLYGON_CENTER_Y];
-			    widthx = widthy = ls->parameter[POLYGON_DIAMETER];
-			} else if (ls->type == GERBV_APTYPE_MACRO_MOIRE) {
-			    offsetx = ls->parameter[MOIRE_CENTER_X];
-			    offsety = ls->parameter[MOIRE_CENTER_Y];
-			    widthx = widthy = ls->parameter[MOIRE_OUTSIDE_DIAMETER];
-			} else if (ls->type == GERBV_APTYPE_MACRO_THERMAL) {
-			    offsetx = ls->parameter[THERMAL_CENTER_X];
-			    offsety = ls->parameter[THERMAL_CENTER_Y];
-			    widthx = widthy = ls->parameter[THERMAL_OUTSIDE_DIAMETER];
-			} else if (ls->type == GERBV_APTYPE_MACRO_LINE20) {
-			    widthx = widthy = ls->parameter[LINE20_LINE_WIDTH];
-			    gerber_update_min_and_max (&boundingBox,
-						       curr_net->stop_x +
-						       ls->parameter[LINE20_START_X],
-						       curr_net->stop_y +
-						       ls->parameter[LINE20_START_Y], 
-						       widthx/2,widthx/2,widthy/2,widthy/2);
-			    gerber_update_min_and_max (&boundingBox,
-						       curr_net->stop_x +
-						       ls->parameter[LINE20_END_X],
-						       curr_net->stop_y +
-						       ls->parameter[LINE20_END_Y], 
-						       widthx/2,widthx/2,widthy/2,widthy/2);
-			    calculatedAlready = TRUE;
-			} else if (ls->type == GERBV_APTYPE_MACRO_LINE21) {
-			    gdouble largestDimension = hypot(ls->parameter[LINE21_WIDTH],
-							     ls->parameter[LINE21_HEIGHT]);
-			    offsetx = ls->parameter[LINE21_CENTER_X];
-			    offsety = ls->parameter[LINE21_CENTER_Y];
-			    widthx = widthy = largestDimension;
-			} else if (ls->type == GERBV_APTYPE_MACRO_LINE22) {
-			    gdouble largestDimension = hypot(ls->parameter[LINE22_WIDTH],
-							     ls->parameter[LINE22_HEIGHT]);
-
-			    offsetx = ls->parameter[LINE22_LOWER_LEFT_X] +
-	      			ls->parameter[LINE22_WIDTH]/2;
-			    offsety = ls->parameter[LINE22_LOWER_LEFT_Y] +
-	      			ls->parameter[LINE22_HEIGHT]/2;
-			    widthx = widthy=largestDimension;
-			}
-	      	
-			if (!calculatedAlready) {
-			    gerber_update_min_and_max (&boundingBox,
-						       curr_net->stop_x + offsetx,
-						       curr_net->stop_y + offsety, 
-						       widthx/2,widthx/2,widthy/2,widthy/2);
-			}
-	    		ls = ls->next;
-		    }
-		} else {
-		    if (image->aperture[curr_net->aperture] != NULL) {
-			aperture_sizeX = image->aperture[curr_net->aperture]->parameter[0];
-			if ((image->aperture[curr_net->aperture]->type == GERBV_APTYPE_RECTANGLE) || (image->aperture[curr_net->aperture]->type == GERBV_APTYPE_OVAL)) {
-				aperture_sizeY = image->aperture[curr_net->aperture]->parameter[1];
-			}
-			else
-				aperture_sizeY = aperture_sizeX;
-		    } else {
-			/* this is usually for polygon fills, where the aperture width
-			   is "zero" */
-			aperture_sizeX = aperture_sizeY = 0;
-		    }
-
-		    /* if it's an arc path, use a special calc */
-
-		    if ((curr_net->interpolation ==
-					GERBV_INTERPOLATION_CW_CIRCULAR) ||
-			(curr_net->interpolation ==
-					GERBV_INTERPOLATION_CCW_CIRCULAR)) {
-				calc_cirseg_bbox(curr_net->cirseg,
-						aperture_sizeX, aperture_sizeY,
-						&boundingBox);
-		    } else {
-			    /* check both the start and stop of the aperture points against
-			       a running min/max counter */
-			    /* Note: only check start coordinate if this isn't a flash, 
-			       since the start point may be bogus if it is a flash */
-			    if (curr_net->aperture_state != GERBV_APERTURE_STATE_FLASH) {
-				gerber_update_min_and_max (&boundingBox,
-							   curr_net->start_x, curr_net->start_y, 
-							   aperture_sizeX/2,aperture_sizeX/2,
-							   aperture_sizeY/2,aperture_sizeY/2);
-			    }
-			    gerber_update_min_and_max (&boundingBox,
-						       curr_net->stop_x, curr_net->stop_y, 
-						       aperture_sizeX/2,aperture_sizeX/2,
-						       aperture_sizeY/2,aperture_sizeY/2);
-		    }
-					     
-		}
-		/* update the info bounding box with this latest bounding box */
-		/* don't change the bounding box if the polarity is clear */
-		if (state->layer->polarity != GERBV_POLARITY_CLEAR){
-			gerber_update_image_min_max(&boundingBox, repeat_off_X, repeat_off_Y, image);
-		}
-		/* optionally update the knockout measurement box */
-		if (knockoutMeasure) {
-			if (boundingBox.left < knockoutLimitXmin)
-				knockoutLimitXmin = boundingBox.left;
-			if (boundingBox.right+repeat_off_X > knockoutLimitXmax)
-				knockoutLimitXmax = boundingBox.right+repeat_off_X;
-			if (boundingBox.bottom < knockoutLimitYmin)
-				knockoutLimitYmin = boundingBox.bottom;
-			if (boundingBox.top+repeat_off_Y > knockoutLimitYmax)
-				knockoutLimitYmax = boundingBox.top+repeat_off_Y;
-		}
-		/* if we're not in a polygon fill, then update the object bounding box */
-		if (!state->in_parea_fill) {
-			curr_net->boundingBox = boundingBox;
-			boundingBox = boundingBoxNew;
-		}
-	    }
-	    break;
-
-	case '\0': case '\t': case ' ':
-	    break;
-
-	case '\n':
-	    line_num++;
-
-	    /* Get <CR> char, if any, from <LF><CR> pair */
-	    read = gerb_fgetc(fd);
-	    if (read != '\r' && read != EOF)
-		    gerb_ungetc(fd);
-	    break;
-
-	case '\r':
-	    line_num++;
-
-	    /* Get <LF> char, if any, from <CR><LF> pair */
-	    read = gerb_fgetc(fd);
-	    if (read != '\n' && read != EOF)
-		    gerb_ungetc(fd);
-	    break;
-
-	default:
-	    stats->unknown++;
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Found unknown character '%s' (0x%x) "
-			"at line %ld in file \"%s\""),
-		    gerbv_escape_char(read), read,
-		    line_num, fd->filename);
-	}  /* switch((char) (read & 0xff)) */
+        switch ((char)(read & 0xff)) {
+            case 'G':
+                dprintf("... Found G code at line %ld\n", line_num);
+                parse_G_code(fd, state, image, &line_num);
+                break;
+            case 'D':
+                dprintf("... Found D code at line %ld\n", line_num);
+                parse_D_code(fd, state, image, &line_num);
+                break;
+            case 'M':
+                dprintf("... Found M code at line %ld\n", line_num);
+
+                switch (parse_M_code(fd, image, &line_num)) {
+                    case 1:
+                    case 2:
+                    case 3: foundEOF = TRUE; break;
+                    default:
+                        gerbv_stats_printf(
+                            error_list, GERBV_MESSAGE_ERROR, -1, _("Unknown M code found at line %ld in file \"%s\""),
+                            line_num, fd->filename
+                        );
+                } /* switch(parse_M_code) */
+                break;
+            case 'X':
+                stats->X++;
+                coord = gerb_fgetint(fd, &len);
+                if (image->format)
+                    add_trailing_zeros_if_omitted(
+                        &coord, image->format->x_int + image->format->x_dec - len, image->format
+                    );
+                dprintf("... Found X code %d at line %ld\n", coord, line_num);
+                if (image->format && image->format->coordinate == GERBV_COORDINATE_INCREMENTAL)
+                    state->curr_x += coord;
+                else
+                    state->curr_x = coord;
+
+                state->changed = 1;
+                break;
+
+            case 'Y':
+                stats->Y++;
+                coord = gerb_fgetint(fd, &len);
+                if (image->format)
+                    add_trailing_zeros_if_omitted(
+                        &coord, image->format->y_int + image->format->y_dec - len, image->format
+                    );
+                dprintf("... Found Y code %d at line %ld\n", coord, line_num);
+                if (image->format && image->format->coordinate == GERBV_COORDINATE_INCREMENTAL)
+                    state->curr_y += coord;
+                else
+                    state->curr_y = coord;
+
+                state->changed = 1;
+                break;
+
+            case 'I':
+                stats->I++;
+                coord = gerb_fgetint(fd, &len);
+                if (image->format)
+                    add_trailing_zeros_if_omitted(
+                        &coord, image->format->x_int + image->format->x_dec - len, image->format
+                    );
+                dprintf("... Found I code %d at line %ld\n", coord, line_num);
+                state->delta_cp_x = coord;
+                state->changed    = 1;
+                break;
+
+            case 'J':
+                stats->J++;
+                coord = gerb_fgetint(fd, &len);
+                if (image->format)
+                    add_trailing_zeros_if_omitted(
+                        &coord, image->format->y_int + image->format->y_dec - len, image->format
+                    );
+                dprintf("... Found J code %d at line %ld\n", coord, line_num);
+                state->delta_cp_y = coord;
+                state->changed    = 1;
+                break;
+
+            case '%':
+                dprintf("... Found %% code at line %ld\n", line_num);
+                while (1) {
+                    parse_rs274x(levelOfRecursion, fd, image, state, curr_net, stats, directoryPath, &line_num);
+
+                    /* advance past any whitespace here */
+                    int c;
+                    while (1) {
+                        c = gerb_fgetc(fd);
+
+                        switch (c) {
+                            case '\0':
+                            case '\t':
+                            case ' ': continue;
+
+                            case '\n':
+                                line_num++;
+
+                                /* Get <CR> char, if any, from <LF><CR> pair */
+                                read = gerb_fgetc(fd);
+                                if (read != '\r' && read != EOF)
+                                    gerb_ungetc(fd);
+
+                                continue;
+
+                            case '\r':
+                                line_num++;
+
+                                /* Get <LF> char, if any, from <CR><LF> pair */
+                                read = gerb_fgetc(fd);
+                                if (read != '\n' && read != EOF)
+                                    gerb_ungetc(fd);
+
+                                continue;
+                        }
+
+                        break; /* break while(1) */
+                    };
+
+                    if (c == EOF || c == '%')
+                        break;
+
+                    /* Loop again to catch multiple blocks on the same line
+                     * (separated by * char) */
+                    gerb_ungetc(fd);
+                }
+                break;
+            case '*':
+                dprintf("... Found * code at line %ld\n", line_num);
+                stats->star++;
+                if (state->changed == 0)
+                    break;
+                state->changed = 0;
+
+                /* don't even bother saving the net if the aperture state is GERBV_APERTURE_STATE_OFF and we
+                   aren't starting a polygon fill (where we need it to get to the start point) */
+                if ((state->aperture_state == GERBV_APERTURE_STATE_OFF) && (!state->in_parea_fill)
+                    && (state->interpolation != GERBV_INTERPOLATION_PAREA_START)) {
+                    /* save the coordinate so the next net can use it for a start point */
+                    state->prev_x = state->curr_x;
+                    state->prev_y = state->curr_y;
+                    break;
+                }
+                curr_net = gerber_create_new_net(curr_net, state->layer, state->state);
+                /*
+                 * Scale to given coordinate format
+                 * XXX only "omit leading zeros".
+                 */
+                if (image && image->format) {
+                    x_scale = pow(10.0, (double)image->format->x_dec);
+                    y_scale = pow(10.0, (double)image->format->y_dec);
+                }
+                x_scale *= scale;
+                y_scale *= scale;
+                curr_net->start_x = (double)state->prev_x / x_scale;
+                curr_net->start_y = (double)state->prev_y / y_scale;
+                curr_net->stop_x  = (double)state->curr_x / x_scale;
+                curr_net->stop_y  = (double)state->curr_y / y_scale;
+                delta_cp_x        = (double)state->delta_cp_x / x_scale;
+                delta_cp_y        = (double)state->delta_cp_y / y_scale;
+
+                switch (state->interpolation) {
+                    case GERBV_INTERPOLATION_CW_CIRCULAR:
+                    case GERBV_INTERPOLATION_CCW_CIRCULAR:
+                        {
+                            int cw = (state->interpolation == GERBV_INTERPOLATION_CW_CIRCULAR);
+
+                            curr_net->cirseg = g_new0(gerbv_cirseg_t, 1);
+                            if (state->mq_on) {
+                                calc_cirseg_mq(curr_net, cw, delta_cp_x, delta_cp_y);
+                            } else {
+                                calc_cirseg_sq(curr_net, cw, delta_cp_x, delta_cp_y);
+
+                                /*
+                                 * In single quadrant circular interpolation Ix and Jy
+                                 * incremental distance must be unsigned.
+                                 */
+                                if (delta_cp_x < 0 || delta_cp_y < 0) {
+                                    gerbv_stats_printf(
+                                        error_list, GERBV_MESSAGE_ERROR, -1,
+                                        _("Signed incremental distance IxJy "
+                                          "in single quadrant %s circular "
+                                          "interpolation %s at line %ld "
+                                          "in file \"%s\""),
+                                        cw ? _("CW") : _("CCW"), cw ? "G02" : "G03", line_num, fd->filename
+                                    );
+                                }
+                            }
+                            break;
+                        }
+                    case GERBV_INTERPOLATION_PAREA_START:
+                        /*
+                         * To be able to get back and fill in number of polygon corners
+                         */
+                        state->parea_start_node = curr_net;
+                        state->in_parea_fill    = 1;
+                        polygonPoints           = 0;
+                        boundingBox             = boundingBoxNew;
+                        break;
+                    case GERBV_INTERPOLATION_PAREA_END:
+                        /* save the calculated bounding box to the master node */
+                        if (state->parea_start_node != NULL) {
+                            state->parea_start_node->boundingBox = boundingBox;
+                        } else {
+                            gerbv_stats_printf(
+                                error_list, GERBV_MESSAGE_ERROR, -1,
+                                _("End of polygon without start "
+                                  "at line %ld in file \"%s\""),
+                                line_num, fd->filename
+                            );
+                        }
+
+                        /* close out the polygon */
+                        state->parea_start_node = NULL;
+                        state->in_parea_fill    = 0;
+                        polygonPoints           = 0;
+                        break;
+                    default: break;
+                } /* switch(state->interpolation) */
+
+                /*
+                 * Count number of points in Polygon Area
+                 */
+                if (state->in_parea_fill && state->parea_start_node) {
+                    /*
+                     * "...all lines drawn with D01 are considered edges of the
+                     * polygon. D02 closes and fills the polygon."
+                     * p.49 rs274xrevd_e.pdf
+                     * D02 -> state->aperture_state == GERBV_APERTURE_STATE_OFF
+                     */
+
+                    /* UPDATE: only end the polygon during a D02 call if we've already
+                       drawn a polygon edge (with D01) */
+
+                    if (state->aperture_state == GERBV_APERTURE_STATE_OFF
+                        && state->interpolation != GERBV_INTERPOLATION_PAREA_START && polygonPoints > 0) {
+                        curr_net->interpolation = GERBV_INTERPOLATION_PAREA_END;
+                        curr_net                = gerber_create_new_net(curr_net, state->layer, state->state);
+                        curr_net->interpolation = GERBV_INTERPOLATION_PAREA_START;
+                        state->parea_start_node->boundingBox = boundingBox;
+                        state->parea_start_node              = curr_net;
+                        polygonPoints                        = 0;
+                        curr_net          = gerber_create_new_net(curr_net, state->layer, state->state);
+                        curr_net->start_x = (double)state->prev_x / x_scale;
+                        curr_net->start_y = (double)state->prev_y / y_scale;
+                        curr_net->stop_x  = (double)state->curr_x / x_scale;
+                        curr_net->stop_y  = (double)state->curr_y / y_scale;
+                        boundingBox       = boundingBoxNew;
+                    } else if (state->interpolation != GERBV_INTERPOLATION_PAREA_START)
+                        polygonPoints++;
+
+                } /* if (state->in_parea_fill && state->parea_start_node) */
+
+                curr_net->interpolation = state->interpolation;
+
+                /*
+                 * Override circular interpolation if no center was given.
+                 * This should be a safe hack, since a good file should always
+                 * include I or J.  And even if the radius is zero, the endpoint
+                 * should be the same as the start point, creating no line
+                 */
+                if (((state->interpolation == GERBV_INTERPOLATION_CW_CIRCULAR)
+                     || (state->interpolation == GERBV_INTERPOLATION_CCW_CIRCULAR))
+                    && ((state->delta_cp_x == 0.0) && (state->delta_cp_y == 0.0)))
+                    curr_net->interpolation = GERBV_INTERPOLATION_LINEARx1;
+
+                /*
+                 * If we detected the end of Polygon Area Fill we go back to
+                 * the interpolation we had before that.
+                 * Also if we detected any of the quadrant flags, since some
+                 * gerbers don't reset the interpolation (EagleCad again).
+                 */
+                if ((state->interpolation == GERBV_INTERPOLATION_PAREA_START
+                     || state->interpolation == GERBV_INTERPOLATION_PAREA_END)
+                    && state->prev_interpolation != GERBV_INTERPOLATION_PAREA_END) {
+                    state->interpolation = state->prev_interpolation;
+                }
+
+                /*
+                 * Save layer polarity and unit
+                 */
+                curr_net->layer = state->layer;
+
+                state->delta_cp_x        = 0.0;
+                state->delta_cp_y        = 0.0;
+                curr_net->aperture       = state->curr_aperture;
+                curr_net->aperture_state = state->aperture_state;
+
+                /*
+                 * For next round we save the current position as
+                 * the previous position
+                 */
+                state->prev_x = state->curr_x;
+                state->prev_y = state->curr_y;
+
+                /*
+                 * If we have an aperture defined at the moment we find
+                 * min and max of image with compensation for mm.
+                 */
+                if ((curr_net->aperture == 0) && !state->in_parea_fill)
+                    break;
+
+                /* only update the min/max values and aperture stats if we are drawing */
+                if ((curr_net->aperture_state != GERBV_APERTURE_STATE_OFF)
+                    && (curr_net->interpolation != GERBV_INTERPOLATION_PAREA_START)) {
+                    double repeat_off_X = 0.0, repeat_off_Y = 0.0;
+
+                    /* Update stats with current aperture number if not in polygon */
+                    if (!state->in_parea_fill) {
+                        dprintf("     In %s(), adding 1 to D_list ...\n", __func__);
+                        int retcode =
+                            gerbv_stats_increment_D_list_count(stats->D_code_list, curr_net->aperture, 1, error_list);
+                        if (retcode == -1) {
+                            gerbv_stats_printf(
+                                error_list, GERBV_MESSAGE_ERROR, -1,
+                                _("Found undefined D code D%02d "
+                                  "at line %ld in file \"%s\""),
+                                curr_net->aperture, line_num, fd->filename
+                            );
+                            stats->D_unknown++;
+                        }
+                    }
+
+                    /*
+                     * If step_and_repeat (%SR%) is used, check min_x,max_y etc for
+                     * the ends of the step_and_repeat lattice. This goes wrong in
+                     * the case of negative dist_X or dist_Y, in which case we
+                     * should compare against the startpoints of the lines, not
+                     * the stoppoints, but that seems an uncommon case (and the
+                     * error isn't very big any way).
+                     */
+                    repeat_off_X = (state->layer->stepAndRepeat.X - 1) * state->layer->stepAndRepeat.dist_X;
+                    repeat_off_Y = (state->layer->stepAndRepeat.Y - 1) * state->layer->stepAndRepeat.dist_Y;
+
+                    cairo_matrix_init(&currentMatrix, 1, 0, 0, 1, 0, 0);
+                    /* offset image */
+                    cairo_matrix_translate(&currentMatrix, image->info->offsetA, image->info->offsetB);
+                    /* do image rotation */
+                    cairo_matrix_rotate(&currentMatrix, image->info->imageRotation);
+                    /* it's a new layer, so recalculate the new transformation
+                     * matrix for it */
+                    /* do any rotations */
+                    cairo_matrix_rotate(&currentMatrix, state->layer->rotation);
+
+                    /* calculate current layer and state transformation matrices */
+                    /* apply scale factor */
+                    cairo_matrix_scale(&currentMatrix, state->state->scaleA, state->state->scaleB);
+                    /* apply offset */
+                    cairo_matrix_translate(&currentMatrix, state->state->offsetA, state->state->offsetB);
+                    /* apply mirror */
+                    switch (state->state->mirrorState) {
+                        case GERBV_MIRROR_STATE_FLIPA: cairo_matrix_scale(&currentMatrix, -1, 1); break;
+                        case GERBV_MIRROR_STATE_FLIPB: cairo_matrix_scale(&currentMatrix, 1, -1); break;
+                        case GERBV_MIRROR_STATE_FLIPAB: cairo_matrix_scale(&currentMatrix, -1, -1); break;
+                        default: break;
+                    }
+                    /* finally, apply axis select */
+                    if (state->state->axisSelect == GERBV_AXIS_SELECT_SWAPAB) {
+                        /* we do this by rotating 270 (counterclockwise, then
+                         *  mirroring the Y axis
+                         */
+                        cairo_matrix_rotate(&currentMatrix, M_PI + M_PI_2);
+                        cairo_matrix_scale(&currentMatrix, 1, -1);
+                    }
+                    /* if it's a macro, step through all the primitive components
+                       and calculate the true bounding box */
+                    if ((image->aperture[curr_net->aperture] != NULL)
+                        && (image->aperture[curr_net->aperture]->type == GERBV_APTYPE_MACRO)) {
+                        gerbv_simplified_amacro_t* ls = image->aperture[curr_net->aperture]->simplified;
+
+                        while (ls != NULL) {
+                            gdouble  offsetx = 0, offsety = 0, widthx = 0, widthy = 0;
+                            gboolean calculatedAlready = FALSE;
+
+                            if (ls->type == GERBV_APTYPE_MACRO_CIRCLE) {
+                                offsetx = ls->parameter[CIRCLE_CENTER_X];
+                                offsety = ls->parameter[CIRCLE_CENTER_Y];
+                                widthx = widthy = ls->parameter[CIRCLE_DIAMETER];
+                            } else if (ls->type == GERBV_APTYPE_MACRO_OUTLINE) {
+                                int pointCounter, numberOfPoints;
+                                numberOfPoints = ls->parameter[OUTLINE_NUMBER_OF_POINTS] + 1;
+
+                                for (pointCounter = 0; pointCounter < numberOfPoints; pointCounter++) {
+                                    gerber_update_min_and_max(
+                                        &boundingBox,
+                                        curr_net->stop_x + ls->parameter[OUTLINE_X_IDX_OF_POINT(pointCounter)],
+                                        curr_net->stop_y + ls->parameter[OUTLINE_Y_IDX_OF_POINT(pointCounter)], 0, 0, 0,
+                                        0
+                                    );
+                                }
+                                calculatedAlready = TRUE;
+                            } else if (ls->type == GERBV_APTYPE_MACRO_POLYGON) {
+                                offsetx = ls->parameter[POLYGON_CENTER_X];
+                                offsety = ls->parameter[POLYGON_CENTER_Y];
+                                widthx = widthy = ls->parameter[POLYGON_DIAMETER];
+                            } else if (ls->type == GERBV_APTYPE_MACRO_MOIRE) {
+                                offsetx = ls->parameter[MOIRE_CENTER_X];
+                                offsety = ls->parameter[MOIRE_CENTER_Y];
+                                widthx = widthy = ls->parameter[MOIRE_OUTSIDE_DIAMETER];
+                            } else if (ls->type == GERBV_APTYPE_MACRO_THERMAL) {
+                                offsetx = ls->parameter[THERMAL_CENTER_X];
+                                offsety = ls->parameter[THERMAL_CENTER_Y];
+                                widthx = widthy = ls->parameter[THERMAL_OUTSIDE_DIAMETER];
+                            } else if (ls->type == GERBV_APTYPE_MACRO_LINE20) {
+                                widthx = widthy = ls->parameter[LINE20_LINE_WIDTH];
+                                gerber_update_min_and_max(
+                                    &boundingBox, curr_net->stop_x + ls->parameter[LINE20_START_X],
+                                    curr_net->stop_y + ls->parameter[LINE20_START_Y], widthx / 2, widthx / 2,
+                                    widthy / 2, widthy / 2
+                                );
+                                gerber_update_min_and_max(
+                                    &boundingBox, curr_net->stop_x + ls->parameter[LINE20_END_X],
+                                    curr_net->stop_y + ls->parameter[LINE20_END_Y], widthx / 2, widthx / 2, widthy / 2,
+                                    widthy / 2
+                                );
+                                calculatedAlready = TRUE;
+                            } else if (ls->type == GERBV_APTYPE_MACRO_LINE21) {
+                                gdouble largestDimension =
+                                    hypot(ls->parameter[LINE21_WIDTH], ls->parameter[LINE21_HEIGHT]);
+                                offsetx = ls->parameter[LINE21_CENTER_X];
+                                offsety = ls->parameter[LINE21_CENTER_Y];
+                                widthx = widthy = largestDimension;
+                            } else if (ls->type == GERBV_APTYPE_MACRO_LINE22) {
+                                gdouble largestDimension =
+                                    hypot(ls->parameter[LINE22_WIDTH], ls->parameter[LINE22_HEIGHT]);
+
+                                offsetx = ls->parameter[LINE22_LOWER_LEFT_X] + ls->parameter[LINE22_WIDTH] / 2;
+                                offsety = ls->parameter[LINE22_LOWER_LEFT_Y] + ls->parameter[LINE22_HEIGHT] / 2;
+                                widthx = widthy = largestDimension;
+                            }
+
+                            if (!calculatedAlready) {
+                                gerber_update_min_and_max(
+                                    &boundingBox, curr_net->stop_x + offsetx, curr_net->stop_y + offsety, widthx / 2,
+                                    widthx / 2, widthy / 2, widthy / 2
+                                );
+                            }
+                            ls = ls->next;
+                        }
+                    } else {
+                        if (image->aperture[curr_net->aperture] != NULL) {
+                            aperture_sizeX = image->aperture[curr_net->aperture]->parameter[0];
+                            if ((image->aperture[curr_net->aperture]->type == GERBV_APTYPE_RECTANGLE)
+                                || (image->aperture[curr_net->aperture]->type == GERBV_APTYPE_OVAL)) {
+                                aperture_sizeY = image->aperture[curr_net->aperture]->parameter[1];
+                            } else
+                                aperture_sizeY = aperture_sizeX;
+                        } else {
+                            /* this is usually for polygon fills, where the aperture width
+                               is "zero" */
+                            aperture_sizeX = aperture_sizeY = 0;
+                        }
+
+                        /* if it's an arc path, use a special calc */
+
+                        if ((curr_net->interpolation == GERBV_INTERPOLATION_CW_CIRCULAR)
+                            || (curr_net->interpolation == GERBV_INTERPOLATION_CCW_CIRCULAR)) {
+                            calc_cirseg_bbox(curr_net->cirseg, aperture_sizeX, aperture_sizeY, &boundingBox);
+                        } else {
+                            /* check both the start and stop of the aperture points against
+                               a running min/max counter */
+                            /* Note: only check start coordinate if this isn't a flash,
+                               since the start point may be bogus if it is a flash */
+                            if (curr_net->aperture_state != GERBV_APERTURE_STATE_FLASH) {
+                                gerber_update_min_and_max(
+                                    &boundingBox, curr_net->start_x, curr_net->start_y, aperture_sizeX / 2,
+                                    aperture_sizeX / 2, aperture_sizeY / 2, aperture_sizeY / 2
+                                );
+                            }
+                            gerber_update_min_and_max(
+                                &boundingBox, curr_net->stop_x, curr_net->stop_y, aperture_sizeX / 2,
+                                aperture_sizeX / 2, aperture_sizeY / 2, aperture_sizeY / 2
+                            );
+                        }
+                    }
+                    /* update the info bounding box with this latest bounding box */
+                    /* don't change the bounding box if the polarity is clear */
+                    if (state->layer->polarity != GERBV_POLARITY_CLEAR) {
+                        gerber_update_image_min_max(&boundingBox, repeat_off_X, repeat_off_Y, image);
+                    }
+                    /* optionally update the knockout measurement box */
+                    if (knockoutMeasure) {
+                        if (boundingBox.left < knockoutLimitXmin)
+                            knockoutLimitXmin = boundingBox.left;
+                        if (boundingBox.right + repeat_off_X > knockoutLimitXmax)
+                            knockoutLimitXmax = boundingBox.right + repeat_off_X;
+                        if (boundingBox.bottom < knockoutLimitYmin)
+                            knockoutLimitYmin = boundingBox.bottom;
+                        if (boundingBox.top + repeat_off_Y > knockoutLimitYmax)
+                            knockoutLimitYmax = boundingBox.top + repeat_off_Y;
+                    }
+                    /* if we're not in a polygon fill, then update the object bounding box */
+                    if (!state->in_parea_fill) {
+                        curr_net->boundingBox = boundingBox;
+                        boundingBox           = boundingBoxNew;
+                    }
+                }
+                break;
+
+            case '\0':
+            case '\t':
+            case ' ': break;
+
+            case '\n':
+                line_num++;
+
+                /* Get <CR> char, if any, from <LF><CR> pair */
+                read = gerb_fgetc(fd);
+                if (read != '\r' && read != EOF)
+                    gerb_ungetc(fd);
+                break;
+
+            case '\r':
+                line_num++;
+
+                /* Get <LF> char, if any, from <CR><LF> pair */
+                read = gerb_fgetc(fd);
+                if (read != '\n' && read != EOF)
+                    gerb_ungetc(fd);
+                break;
+
+            default:
+                stats->unknown++;
+                gerbv_stats_printf(
+                    error_list, GERBV_MESSAGE_ERROR, -1,
+                    _("Found unknown character '%s' (0x%x) "
+                      "at line %ld in file \"%s\""),
+                    gerbv_escape_char(read), read, line_num, fd->filename
+                );
+        } /* switch((char) (read & 0xff)) */
     }
     return foundEOF;
 }
 
-
 /* ------------------------------------------------------------------ */
-/*! This is a wrapper which gets called from top level.  It 
- *  does some initialization and pre-processing, and 
+/*! This is a wrapper which gets called from top level.  It
+ *  does some initialization and pre-processing, and
  *  then calls gerber_parse_file_segment
- *  which processes the actual file.  Then it does final 
+ *  which processes the actual file.  Then it does final
  *  modifications to the image created.
  */
-gerbv_image_t *
-parse_gerb(gerb_file_t *fd, gchar *directoryPath)
-{
-    gerb_state_t *state = NULL;
-    gerbv_image_t *image = NULL;
-    gerbv_net_t *curr_net = NULL;
-    gerbv_stats_t *stats;
-    gboolean foundEOF = FALSE;
-    
+gerbv_image_t*
+parse_gerb(gerb_file_t* fd, gchar* directoryPath) {
+    gerb_state_t*  state    = NULL;
+    gerbv_image_t* image    = NULL;
+    gerbv_net_t*   curr_net = NULL;
+    gerbv_stats_t* stats;
+    gboolean       foundEOF = FALSE;
+
     /* added by t.motylewski@bfad.de
-     * many locales redefine "." as "," and so on, 
+     * many locales redefine "." as "," and so on,
      * so sscanf and strtod has problems when
      * reading files using %f format */
-    setlocale(LC_NUMERIC, "C" );
+    setlocale(LC_NUMERIC, "C");
 
-    /* 
+    /*
      * Create new state.  This is used locally to keep track
      * of the photoplotter's state as the Gerber is read in.
      */
-    state = g_new0 (gerb_state_t, 1);
+    state = g_new0(gerb_state_t, 1);
 
-    /* 
+    /*
      * Create new image.  This will be returned.
      */
     image = gerbv_create_image(image, "RS274-X (Gerber) File");
     if (image == NULL)
-	GERB_FATAL_ERROR("malloc image failed in %s()", __FUNCTION__);
-    curr_net = image->netlist;
-    image->layertype = GERBV_LAYERTYPE_RS274X;
+        GERB_FATAL_ERROR("malloc image failed in %s()", __FUNCTION__);
+    curr_net           = image->netlist;
+    image->layertype   = GERBV_LAYERTYPE_RS274X;
     image->gerbv_stats = gerbv_stats_new();
     if (image->gerbv_stats == NULL)
-	GERB_FATAL_ERROR("malloc gerbv_stats failed in %s()", __FUNCTION__);
+        GERB_FATAL_ERROR("malloc gerbv_stats failed in %s()", __FUNCTION__);
 
     stats = image->gerbv_stats;
 
     /* set active layer and netstate to point to first default one created */
-    state->layer = image->layers;
-    state->state = image->states;
+    state->layer    = image->layers;
+    state->state    = image->states;
     curr_net->layer = state->layer;
     curr_net->state = state->state;
 
@@ -767,1129 +732,1104 @@ parse_gerb(gerb_file_t *fd, gchar *directoryPath)
      * Start parsing
      */
     dprintf("In %s(), starting to parse file...\n", __func__);
-    foundEOF = gerber_parse_file_segment (1, image, state, curr_net, stats,
-					  fd, directoryPath);
+    foundEOF = gerber_parse_file_segment(1, image, state, curr_net, stats, fd, directoryPath);
 
     if (!foundEOF) {
-	gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Missing Gerber EOF code in file \"%s\""), fd->filename);
+        gerbv_stats_printf(
+            stats->error_list, GERBV_MESSAGE_ERROR, -1, _("Missing Gerber EOF code in file \"%s\""), fd->filename
+        );
     }
     g_free(state);
-    
+
     dprintf("               ... done parsing Gerber file\n");
-    gerber_update_any_running_knockout_measurements (image);
+    gerber_update_any_running_knockout_measurements(image);
     gerber_calculate_final_justify_effects(image);
 
     return image;
 } /* parse_gerb */
 
-
 /* ------------------------------------------------------------------- */
 /*! Checks for signs that this is a RS-274X file
  *  Returns TRUE if it is, FALSE if not.
  */
 gboolean
-gerber_is_rs274x_p(gerb_file_t *fd, gboolean *returnFoundBinary) 
-{
-    char *buf;
-    int len = 0;
-    char *letter;
-    int i;
+gerber_is_rs274x_p(gerb_file_t* fd, gboolean* returnFoundBinary) {
+    char*    buf;
+    int      len = 0;
+    char*    letter;
+    int      i;
     gboolean found_binary = FALSE;
-    gboolean found_ADD = FALSE;
-    gboolean found_D0 = FALSE;
-    gboolean found_D2 = FALSE;
-    gboolean found_M0 = FALSE;
-    gboolean found_M2 = FALSE;
-    gboolean found_star = FALSE;
-    gboolean found_X = FALSE;
-    gboolean found_Y = FALSE;
-   
-    dprintf ("%s(%p, %p), fd->fd = %p\n",
-		    __func__, fd, returnFoundBinary, fd->fd); 
-    buf = (char *) g_malloc(MAXL);
-    if (buf == NULL) 
-	GERB_FATAL_ERROR("malloc buf failed while checking for rs274x in %s()",
-			__FUNCTION__);
-    
+    gboolean found_ADD    = FALSE;
+    gboolean found_D0     = FALSE;
+    gboolean found_D2     = FALSE;
+    gboolean found_M0     = FALSE;
+    gboolean found_M2     = FALSE;
+    gboolean found_star   = FALSE;
+    gboolean found_X      = FALSE;
+    gboolean found_Y      = FALSE;
+
+    dprintf("%s(%p, %p), fd->fd = %p\n", __func__, fd, returnFoundBinary, fd->fd);
+    buf = (char*)g_malloc(MAXL);
+    if (buf == NULL)
+        GERB_FATAL_ERROR("malloc buf failed while checking for rs274x in %s()", __FUNCTION__);
+
     while (fgets(buf, MAXL, fd->fd) != NULL) {
-        dprintf ("buf = \"%s\"\n", buf);
-	len = strlen(buf);
-    
-	/* First look through the file for indications of its type by
-	 * checking that file is not binary (non-printing chars and white 
-	 * spaces)
-	 */
-	for (i = 0; i < len; i++) {
-	    if (!isprint((int) buf[i]) && (buf[i] != '\r') && 
-		(buf[i] != '\n') && (buf[i] != '\t')) {
-		found_binary = TRUE;
-                dprintf ("found_binary (%d)\n", buf[i]);
-	    }
-	}
-	if (g_strstr_len(buf, len, "%ADD")) {
-	    found_ADD = TRUE;
-            dprintf ("found_ADD\n");
-	}
-	if (g_strstr_len(buf, len, "D00") || g_strstr_len(buf, len, "D0")) {
-	    found_D0 = TRUE;
-            dprintf ("found_D0\n");
-	}
-	if (g_strstr_len(buf, len, "D02") || g_strstr_len(buf, len, "D2")) {
-	    found_D2 = TRUE;
-            dprintf ("found_D2\n");
-	}
-	if (g_strstr_len(buf, len, "M00") || g_strstr_len(buf, len, "M0")) {
-	    found_M0 = TRUE;
-            dprintf ("found_M0\n");
-	}
-	if (g_strstr_len(buf, len, "M02") || g_strstr_len(buf, len, "M2")) {
-	    found_M2 = TRUE;
-            dprintf ("found_M2\n");
-	}
-	if (g_strstr_len(buf, len, "*")) {
-	    found_star = TRUE;
-            dprintf ("found_star\n");
-	}
-	/* look for X<number> or Y<number> */
-	if ((letter = g_strstr_len(buf, len, "X")) != NULL) {
-	    if (isdigit((int) letter[1])) { /* grab char after X */
-		found_X = TRUE;
-                dprintf ("found_X\n");
-	    }
-	}
-	if ((letter = g_strstr_len(buf, len, "Y")) != NULL) {
-	    if (isdigit((int) letter[1])) { /* grab char after Y */
-		found_Y = TRUE;
-                dprintf ("found_Y\n");
-	    }
-	}
+        dprintf("buf = \"%s\"\n", buf);
+        len = strlen(buf);
+
+        /* First look through the file for indications of its type by
+         * checking that file is not binary (non-printing chars and white
+         * spaces)
+         */
+        for (i = 0; i < len; i++) {
+            if (!isprint((int)buf[i]) && (buf[i] != '\r') && (buf[i] != '\n') && (buf[i] != '\t')) {
+                found_binary = TRUE;
+                dprintf("found_binary (%d)\n", buf[i]);
+            }
+        }
+        if (g_strstr_len(buf, len, "%ADD")) {
+            found_ADD = TRUE;
+            dprintf("found_ADD\n");
+        }
+        if (g_strstr_len(buf, len, "D00") || g_strstr_len(buf, len, "D0")) {
+            found_D0 = TRUE;
+            dprintf("found_D0\n");
+        }
+        if (g_strstr_len(buf, len, "D02") || g_strstr_len(buf, len, "D2")) {
+            found_D2 = TRUE;
+            dprintf("found_D2\n");
+        }
+        if (g_strstr_len(buf, len, "M00") || g_strstr_len(buf, len, "M0")) {
+            found_M0 = TRUE;
+            dprintf("found_M0\n");
+        }
+        if (g_strstr_len(buf, len, "M02") || g_strstr_len(buf, len, "M2")) {
+            found_M2 = TRUE;
+            dprintf("found_M2\n");
+        }
+        if (g_strstr_len(buf, len, "*")) {
+            found_star = TRUE;
+            dprintf("found_star\n");
+        }
+        /* look for X<number> or Y<number> */
+        if ((letter = g_strstr_len(buf, len, "X")) != NULL) {
+            if (isdigit((int)letter[1])) { /* grab char after X */
+                found_X = TRUE;
+                dprintf("found_X\n");
+            }
+        }
+        if ((letter = g_strstr_len(buf, len, "Y")) != NULL) {
+            if (isdigit((int)letter[1])) { /* grab char after Y */
+                found_Y = TRUE;
+                dprintf("found_Y\n");
+            }
+        }
     }
     rewind(fd->fd);
     free(buf);
-   
+
     *returnFoundBinary = found_binary;
 
     /* Now form logical expression determining if the file is RS-274X */
-    if ((found_D0 || found_D2 || found_M0 || found_M2) && 
-	found_ADD && found_star && (found_X || found_Y)) 
-	return TRUE;
+    if ((found_D0 || found_D2 || found_M0 || found_M2) && found_ADD && found_star && (found_X || found_Y))
+        return TRUE;
 
-    
     return FALSE;
 
 } /* gerber_is_rs274x */
 
-
 /* ------------------------------------------------------------------- */
 /*! Checks for signs that this is a RS-274D file
  *  Returns TRUE if it is, FALSE if not.
  */
 gboolean
-gerber_is_rs274d_p(gerb_file_t *fd) 
-{
-    char *buf;
-    int len = 0;
-    char *letter;
-    int i;
+gerber_is_rs274d_p(gerb_file_t* fd) {
+    char*    buf;
+    int      len = 0;
+    char*    letter;
+    int      i;
     gboolean found_binary = FALSE;
-    gboolean found_ADD = FALSE;
-    gboolean found_D0 = FALSE;
-    gboolean found_D2 = FALSE;
-    gboolean found_M0 = FALSE;
-    gboolean found_M2 = FALSE;
-    gboolean found_star = FALSE;
-    gboolean found_X = FALSE;
-    gboolean found_Y = FALSE;
-    
+    gboolean found_ADD    = FALSE;
+    gboolean found_D0     = FALSE;
+    gboolean found_D2     = FALSE;
+    gboolean found_M0     = FALSE;
+    gboolean found_M2     = FALSE;
+    gboolean found_star   = FALSE;
+    gboolean found_X      = FALSE;
+    gboolean found_Y      = FALSE;
+
     buf = malloc(MAXL);
-    if (buf == NULL) 
-	GERB_FATAL_ERROR("malloc buf failed while checking for rs274d in %s()",
-			__FUNCTION__);
+    if (buf == NULL)
+        GERB_FATAL_ERROR("malloc buf failed while checking for rs274d in %s()", __FUNCTION__);
 
     while (fgets(buf, MAXL, fd->fd) != NULL) {
-	len = strlen(buf);
-    
-	/* First look through the file for indications of its type */
-    
-	/* check that file is not binary (non-printing chars */
-	for (i = 0; i < len; i++) {
-	    if (!isprint( (int) buf[i]) && (buf[i] != '\r') && 
-		(buf[i] != '\n') && (buf[i] != '\t')) {
-		found_binary = TRUE;
-	    }
-	}
-	
-	if (g_strstr_len(buf, len, "%ADD")) {
-	    found_ADD = TRUE;
-	}
-	if (g_strstr_len(buf, len, "D00") || g_strstr_len(buf, len, "D0")) {
-	    found_D0 = TRUE;
-	}
-	if (g_strstr_len(buf, len, "D02") || g_strstr_len(buf, len, "D2")) {
-	    found_D2 = TRUE;
-	}
-	if (g_strstr_len(buf, len, "M00") || g_strstr_len(buf, len, "M0")) {
-	    found_M0 = TRUE;
-	}
-	if (g_strstr_len(buf, len, "M02") || g_strstr_len(buf, len, "M2")) {
-	    found_M2 = TRUE;
-	}
-	if (g_strstr_len(buf, len, "*")) {
-	    found_star = TRUE;
-	}
-	/* look for X<number> or Y<number> */
-	if ((letter = g_strstr_len(buf, len, "X")) != NULL) {
-	    /* grab char after X */
-	    if (isdigit( (int) letter[1])) {
-		found_X = TRUE;
-	    }
-	}
-	if ((letter = g_strstr_len(buf, len, "Y")) != NULL) {
-	    /* grab char after Y */
-	    if (isdigit( (int) letter[1])) {
-		found_Y = TRUE;
-	    }
-	}
+        len = strlen(buf);
+
+        /* First look through the file for indications of its type */
+
+        /* check that file is not binary (non-printing chars */
+        for (i = 0; i < len; i++) {
+            if (!isprint((int)buf[i]) && (buf[i] != '\r') && (buf[i] != '\n') && (buf[i] != '\t')) {
+                found_binary = TRUE;
+            }
+        }
+
+        if (g_strstr_len(buf, len, "%ADD")) {
+            found_ADD = TRUE;
+        }
+        if (g_strstr_len(buf, len, "D00") || g_strstr_len(buf, len, "D0")) {
+            found_D0 = TRUE;
+        }
+        if (g_strstr_len(buf, len, "D02") || g_strstr_len(buf, len, "D2")) {
+            found_D2 = TRUE;
+        }
+        if (g_strstr_len(buf, len, "M00") || g_strstr_len(buf, len, "M0")) {
+            found_M0 = TRUE;
+        }
+        if (g_strstr_len(buf, len, "M02") || g_strstr_len(buf, len, "M2")) {
+            found_M2 = TRUE;
+        }
+        if (g_strstr_len(buf, len, "*")) {
+            found_star = TRUE;
+        }
+        /* look for X<number> or Y<number> */
+        if ((letter = g_strstr_len(buf, len, "X")) != NULL) {
+            /* grab char after X */
+            if (isdigit((int)letter[1])) {
+                found_X = TRUE;
+            }
+        }
+        if ((letter = g_strstr_len(buf, len, "Y")) != NULL) {
+            /* grab char after Y */
+            if (isdigit((int)letter[1])) {
+                found_Y = TRUE;
+            }
+        }
     }
     rewind(fd->fd);
     free(buf);
 
     /* Now form logical expression determining if the file is RS-274D */
-    if ((found_D0 || found_D2 || found_M0 || found_M2) && 
-	!found_ADD && found_star && (found_X || found_Y) && 
-	!found_binary) 
-	return TRUE;
+    if ((found_D0 || found_D2 || found_M0 || found_M2) && !found_ADD && found_star && (found_X || found_Y)
+        && !found_binary)
+        return TRUE;
 
     return FALSE;
 
 } /* gerber_is_rs274d */
 
-
 /* ------------------------------------------------------------------- */
 /*! This function reads a G number and updates the current
  *  state.  It also updates the G stats counters
  */
-static void 
-parse_G_code(gerb_file_t *fd, gerb_state_t *state,
-		gerbv_image_t *image, long int *line_num_p)
-{
-    int  op_int;
-    gerbv_format_t *format = image->format;
-    gerbv_stats_t *stats = image->gerbv_stats;
-    gerbv_error_list_t *error_list = stats->error_list;
-    int c;
-
-    op_int=gerb_fgetint(fd, NULL);
+static void
+parse_G_code(gerb_file_t* fd, gerb_state_t* state, gerbv_image_t* image, long int* line_num_p) {
+    int                 op_int;
+    gerbv_format_t*     format     = image->format;
+    gerbv_stats_t*      stats      = image->gerbv_stats;
+    gerbv_error_list_t* error_list = stats->error_list;
+    int                 c;
+
+    op_int = gerb_fgetint(fd, NULL);
 
     /* Emphasize text with new line '\n' in the beginning */
-    dprintf("\n     Found G%02d at line %ld (%s)\n",
-		    op_int, *line_num_p, gerber_g_code_name(op_int));
-    
-    switch(op_int) {
-    case 0:  /* Move */
-	/* Is this doing anything really? */
-	stats->G0++;
-	break;
-    case 1:  /* Linear Interpolation (1X scale) */
-	state->interpolation = GERBV_INTERPOLATION_LINEARx1;
-	stats->G1++;
-	break;
-    case 2:  /* Clockwise Linear Interpolation */
-	state->interpolation = GERBV_INTERPOLATION_CW_CIRCULAR;
-	stats->G2++;
-	break;
-    case 3:  /* Counter Clockwise Linear Interpolation */
-	state->interpolation = GERBV_INTERPOLATION_CCW_CIRCULAR;
-	stats->G3++;
-	break;
-    case 4:  /* Ignore Data Block */
-	/* Don't do anything, just read 'til * */
-	do {
-	    c = gerb_fgetc(fd);
-            if (c == '\r' || c == '\n') {
-                gerbv_stats_printf(error_list, GERBV_MESSAGE_WARNING, -1,
-                                   _("Found newline while parsing "
-                                     "G04 code at line %ld in file \"%s\", "
-                                     "maybe you forgot a \"*\"?"),
-                                   *line_num_p, fd->filename);
+    dprintf("\n     Found G%02d at line %ld (%s)\n", op_int, *line_num_p, gerber_g_code_name(op_int));
+
+    switch (op_int) {
+        case 0: /* Move */
+            /* Is this doing anything really? */
+            stats->G0++;
+            break;
+        case 1: /* Linear Interpolation (1X scale) */
+            state->interpolation = GERBV_INTERPOLATION_LINEARx1;
+            stats->G1++;
+            break;
+        case 2: /* Clockwise Linear Interpolation */
+            state->interpolation = GERBV_INTERPOLATION_CW_CIRCULAR;
+            stats->G2++;
+            break;
+        case 3: /* Counter Clockwise Linear Interpolation */
+            state->interpolation = GERBV_INTERPOLATION_CCW_CIRCULAR;
+            stats->G3++;
+            break;
+        case 4: /* Ignore Data Block */
+            /* Don't do anything, just read 'til * */
+            do {
+                c = gerb_fgetc(fd);
+                if (c == '\r' || c == '\n') {
+                    gerbv_stats_printf(
+                        error_list, GERBV_MESSAGE_WARNING, -1,
+                        _("Found newline while parsing "
+                          "G04 code at line %ld in file \"%s\", "
+                          "maybe you forgot a \"*\"?"),
+                        *line_num_p, fd->filename
+                    );
+                }
+            } while (c != EOF && c != '*');
+
+            stats->G4++;
+            break;
+        case 10: /* Linear Interpolation (10X scale) */
+            state->interpolation = GERBV_INTERPOLATION_LINEARx10;
+            stats->G10++;
+            break;
+        case 11: /* Linear Interpolation (0.1X scale) */
+            state->interpolation = GERBV_INTERPOLATION_LINEARx01;
+            stats->G11++;
+            break;
+        case 12: /* Linear Interpolation (0.01X scale) */
+            state->interpolation = GERBV_INTERPOLATION_LINEARx001;
+            stats->G12++;
+            break;
+        case 36: /* Turn on Polygon Area Fill */
+            state->prev_interpolation = state->interpolation;
+            state->interpolation      = GERBV_INTERPOLATION_PAREA_START;
+            state->changed            = 1;
+            stats->G36++;
+            break;
+        case 37: /* Turn off Polygon Area Fill */
+            state->interpolation = GERBV_INTERPOLATION_PAREA_END;
+            state->changed       = 1;
+            stats->G37++;
+            break;
+        case 54: /* Tool prepare */
+            /* XXX Maybe uneccesary??? */
+            if (gerb_fgetc(fd) == 'D') {
+                int a = gerb_fgetint(fd, NULL);
+                if ((a >= 0) && (a <= APERTURE_MAX)) {
+                    state->curr_aperture = a;
+                } else {
+                    gerbv_stats_printf(
+                        error_list, GERBV_MESSAGE_ERROR, -1,
+                        _("Found aperture D%02d out of bounds while parsing "
+                          "G code at line %ld in file \"%s\""),
+                        a, *line_num_p, fd->filename
+                    );
+                }
+            } else {
+                gerbv_stats_printf(
+                    error_list, GERBV_MESSAGE_ERROR, -1,
+                    _("Found unexpected code after G54 "
+                      "at line %ld in file \"%s\""),
+                    *line_num_p, fd->filename
+                );
+                /* TODO: insert error count here */
             }
-	}
-	while (c != EOF && c != '*');
-
-	stats->G4++;
-	break;
-    case 10: /* Linear Interpolation (10X scale) */
-	state->interpolation = GERBV_INTERPOLATION_LINEARx10;
-	stats->G10++;
-	break;
-    case 11: /* Linear Interpolation (0.1X scale) */
-	state->interpolation = GERBV_INTERPOLATION_LINEARx01;
-	stats->G11++;
-	break;
-    case 12: /* Linear Interpolation (0.01X scale) */
-	state->interpolation = GERBV_INTERPOLATION_LINEARx001;
-	stats->G12++;
-	break;
-    case 36: /* Turn on Polygon Area Fill */
-	state->prev_interpolation = state->interpolation;
-	state->interpolation = GERBV_INTERPOLATION_PAREA_START;
-	state->changed = 1;
-	stats->G36++;
-	break;
-    case 37: /* Turn off Polygon Area Fill */
-	state->interpolation = GERBV_INTERPOLATION_PAREA_END;
-	state->changed = 1;
-	stats->G37++;
-	break;
-    case 54: /* Tool prepare */
-	/* XXX Maybe uneccesary??? */
-	if (gerb_fgetc(fd) == 'D') {
-	    int a = gerb_fgetint(fd, NULL);
-	    if ((a >= 0) && (a <= APERTURE_MAX)) {
-		state->curr_aperture = a;
-	    } else { 
-		gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1, 
-			_("Found aperture D%02d out of bounds while parsing "
-			    "G code at line %ld in file \"%s\""),
-			a, *line_num_p, fd->filename);
-	    }
-	} else {
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Found unexpected code after G54 "
-			"at line %ld in file \"%s\""),
-		    *line_num_p, fd->filename);
-/* TODO: insert error count here */
-	}
-	stats->G54++;
-	break;
-    case 55: /* Prepare for flash */
-	stats->G55++;
-	break;
-    case 70: /* Specify inches */
-	state->state = gerbv_image_return_new_netstate (state->state);
-	state->state->unit = GERBV_UNIT_INCH;
-	stats->G70++;
-	break;
-    case 71: /* Specify millimeters */
-	state->state = gerbv_image_return_new_netstate (state->state);
-	state->state->unit = GERBV_UNIT_MM;
-	stats->G71++;
-	break;
-    case 74: /* Disable 360 circular interpolation */
-	state->mq_on = 0;
-	stats->G74++;
-	break;
-    case 75: /* Enable 360 circular interpolation */
-	state->mq_on = 1;
-	stats->G75++;
-	break;
-    case 90: /* Specify absolut format */
-	if (format) format->coordinate = GERBV_COORDINATE_ABSOLUTE;
-	stats->G90++;
-	break;
-    case 91: /* Specify incremental format */
-	if (format) format->coordinate = GERBV_COORDINATE_INCREMENTAL;
-	stats->G91++;
-	break;
-    default:
-	gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Encountered unknown G code G%02d "
-		    "at line %ld in file \"%s\""),
-		op_int, *line_num_p, fd->filename);
-	gerbv_stats_printf(error_list, GERBV_MESSAGE_WARNING, -1,
-		_("Ignoring unknown G code G%02d"), op_int);
-	stats->G_unknown++;
-/* TODO: insert error count here */
-
-	break;
+            stats->G54++;
+            break;
+        case 55: /* Prepare for flash */ stats->G55++; break;
+        case 70: /* Specify inches */
+            state->state       = gerbv_image_return_new_netstate(state->state);
+            state->state->unit = GERBV_UNIT_INCH;
+            stats->G70++;
+            break;
+        case 71: /* Specify millimeters */
+            state->state       = gerbv_image_return_new_netstate(state->state);
+            state->state->unit = GERBV_UNIT_MM;
+            stats->G71++;
+            break;
+        case 74: /* Disable 360 circular interpolation */
+            state->mq_on = 0;
+            stats->G74++;
+            break;
+        case 75: /* Enable 360 circular interpolation */
+            state->mq_on = 1;
+            stats->G75++;
+            break;
+        case 90: /* Specify absolut format */
+            if (format)
+                format->coordinate = GERBV_COORDINATE_ABSOLUTE;
+            stats->G90++;
+            break;
+        case 91: /* Specify incremental format */
+            if (format)
+                format->coordinate = GERBV_COORDINATE_INCREMENTAL;
+            stats->G91++;
+            break;
+        default:
+            gerbv_stats_printf(
+                error_list, GERBV_MESSAGE_ERROR, -1,
+                _("Encountered unknown G code G%02d "
+                  "at line %ld in file \"%s\""),
+                op_int, *line_num_p, fd->filename
+            );
+            gerbv_stats_printf(error_list, GERBV_MESSAGE_WARNING, -1, _("Ignoring unknown G code G%02d"), op_int);
+            stats->G_unknown++;
+            /* TODO: insert error count here */
+
+            break;
     }
-    
+
     return;
 } /* parse_G_code */
 
-
 /* ------------------------------------------------------------------ */
-/*! This function reads the numeric value of a D code and updates the 
+/*! This function reads the numeric value of a D code and updates the
  *  state.  It also updates the D stats counters
  */
-static void 
-parse_D_code(gerb_file_t *fd, gerb_state_t *state,
-		gerbv_image_t *image, long int *line_num_p)
-{
-    int a;
-    gerbv_stats_t *stats = image->gerbv_stats;
-    gerbv_error_list_t *error_list = stats->error_list;
+static void
+parse_D_code(gerb_file_t* fd, gerb_state_t* state, gerbv_image_t* image, long int* line_num_p) {
+    int                 a;
+    gerbv_stats_t*      stats      = image->gerbv_stats;
+    gerbv_error_list_t* error_list = stats->error_list;
 
     a = gerb_fgetint(fd, NULL);
     dprintf("     Found D%02d code at line %ld\n", a, *line_num_p);
 
-    switch(a) {
-    case 0 : /* Invalid code */
-        gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Found invalid D00 code at line %ld in file \"%s\""),
-		*line_num_p, fd->filename);
-        stats->D_error++;
-	break;
-    case 1 : /* Exposure on */
-	state->aperture_state = GERBV_APERTURE_STATE_ON;
-	state->changed = 1;
-	stats->D1++;
-	break;
-    case 2 : /* Exposure off */
-	state->aperture_state = GERBV_APERTURE_STATE_OFF;
-	state->changed = 1;
-	stats->D2++;
-	break;
-    case 3 : /* Flash aperture */
-	state->aperture_state = GERBV_APERTURE_STATE_FLASH;
-	state->changed = 1;
-	stats->D3++;
-	break;
-    default: /* Aperture in use */
-	if ((a >= 0) && (a <= APERTURE_MAX)) {
-	    state->curr_aperture = a;
-	    
-	} else {
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Found out of bounds aperture D%02d "
-			"at line %ld in file \"%s\""),
-		    a, *line_num_p, fd->filename);
-	    stats->D_error++;
-	}
-	state->changed = 0;
-	break;
+    switch (a) {
+        case 0: /* Invalid code */
+            gerbv_stats_printf(
+                error_list, GERBV_MESSAGE_ERROR, -1, _("Found invalid D00 code at line %ld in file \"%s\""),
+                *line_num_p, fd->filename
+            );
+            stats->D_error++;
+            break;
+        case 1: /* Exposure on */
+            state->aperture_state = GERBV_APERTURE_STATE_ON;
+            state->changed        = 1;
+            stats->D1++;
+            break;
+        case 2: /* Exposure off */
+            state->aperture_state = GERBV_APERTURE_STATE_OFF;
+            state->changed        = 1;
+            stats->D2++;
+            break;
+        case 3: /* Flash aperture */
+            state->aperture_state = GERBV_APERTURE_STATE_FLASH;
+            state->changed        = 1;
+            stats->D3++;
+            break;
+        default: /* Aperture in use */
+            if ((a >= 0) && (a <= APERTURE_MAX)) {
+                state->curr_aperture = a;
+
+            } else {
+                gerbv_stats_printf(
+                    error_list, GERBV_MESSAGE_ERROR, -1,
+                    _("Found out of bounds aperture D%02d "
+                      "at line %ld in file \"%s\""),
+                    a, *line_num_p, fd->filename
+                );
+                stats->D_error++;
+            }
+            state->changed = 0;
+            break;
     }
-    
+
     return;
 } /* parse_D_code */
 
-
 /* ------------------------------------------------------------------ */
 static int
-parse_M_code(gerb_file_t *fd, gerbv_image_t *image, long int *line_num_p)
-{
-    int op_int;
-    gerbv_stats_t *stats = image->gerbv_stats;
-    
-    op_int=gerb_fgetint(fd, NULL);
-    
+parse_M_code(gerb_file_t* fd, gerbv_image_t* image, long int* line_num_p) {
+    int            op_int;
+    gerbv_stats_t* stats = image->gerbv_stats;
+
+    op_int = gerb_fgetint(fd, NULL);
+
     switch (op_int) {
-    case 0:  /* Program stop */
-	stats->M0++;
-	return 1;
-    case 1:  /* Optional stop */
-	stats->M1++;
-	return 2;
-    case 2:  /* End of program */
-	stats->M2++;
-	return 3;
-    default:
-	gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Encountered unknown M%02d code at line %ld in file \"%s\""),
-		op_int, *line_num_p, fd->filename);
-	gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1,
-		_("Ignoring unknown M%02d code"), op_int);
-	stats->M_unknown++;
+        case 0: /* Program stop */ stats->M0++; return 1;
+        case 1: /* Optional stop */ stats->M1++; return 2;
+        case 2: /* End of program */ stats->M2++; return 3;
+        default:
+            gerbv_stats_printf(
+                stats->error_list, GERBV_MESSAGE_ERROR, -1,
+                _("Encountered unknown M%02d code at line %ld in file \"%s\""), op_int, *line_num_p, fd->filename
+            );
+            gerbv_stats_printf(stats->error_list, GERBV_MESSAGE_WARNING, -1, _("Ignoring unknown M%02d code"), op_int);
+            stats->M_unknown++;
     }
     return 0;
 } /* parse_M_code */
 
 /* ------------------------------------------------------------------ */
-static void 
-parse_rs274x(gint levelOfRecursion, gerb_file_t *fd, gerbv_image_t *image, 
-	     gerb_state_t *state, gerbv_net_t *curr_net, gerbv_stats_t *stats, 
-	     gchar *directoryPath, long int *line_num_p)
-{
-    int op[2];
-    char str[3];
-    int tmp;
-    gerbv_aperture_t *a = NULL;
-    gerbv_amacro_t *tmp_amacro;
-    int ano;
-    gdouble scale = 1.0;
-    gerbv_error_list_t *error_list = stats->error_list;
-    
+static void
+parse_rs274x(
+    gint levelOfRecursion, gerb_file_t* fd, gerbv_image_t* image, gerb_state_t* state, gerbv_net_t* curr_net,
+    gerbv_stats_t* stats, gchar* directoryPath, long int* line_num_p
+) {
+    int                 op[2];
+    char                str[3];
+    int                 tmp;
+    gerbv_aperture_t*   a = NULL;
+    gerbv_amacro_t*     tmp_amacro;
+    int                 ano;
+    gdouble             scale      = 1.0;
+    gerbv_error_list_t* error_list = stats->error_list;
+
     if (state->state->unit == GERBV_UNIT_MM)
-    	scale = 25.4;
-    
+        scale = 25.4;
+
     op[0] = gerb_fgetc(fd);
     op[1] = gerb_fgetc(fd);
-    
+
     if (op[0] == EOF || op[1] == EOF)
-	gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Unexpected EOF found in file \"%s\""), fd->filename);
-
-    switch (A2I(op[0], op[1])){
-	
-	/* 
-	 * Directive parameters 
-	 */
-    case A2I('A','S'): /* Axis Select */
-	op[0] = gerb_fgetc(fd);
-	op[1] = gerb_fgetc(fd);
-	state->state = gerbv_image_return_new_netstate (state->state);
-	
-	if (op[0] == EOF || op[1] == EOF)
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Unexpected EOF found in file \"%s\""), fd->filename);
-	
-	if (((op[0] == 'A') && (op[1] == 'Y')) ||
-	    ((op[0] == 'B') && (op[1] == 'X'))) {
-	    state->state->axisSelect = GERBV_AXIS_SELECT_SWAPAB;
-	} else {
-	    state->state->axisSelect = GERBV_AXIS_SELECT_NOSELECT;
-	}
-
-	op[0] = gerb_fgetc(fd);
-	op[1] = gerb_fgetc(fd);
-	
-	if (op[0] == EOF || op[1] == EOF)
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Unexpected EOF found in file \"%s\""), fd->filename);
-
-	if (((op[0] == 'A') && (op[1] == 'Y')) ||
-	    ((op[0] == 'B') && (op[1] == 'X'))) {
-	    state->state->axisSelect = GERBV_AXIS_SELECT_SWAPAB;
-	} else {
-	    state->state->axisSelect = GERBV_AXIS_SELECT_NOSELECT;
-	}
-	break;
-
-    case A2I('F','S'): /* Format Statement */
-	image->format = g_new0 (gerbv_format_t,1);
-	
-	switch (gerb_fgetc(fd)) {
-	case 'L':
-	    image->format->omit_zeros = GERBV_OMIT_ZEROS_LEADING;
-	    break;
-	case 'T':
-	    image->format->omit_zeros = GERBV_OMIT_ZEROS_TRAILING;
-	    break;
-	case 'D':
-	    image->format->omit_zeros = GERBV_OMIT_ZEROS_EXPLICIT;
-	    break;
-	default:
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("EagleCad bug detected: Undefined handling of zeros "
-			"in format code at line %ld in file \"%s\""),
-		    *line_num_p, fd->filename);
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_WARNING, -1,
-		    _("Defaulting to omitting leading zeros"));
-	    gerb_ungetc(fd);
-	    image->format->omit_zeros = GERBV_OMIT_ZEROS_LEADING;
-	}
-	
-	switch (gerb_fgetc(fd)) {
-	case 'A':
-	    image->format->coordinate = GERBV_COORDINATE_ABSOLUTE;
-	    break;
-	case 'I':
-	    image->format->coordinate = GERBV_COORDINATE_INCREMENTAL;
-	    break;
-	default:
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Invalid coordinate type defined in format code "
-			"at line %ld in file \"%s\""),
-		    *line_num_p, fd->filename);
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_WARNING, -1,
-		    _("Defaulting to absolute coordinates"));
-	    image->format->coordinate = GERBV_COORDINATE_ABSOLUTE;
-	}
-	op[0] = gerb_fgetc(fd);
-	while((op[0] != '*')&&(op[0] != EOF)) {
-	    switch (op[0]) {
-	    case 'N':
-		op[0] = (char)gerb_fgetc(fd);
-		image->format->lim_seqno = op[0] - '0';
-		break;
-	    case 'G':
-		op[0] = (char)gerb_fgetc(fd);
-		image->format->lim_gf = op[0] - '0';
-		break;
-	    case 'D':
-		op[0] = (char)gerb_fgetc(fd);
-		image->format->lim_pf = op[0] - '0';
-		break;
-	    case 'M':
-		op[0] = (char)gerb_fgetc(fd);
-		image->format->lim_mf = op[0] - '0';
-		break;
-	    case 'X' :
-		op[0] = gerb_fgetc(fd);
-		if ((op[0] < '0') || (op[0] > '6')) {
-		    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			    _("Illegal format size '%s' "
-				"at line %ld in file \"%s\""),
-			    gerbv_escape_char(op[0]),
-			    *line_num_p, fd->filename);
-		}
-		image->format->x_int = op[0] - '0';
-		op[0] = gerb_fgetc(fd);
-		if ((op[0] < '0') || (op[0] > '6')) {
-		    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			    _("Illegal format size '%s' "
-				"at line %ld in file \"%s\""),
-			    gerbv_escape_char(op[0]),
-			    *line_num_p, fd->filename);
-		}
-		image->format->x_dec = op[0] - '0';
-		break;
-	    case 'Y':
-		op[0] = gerb_fgetc(fd);
-		if ((op[0] < '0') || (op[0] > '6')) {
-		    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			    _("Illegal format size '%s' "
-				"at line %ld in file \"%s\""),
-			    gerbv_escape_char(op[0]),
-			    *line_num_p, fd->filename);
-		}
-		image->format->y_int = op[0] - '0';
-		op[0] = gerb_fgetc(fd);
-		if ((op[0] < '0') || (op[0] > '6')) {
-		    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			    _("Illegal format size '%s' "
-			       "at line %ld in file \"%s\""),
-			    gerbv_escape_char(op[0]),
-			    *line_num_p, fd->filename);
-		}
-		image->format->y_dec = op[0] - '0';
-		break;
-	    default :
-		gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Illegal format statement '%s' "
-			   "at line %ld in file \"%s\""),
-			gerbv_escape_char(op[0]),
-			*line_num_p, fd->filename);
-		gerbv_stats_printf(error_list, GERBV_MESSAGE_WARNING, -1,
-			_("Ignoring invalid format statement"));
-	    }
-	    op[0] = gerb_fgetc(fd);
-	}
-	break;
-    case A2I('M','I'): /* Mirror Image */
-	op[0] = gerb_fgetc(fd);
-	state->state = gerbv_image_return_new_netstate (state->state);
-	
-	while ((op[0] != '*')&&(op[0] != EOF)) {
-            gint readValue=0;
-	    switch (op[0]) {
-	    case 'A' :
-		readValue = gerb_fgetint(fd, NULL);
-		if (readValue == 1) {
-		    if (state->state->mirrorState == GERBV_MIRROR_STATE_FLIPB)
-			state->state->mirrorState=GERBV_MIRROR_STATE_FLIPAB;
-		    else
-			state->state->mirrorState=GERBV_MIRROR_STATE_FLIPA;
-		}
-		break;
-	    case 'B' :
-		readValue = gerb_fgetint(fd, NULL);
-		if (readValue == 1) {
-		    if (state->state->mirrorState == GERBV_MIRROR_STATE_FLIPA)
-			state->state->mirrorState=GERBV_MIRROR_STATE_FLIPAB;
-		    else
-			state->state->mirrorState=GERBV_MIRROR_STATE_FLIPB;
-		}
-		break;
-	    default :
-		gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Wrong character '%s' in mirror "
-			    "at line %ld in file \"%s\""),
-			gerbv_escape_char(op[0]), *line_num_p, fd->filename);
-	    }
-	    op[0] = gerb_fgetc(fd);
-	}
-	break;  
-    case A2I('M','O'): /* Mode of Units */
-	op[0] = gerb_fgetc(fd);
-	op[1] = gerb_fgetc(fd);
-	
-	if (op[0] == EOF || op[1] == EOF)
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Unexpected EOF found in file \"%s\""), fd->filename);
-
-	switch (A2I(op[0],op[1])) {
-	case A2I('I','N'):
-	    state->state = gerbv_image_return_new_netstate (state->state);
-	    state->state->unit = GERBV_UNIT_INCH;
-	    break;
-	case A2I('M','M'):
-	    state->state = gerbv_image_return_new_netstate (state->state);
-	    state->state->unit = GERBV_UNIT_MM;
-	    break;
-	default:
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Illegal unit '%s%s' at line %ld in file \"%s\""),
-		    gerbv_escape_char(op[0]), gerbv_escape_char(op[1]),
-		    *line_num_p, fd->filename);
-	}
-	break;
-    case A2I('O','F'): /* Offset */
-	op[0] = gerb_fgetc(fd);
-	
-	while ((op[0] != '*')&&(op[0] != EOF)) {
-	    switch (op[0]) {
-	    case 'A' :
-		state->state->offsetA = gerb_fgetdouble(fd) / scale;
-		break;
-	    case 'B' :
-		state->state->offsetB = gerb_fgetdouble(fd) / scale;
-		break;
-	    default :
-		gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Wrong character '%s' in offset "
-			    "at line %ld in file \"%s\""),
-			gerbv_escape_char(op[0]), *line_num_p, fd->filename);
-	    }
-	    op[0] = gerb_fgetc(fd);
-	}
-	break;
-    case A2I('I','F'): /* Include file */
-	{
-	    gchar *includeFilename = gerb_fgetstring(fd, '*');
-	    
-	    if (includeFilename) {
-		gchar *fullPath;
-		if (!g_path_is_absolute(includeFilename)) {
-		    fullPath = g_build_filename (directoryPath, includeFilename, NULL);
-		} else {
-		    fullPath = g_strdup (includeFilename);
-		}
-		if (levelOfRecursion < 10) {
-		    gerb_file_t *includefd = NULL;
-		    
-		    includefd = gerb_fopen(fullPath);
-		    if (includefd) {
-			gerber_parse_file_segment (levelOfRecursion + 1, image, state, curr_net, stats, includefd, directoryPath);
-			gerb_fclose(includefd);
-		    } else {
-			gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-				_("Included file \"%s\" cannot be found "
-				    "at line %ld in file \"%s\""),
-				fullPath, *line_num_p, fd->filename);
-		    }
-		    g_free (fullPath);
-		} else {
-		    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			    _("Parser encountered more than 10 levels of "
-				"include file recursion which is not allowed "
-				"by the RS-274X spec"));
-		}
-		g_free (includeFilename);
-	    }
-	}
-	break;
-    case A2I('I','O'): /* Image offset */
-	op[0] = gerb_fgetc(fd);
-	
-	while ((op[0] != '*')&&(op[0] != EOF)) {
-	    switch (op[0]) {
-	    case 'A' :
-		image->info->offsetA = gerb_fgetdouble(fd) / scale;
-		break;
-	    case 'B' :
-		image->info->offsetB = gerb_fgetdouble(fd) / scale;
-		break;
-	    default :
-		gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Wrong character '%s' in image offset "
-			    "at line %ld in file \"%s\""),
-			gerbv_escape_char(op[0]), *line_num_p, fd->filename);
-	    }
-	    op[0] = gerb_fgetc(fd);
-	}
-	break;
-    case A2I('S','F'): /* Scale Factor */
-     state->state = gerbv_image_return_new_netstate (state->state);
-	if (gerb_fgetc(fd) == 'A')
-	    state->state->scaleA = gerb_fgetdouble(fd);
-	else 
-	    gerb_ungetc(fd);
-	if (gerb_fgetc(fd) == 'B')
-	    state->state->scaleB = gerb_fgetdouble(fd);
-	else 
-	    gerb_ungetc(fd);
-	break;
-    case A2I('I','C'): /* Input Code */
-	/* Thanks to Stephen Adam for providing this information. As he writes:
-	 *      btw, here's a logic puzzle for you.  If you need to
-	 * read the gerber file to see how it's encoded, then
-	 * how can you read it?
-	 */
-	op[0] = gerb_fgetc(fd);
-	op[1] = gerb_fgetc(fd);
-	
-	if (op[0] == EOF || op[1] == EOF)
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Unexpected EOF found in file \"%s\""), fd->filename);
-
-	switch (A2I(op[0],op[1])) {
-	case A2I('A','S'):
-	    image->info->encoding = GERBV_ENCODING_ASCII;
-	    break;
-	case A2I('E','B'):
-	    image->info->encoding = GERBV_ENCODING_EBCDIC;
-	    break;
-	case A2I('B','C'):
-	    image->info->encoding = GERBV_ENCODING_BCD;
-	    break;
-	case A2I('I','S'):
-	    image->info->encoding = GERBV_ENCODING_ISO_ASCII;
-	    break;
-	case A2I('E','I'):
-	    image->info->encoding = GERBV_ENCODING_EIA;
-	    break;
-	default:
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Unknown input code (IC) '%s%s' "
-			"at line %ld in file \"%s\""),
-		    gerbv_escape_char(op[0]), gerbv_escape_char(op[1]),
-		    *line_num_p, fd->filename);
-	}
-	break;
-	
-	/* Image parameters */
-    case A2I('I','J'): /* Image Justify */
-	op[0] = gerb_fgetc(fd);
-	image->info->imageJustifyTypeA = GERBV_JUSTIFY_LOWERLEFT;
-	image->info->imageJustifyTypeB = GERBV_JUSTIFY_LOWERLEFT;
-	image->info->imageJustifyOffsetA = 0.0;
-	image->info->imageJustifyOffsetB = 0.0;
-	while ((op[0] != '*')&&(op[0] != EOF)) {
-	    switch (op[0]) {
-	    case 'A' :
-	    	op[0] = gerb_fgetc(fd);
-	    	if (op[0] == 'C') {
-		    image->info->imageJustifyTypeA = GERBV_JUSTIFY_CENTERJUSTIFY;
-	    	} else if (op[0] == 'L') {
-		    image->info->imageJustifyTypeA = GERBV_JUSTIFY_LOWERLEFT;
-	    	} else {
-		    gerb_ungetc (fd);
-		    image->info->imageJustifyOffsetA = gerb_fgetdouble(fd) / scale;
-	    	}
-		break;
-	    case 'B' :
-		op[0] = gerb_fgetc(fd);
-	    	if (op[0] == 'C') {
-		    image->info->imageJustifyTypeB = GERBV_JUSTIFY_CENTERJUSTIFY;
-	    	} else if (op[0] == 'L') {
-		    image->info->imageJustifyTypeB = GERBV_JUSTIFY_LOWERLEFT;
-	    	} else {
-		    gerb_ungetc (fd);
-		    image->info->imageJustifyOffsetB = gerb_fgetdouble(fd) / scale;
-	    	}
-		break;
-	    default :
-		gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Wrong character '%s' in image justify "
-			    "at line %ld in file \"%s\""),
-			gerbv_escape_char(op[0]), *line_num_p, fd->filename);
-	    }
-	    op[0] = gerb_fgetc(fd);
-	}
-	break;
-    case A2I('I','N'): /* Image Name */
-	image->info->name = gerb_fgetstring(fd, '*');
-	break;
-    case A2I('I','P'): /* Image Polarity */
-	
-	for (ano = 0; ano < 3; ano++) {
-	    op[0] = gerb_fgetc(fd);
-	    if (op[0] == EOF) {
-		gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Unexpected EOF while reading image polarity (IP) "
-			    "in file \"%s\""), fd->filename);
-	    }
-	    str[ano] = (char)op[0];
-	}
-	
-	if (strncmp(str, "POS", 3) == 0) 
-	    image->info->polarity = GERBV_POLARITY_POSITIVE;
-	else if (strncmp(str, "NEG", 3) == 0)
-	    image->info->polarity = GERBV_POLARITY_NEGATIVE;
-	else {
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Unknown polarity '%s%s%s' "
-			"at line %ld in file \"%s\""),
-		    gerbv_escape_char(str[0]), gerbv_escape_char(str[1]),
-		    gerbv_escape_char(str[2]), *line_num_p, fd->filename);
-	}
-	break;
-    case A2I('I','R'): /* Image Rotation */
-	tmp = gerb_fgetint(fd, NULL) % 360;
-	if (tmp == 0)
-	    image->info->imageRotation = 0.0;
-	else if (tmp == 90)
-	    image->info->imageRotation = M_PI_2;
-	else if (tmp == 180)
-	    image->info->imageRotation = M_PI;
-	else if (tmp == 270)
-	    image->info->imageRotation = M_PI + M_PI_2;
-	else {
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Image rotation must be 0, 90, 180 or 270 "
-			"(is actually %d) at line %ld in file \"%s\""),
-		    tmp, *line_num_p, fd->filename);
-	}
-	break;
-    case A2I('P','F'): /* Plotter Film */
-	image->info->plotterFilm = gerb_fgetstring(fd, '*');
-	break;
-	
-	/* Aperture parameters */
-    case A2I('A','D'): /* Aperture Description */
-	a = (gerbv_aperture_t *) g_new0 (gerbv_aperture_t,1);
-
-	ano = parse_aperture_definition(fd, a, image, scale, line_num_p);
-	if (ano == -1) {
-		/* error with line parse, so just quietly ignore */
-	}
-	else if ((ano >= 0) && (ano <= APERTURE_MAX)) {
-	    a->unit = state->state->unit;
-	    image->aperture[ano] = a;
-	    dprintf("     In %s(), adding new aperture to aperture list ...\n",
-			    __func__);
-	    gerbv_stats_add_aperture(stats->aperture_list,
-				    -1, ano, 
-				    a->type,
-				    a->parameter);
-	    gerbv_stats_add_to_D_list(stats->D_code_list,
-				     ano);
-	    if (ano < APERTURE_MIN) {
-		    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			    _("Aperture number out of bounds %d "
-				"at line %ld in file \"%s\""),
-			    ano, *line_num_p, fd->filename);
-	    }
-	} else {
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Aperture number out of bounds %d "
-		       "at line %ld in file \"%s\""),
-		    ano, *line_num_p, fd->filename);
-	}
-	/* Add aperture info to stats->aperture_list here */
-	
-	break;
-    case A2I('A','M'): /* Aperture Macro */
-	tmp_amacro = image->amacro;
-	image->amacro = parse_aperture_macro(fd);
-	if (image->amacro) {
-	    image->amacro->next = tmp_amacro;
+        gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1, _("Unexpected EOF found in file \"%s\""), fd->filename);
+
+    switch (A2I(op[0], op[1])) {
+
+        /*
+         * Directive parameters
+         */
+        case A2I('A', 'S'): /* Axis Select */
+            op[0]        = gerb_fgetc(fd);
+            op[1]        = gerb_fgetc(fd);
+            state->state = gerbv_image_return_new_netstate(state->state);
+
+            if (op[0] == EOF || op[1] == EOF)
+                gerbv_stats_printf(
+                    error_list, GERBV_MESSAGE_ERROR, -1, _("Unexpected EOF found in file \"%s\""), fd->filename
+                );
+
+            if (((op[0] == 'A') && (op[1] == 'Y')) || ((op[0] == 'B') && (op[1] == 'X'))) {
+                state->state->axisSelect = GERBV_AXIS_SELECT_SWAPAB;
+            } else {
+                state->state->axisSelect = GERBV_AXIS_SELECT_NOSELECT;
+            }
+
+            op[0] = gerb_fgetc(fd);
+            op[1] = gerb_fgetc(fd);
+
+            if (op[0] == EOF || op[1] == EOF)
+                gerbv_stats_printf(
+                    error_list, GERBV_MESSAGE_ERROR, -1, _("Unexpected EOF found in file \"%s\""), fd->filename
+                );
+
+            if (((op[0] == 'A') && (op[1] == 'Y')) || ((op[0] == 'B') && (op[1] == 'X'))) {
+                state->state->axisSelect = GERBV_AXIS_SELECT_SWAPAB;
+            } else {
+                state->state->axisSelect = GERBV_AXIS_SELECT_NOSELECT;
+            }
+            break;
+
+        case A2I('F', 'S'): /* Format Statement */
+            image->format = g_new0(gerbv_format_t, 1);
+
+            switch (gerb_fgetc(fd)) {
+                case 'L': image->format->omit_zeros = GERBV_OMIT_ZEROS_LEADING; break;
+                case 'T': image->format->omit_zeros = GERBV_OMIT_ZEROS_TRAILING; break;
+                case 'D': image->format->omit_zeros = GERBV_OMIT_ZEROS_EXPLICIT; break;
+                default:
+                    gerbv_stats_printf(
+                        error_list, GERBV_MESSAGE_ERROR, -1,
+                        _("EagleCad bug detected: Undefined handling of zeros "
+                          "in format code at line %ld in file \"%s\""),
+                        *line_num_p, fd->filename
+                    );
+                    gerbv_stats_printf(
+                        error_list, GERBV_MESSAGE_WARNING, -1, _("Defaulting to omitting leading zeros")
+                    );
+                    gerb_ungetc(fd);
+                    image->format->omit_zeros = GERBV_OMIT_ZEROS_LEADING;
+            }
+
+            switch (gerb_fgetc(fd)) {
+                case 'A': image->format->coordinate = GERBV_COORDINATE_ABSOLUTE; break;
+                case 'I': image->format->coordinate = GERBV_COORDINATE_INCREMENTAL; break;
+                default:
+                    gerbv_stats_printf(
+                        error_list, GERBV_MESSAGE_ERROR, -1,
+                        _("Invalid coordinate type defined in format code "
+                          "at line %ld in file \"%s\""),
+                        *line_num_p, fd->filename
+                    );
+                    gerbv_stats_printf(error_list, GERBV_MESSAGE_WARNING, -1, _("Defaulting to absolute coordinates"));
+                    image->format->coordinate = GERBV_COORDINATE_ABSOLUTE;
+            }
+            op[0] = gerb_fgetc(fd);
+            while ((op[0] != '*') && (op[0] != EOF)) {
+                switch (op[0]) {
+                    case 'N':
+                        op[0]                    = (char)gerb_fgetc(fd);
+                        image->format->lim_seqno = op[0] - '0';
+                        break;
+                    case 'G':
+                        op[0]                 = (char)gerb_fgetc(fd);
+                        image->format->lim_gf = op[0] - '0';
+                        break;
+                    case 'D':
+                        op[0]                 = (char)gerb_fgetc(fd);
+                        image->format->lim_pf = op[0] - '0';
+                        break;
+                    case 'M':
+                        op[0]                 = (char)gerb_fgetc(fd);
+                        image->format->lim_mf = op[0] - '0';
+                        break;
+                    case 'X':
+                        op[0] = gerb_fgetc(fd);
+                        if ((op[0] < '0') || (op[0] > '6')) {
+                            gerbv_stats_printf(
+                                error_list, GERBV_MESSAGE_ERROR, -1,
+                                _("Illegal format size '%s' "
+                                  "at line %ld in file \"%s\""),
+                                gerbv_escape_char(op[0]), *line_num_p, fd->filename
+                            );
+                        }
+                        image->format->x_int = op[0] - '0';
+                        op[0]                = gerb_fgetc(fd);
+                        if ((op[0] < '0') || (op[0] > '6')) {
+                            gerbv_stats_printf(
+                                error_list, GERBV_MESSAGE_ERROR, -1,
+                                _("Illegal format size '%s' "
+                                  "at line %ld in file \"%s\""),
+                                gerbv_escape_char(op[0]), *line_num_p, fd->filename
+                            );
+                        }
+                        image->format->x_dec = op[0] - '0';
+                        break;
+                    case 'Y':
+                        op[0] = gerb_fgetc(fd);
+                        if ((op[0] < '0') || (op[0] > '6')) {
+                            gerbv_stats_printf(
+                                error_list, GERBV_MESSAGE_ERROR, -1,
+                                _("Illegal format size '%s' "
+                                  "at line %ld in file \"%s\""),
+                                gerbv_escape_char(op[0]), *line_num_p, fd->filename
+                            );
+                        }
+                        image->format->y_int = op[0] - '0';
+                        op[0]                = gerb_fgetc(fd);
+                        if ((op[0] < '0') || (op[0] > '6')) {
+                            gerbv_stats_printf(
+                                error_list, GERBV_MESSAGE_ERROR, -1,
+                                _("Illegal format size '%s' "
+                                  "at line %ld in file \"%s\""),
+                                gerbv_escape_char(op[0]), *line_num_p, fd->filename
+                            );
+                        }
+                        image->format->y_dec = op[0] - '0';
+                        break;
+                    default:
+                        gerbv_stats_printf(
+                            error_list, GERBV_MESSAGE_ERROR, -1,
+                            _("Illegal format statement '%s' "
+                              "at line %ld in file \"%s\""),
+                            gerbv_escape_char(op[0]), *line_num_p, fd->filename
+                        );
+                        gerbv_stats_printf(
+                            error_list, GERBV_MESSAGE_WARNING, -1, _("Ignoring invalid format statement")
+                        );
+                }
+                op[0] = gerb_fgetc(fd);
+            }
+            break;
+        case A2I('M', 'I'): /* Mirror Image */
+            op[0]        = gerb_fgetc(fd);
+            state->state = gerbv_image_return_new_netstate(state->state);
+
+            while ((op[0] != '*') && (op[0] != EOF)) {
+                gint readValue = 0;
+                switch (op[0]) {
+                    case 'A':
+                        readValue = gerb_fgetint(fd, NULL);
+                        if (readValue == 1) {
+                            if (state->state->mirrorState == GERBV_MIRROR_STATE_FLIPB)
+                                state->state->mirrorState = GERBV_MIRROR_STATE_FLIPAB;
+                            else
+                                state->state->mirrorState = GERBV_MIRROR_STATE_FLIPA;
+                        }
+                        break;
+                    case 'B':
+                        readValue = gerb_fgetint(fd, NULL);
+                        if (readValue == 1) {
+                            if (state->state->mirrorState == GERBV_MIRROR_STATE_FLIPA)
+                                state->state->mirrorState = GERBV_MIRROR_STATE_FLIPAB;
+                            else
+                                state->state->mirrorState = GERBV_MIRROR_STATE_FLIPB;
+                        }
+                        break;
+                    default:
+                        gerbv_stats_printf(
+                            error_list, GERBV_MESSAGE_ERROR, -1,
+                            _("Wrong character '%s' in mirror "
+                              "at line %ld in file \"%s\""),
+                            gerbv_escape_char(op[0]), *line_num_p, fd->filename
+                        );
+                }
+                op[0] = gerb_fgetc(fd);
+            }
+            break;
+        case A2I('M', 'O'): /* Mode of Units */
+            op[0] = gerb_fgetc(fd);
+            op[1] = gerb_fgetc(fd);
+
+            if (op[0] == EOF || op[1] == EOF)
+                gerbv_stats_printf(
+                    error_list, GERBV_MESSAGE_ERROR, -1, _("Unexpected EOF found in file \"%s\""), fd->filename
+                );
+
+            switch (A2I(op[0], op[1])) {
+                case A2I('I', 'N'):
+                    state->state       = gerbv_image_return_new_netstate(state->state);
+                    state->state->unit = GERBV_UNIT_INCH;
+                    break;
+                case A2I('M', 'M'):
+                    state->state       = gerbv_image_return_new_netstate(state->state);
+                    state->state->unit = GERBV_UNIT_MM;
+                    break;
+                default:
+                    gerbv_stats_printf(
+                        error_list, GERBV_MESSAGE_ERROR, -1, _("Illegal unit '%s%s' at line %ld in file \"%s\""),
+                        gerbv_escape_char(op[0]), gerbv_escape_char(op[1]), *line_num_p, fd->filename
+                    );
+            }
+            break;
+        case A2I('O', 'F'): /* Offset */
+            op[0] = gerb_fgetc(fd);
+
+            while ((op[0] != '*') && (op[0] != EOF)) {
+                switch (op[0]) {
+                    case 'A': state->state->offsetA = gerb_fgetdouble(fd) / scale; break;
+                    case 'B': state->state->offsetB = gerb_fgetdouble(fd) / scale; break;
+                    default:
+                        gerbv_stats_printf(
+                            error_list, GERBV_MESSAGE_ERROR, -1,
+                            _("Wrong character '%s' in offset "
+                              "at line %ld in file \"%s\""),
+                            gerbv_escape_char(op[0]), *line_num_p, fd->filename
+                        );
+                }
+                op[0] = gerb_fgetc(fd);
+            }
+            break;
+        case A2I('I', 'F'): /* Include file */
+            {
+                gchar* includeFilename = gerb_fgetstring(fd, '*');
+
+                if (includeFilename) {
+                    gchar* fullPath;
+                    if (!g_path_is_absolute(includeFilename)) {
+                        fullPath = g_build_filename(directoryPath, includeFilename, NULL);
+                    } else {
+                        fullPath = g_strdup(includeFilename);
+                    }
+                    if (levelOfRecursion < 10) {
+                        gerb_file_t* includefd = NULL;
+
+                        includefd = gerb_fopen(fullPath);
+                        if (includefd) {
+                            gerber_parse_file_segment(
+                                levelOfRecursion + 1, image, state, curr_net, stats, includefd, directoryPath
+                            );
+                            gerb_fclose(includefd);
+                        } else {
+                            gerbv_stats_printf(
+                                error_list, GERBV_MESSAGE_ERROR, -1,
+                                _("Included file \"%s\" cannot be found "
+                                  "at line %ld in file \"%s\""),
+                                fullPath, *line_num_p, fd->filename
+                            );
+                        }
+                        g_free(fullPath);
+                    } else {
+                        gerbv_stats_printf(
+                            error_list, GERBV_MESSAGE_ERROR, -1,
+                            _("Parser encountered more than 10 levels of "
+                              "include file recursion which is not allowed "
+                              "by the RS-274X spec")
+                        );
+                    }
+                    g_free(includeFilename);
+                }
+            }
+            break;
+        case A2I('I', 'O'): /* Image offset */
+            op[0] = gerb_fgetc(fd);
+
+            while ((op[0] != '*') && (op[0] != EOF)) {
+                switch (op[0]) {
+                    case 'A': image->info->offsetA = gerb_fgetdouble(fd) / scale; break;
+                    case 'B': image->info->offsetB = gerb_fgetdouble(fd) / scale; break;
+                    default:
+                        gerbv_stats_printf(
+                            error_list, GERBV_MESSAGE_ERROR, -1,
+                            _("Wrong character '%s' in image offset "
+                              "at line %ld in file \"%s\""),
+                            gerbv_escape_char(op[0]), *line_num_p, fd->filename
+                        );
+                }
+                op[0] = gerb_fgetc(fd);
+            }
+            break;
+        case A2I('S', 'F'): /* Scale Factor */
+            state->state = gerbv_image_return_new_netstate(state->state);
+            if (gerb_fgetc(fd) == 'A')
+                state->state->scaleA = gerb_fgetdouble(fd);
+            else
+                gerb_ungetc(fd);
+            if (gerb_fgetc(fd) == 'B')
+                state->state->scaleB = gerb_fgetdouble(fd);
+            else
+                gerb_ungetc(fd);
+            break;
+        case A2I('I', 'C'): /* Input Code */
+            /* Thanks to Stephen Adam for providing this information. As he writes:
+             *      btw, here's a logic puzzle for you.  If you need to
+             * read the gerber file to see how it's encoded, then
+             * how can you read it?
+             */
+            op[0] = gerb_fgetc(fd);
+            op[1] = gerb_fgetc(fd);
+
+            if (op[0] == EOF || op[1] == EOF)
+                gerbv_stats_printf(
+                    error_list, GERBV_MESSAGE_ERROR, -1, _("Unexpected EOF found in file \"%s\""), fd->filename
+                );
+
+            switch (A2I(op[0], op[1])) {
+                case A2I('A', 'S'): image->info->encoding = GERBV_ENCODING_ASCII; break;
+                case A2I('E', 'B'): image->info->encoding = GERBV_ENCODING_EBCDIC; break;
+                case A2I('B', 'C'): image->info->encoding = GERBV_ENCODING_BCD; break;
+                case A2I('I', 'S'): image->info->encoding = GERBV_ENCODING_ISO_ASCII; break;
+                case A2I('E', 'I'): image->info->encoding = GERBV_ENCODING_EIA; break;
+                default:
+                    gerbv_stats_printf(
+                        error_list, GERBV_MESSAGE_ERROR, -1,
+                        _("Unknown input code (IC) '%s%s' "
+                          "at line %ld in file \"%s\""),
+                        gerbv_escape_char(op[0]), gerbv_escape_char(op[1]), *line_num_p, fd->filename
+                    );
+            }
+            break;
+
+        /* Image parameters */
+        case A2I('I', 'J'): /* Image Justify */
+            op[0]                            = gerb_fgetc(fd);
+            image->info->imageJustifyTypeA   = GERBV_JUSTIFY_LOWERLEFT;
+            image->info->imageJustifyTypeB   = GERBV_JUSTIFY_LOWERLEFT;
+            image->info->imageJustifyOffsetA = 0.0;
+            image->info->imageJustifyOffsetB = 0.0;
+            while ((op[0] != '*') && (op[0] != EOF)) {
+                switch (op[0]) {
+                    case 'A':
+                        op[0] = gerb_fgetc(fd);
+                        if (op[0] == 'C') {
+                            image->info->imageJustifyTypeA = GERBV_JUSTIFY_CENTERJUSTIFY;
+                        } else if (op[0] == 'L') {
+                            image->info->imageJustifyTypeA = GERBV_JUSTIFY_LOWERLEFT;
+                        } else {
+                            gerb_ungetc(fd);
+                            image->info->imageJustifyOffsetA = gerb_fgetdouble(fd) / scale;
+                        }
+                        break;
+                    case 'B':
+                        op[0] = gerb_fgetc(fd);
+                        if (op[0] == 'C') {
+                            image->info->imageJustifyTypeB = GERBV_JUSTIFY_CENTERJUSTIFY;
+                        } else if (op[0] == 'L') {
+                            image->info->imageJustifyTypeB = GERBV_JUSTIFY_LOWERLEFT;
+                        } else {
+                            gerb_ungetc(fd);
+                            image->info->imageJustifyOffsetB = gerb_fgetdouble(fd) / scale;
+                        }
+                        break;
+                    default:
+                        gerbv_stats_printf(
+                            error_list, GERBV_MESSAGE_ERROR, -1,
+                            _("Wrong character '%s' in image justify "
+                              "at line %ld in file \"%s\""),
+                            gerbv_escape_char(op[0]), *line_num_p, fd->filename
+                        );
+                }
+                op[0] = gerb_fgetc(fd);
+            }
+            break;
+        case A2I('I', 'N'): /* Image Name */ image->info->name = gerb_fgetstring(fd, '*'); break;
+        case A2I('I', 'P'): /* Image Polarity */
+
+            for (ano = 0; ano < 3; ano++) {
+                op[0] = gerb_fgetc(fd);
+                if (op[0] == EOF) {
+                    gerbv_stats_printf(
+                        error_list, GERBV_MESSAGE_ERROR, -1,
+                        _("Unexpected EOF while reading image polarity (IP) "
+                          "in file \"%s\""),
+                        fd->filename
+                    );
+                }
+                str[ano] = (char)op[0];
+            }
+
+            if (strncmp(str, "POS", 3) == 0)
+                image->info->polarity = GERBV_POLARITY_POSITIVE;
+            else if (strncmp(str, "NEG", 3) == 0)
+                image->info->polarity = GERBV_POLARITY_NEGATIVE;
+            else {
+                gerbv_stats_printf(
+                    error_list, GERBV_MESSAGE_ERROR, -1,
+                    _("Unknown polarity '%s%s%s' "
+                      "at line %ld in file \"%s\""),
+                    gerbv_escape_char(str[0]), gerbv_escape_char(str[1]), gerbv_escape_char(str[2]), *line_num_p,
+                    fd->filename
+                );
+            }
+            break;
+        case A2I('I', 'R'): /* Image Rotation */
+            tmp = gerb_fgetint(fd, NULL) % 360;
+            if (tmp == 0)
+                image->info->imageRotation = 0.0;
+            else if (tmp == 90)
+                image->info->imageRotation = M_PI_2;
+            else if (tmp == 180)
+                image->info->imageRotation = M_PI;
+            else if (tmp == 270)
+                image->info->imageRotation = M_PI + M_PI_2;
+            else {
+                gerbv_stats_printf(
+                    error_list, GERBV_MESSAGE_ERROR, -1,
+                    _("Image rotation must be 0, 90, 180 or 270 "
+                      "(is actually %d) at line %ld in file \"%s\""),
+                    tmp, *line_num_p, fd->filename
+                );
+            }
+            break;
+        case A2I('P', 'F'): /* Plotter Film */ image->info->plotterFilm = gerb_fgetstring(fd, '*'); break;
+
+        /* Aperture parameters */
+        case A2I('A', 'D'): /* Aperture Description */
+            a = (gerbv_aperture_t*)g_new0(gerbv_aperture_t, 1);
+
+            ano = parse_aperture_definition(fd, a, image, scale, line_num_p);
+            if (ano == -1) {
+                /* error with line parse, so just quietly ignore */
+            } else if ((ano >= 0) && (ano <= APERTURE_MAX)) {
+                a->unit              = state->state->unit;
+                image->aperture[ano] = a;
+                dprintf("     In %s(), adding new aperture to aperture list ...\n", __func__);
+                gerbv_stats_add_aperture(stats->aperture_list, -1, ano, a->type, a->parameter);
+                gerbv_stats_add_to_D_list(stats->D_code_list, ano);
+                if (ano < APERTURE_MIN) {
+                    gerbv_stats_printf(
+                        error_list, GERBV_MESSAGE_ERROR, -1,
+                        _("Aperture number out of bounds %d "
+                          "at line %ld in file \"%s\""),
+                        ano, *line_num_p, fd->filename
+                    );
+                }
+            } else {
+                gerbv_stats_printf(
+                    error_list, GERBV_MESSAGE_ERROR, -1,
+                    _("Aperture number out of bounds %d "
+                      "at line %ld in file \"%s\""),
+                    ano, *line_num_p, fd->filename
+                );
+            }
+            /* Add aperture info to stats->aperture_list here */
+
+            break;
+        case A2I('A', 'M'): /* Aperture Macro */
+            tmp_amacro    = image->amacro;
+            image->amacro = parse_aperture_macro(fd);
+            if (image->amacro) {
+                image->amacro->next = tmp_amacro;
 #ifdef AMACRO_DEBUG
-	    print_program(image->amacro);
+                print_program(image->amacro);
 #endif
-	} else {
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Failed to parse aperture macro "
-		       "at line %ld in file \"%s\""),
-		    *line_num_p, fd->filename);
-	}
-	// return, since we want to skip the later back-up loop
-	return;
-	/* Layer */
-    case A2I('L','N'): /* Layer Name */
-	state->layer = gerbv_image_return_new_layer (state->layer);
-	state->layer->name = gerb_fgetstring(fd, '*');
-	break;
-    case A2I('L','P'): /* Layer Polarity */
-	state->layer = gerbv_image_return_new_layer (state->layer);
-	switch (gerb_fgetc(fd)) {
-	case 'D': /* Dark Polarity (default) */
-	    state->layer->polarity = GERBV_POLARITY_DARK;
-	    break;
-	case 'C': /* Clear Polarity */
-	    state->layer->polarity = GERBV_POLARITY_CLEAR;
-	    break;
-	default:
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Unknown layer polarity '%s' "
-		       "at line %ld in file \"%s\""),
-		    gerbv_escape_char(op[0]), *line_num_p, fd->filename);
-	}
-	break;
-    case A2I('K','O'): /* Knock Out */
-        state->layer = gerbv_image_return_new_layer (state->layer);
-        gerber_update_any_running_knockout_measurements (image);
-        /* reset any previous knockout measurements */
-        knockoutMeasure = FALSE;
-        op[0] = gerb_fgetc(fd);
-	if (op[0] == '*') { /* Disable previous SR parameters */
-	    state->layer->knockout.type = GERBV_KNOCKOUT_TYPE_NOKNOCKOUT;
-	    break;
-	} else if (op[0] == 'C') {
-	    state->layer->knockout.polarity = GERBV_POLARITY_CLEAR;
-	} else if (op[0] == 'D') {
-	    state->layer->knockout.polarity = GERBV_POLARITY_DARK;
-	} else {
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Knockout must supply a polarity (C, D, or *) "
-			"at line %ld in file \"%s\""),
-		    *line_num_p, fd->filename);
-	}
-	state->layer->knockout.lowerLeftX = 0.0;
-	state->layer->knockout.lowerLeftY = 0.0;
-	state->layer->knockout.width = 0.0;
-	state->layer->knockout.height = 0.0;
-	state->layer->knockout.border = 0.0;
-	state->layer->knockout.firstInstance = TRUE;
-	op[0] = gerb_fgetc(fd);
-	while ((op[0] != '*')&&(op[0] != EOF)) { 
-	    switch (op[0]) {
-	    case 'X':
-	        state->layer->knockout.type = GERBV_KNOCKOUT_TYPE_FIXEDKNOCK;
-		state->layer->knockout.lowerLeftX = gerb_fgetdouble(fd) / scale;
-		break;
-	    case 'Y':
-	        state->layer->knockout.type = GERBV_KNOCKOUT_TYPE_FIXEDKNOCK;
-		state->layer->knockout.lowerLeftY = gerb_fgetdouble(fd) / scale;
-		break;
-	    case 'I':
-	        state->layer->knockout.type = GERBV_KNOCKOUT_TYPE_FIXEDKNOCK;
-		state->layer->knockout.width = gerb_fgetdouble(fd) / scale;
-		break;
-	    case 'J':
-	        state->layer->knockout.type = GERBV_KNOCKOUT_TYPE_FIXEDKNOCK;
-		state->layer->knockout.height = gerb_fgetdouble(fd) / scale;
-		break;
-	    case 'K':
-	        state->layer->knockout.type = GERBV_KNOCKOUT_TYPE_BORDER;
-	        state->layer->knockout.border = gerb_fgetdouble(fd) / scale;
-	        /* this is a bordered knockout, so we need to start measuring the
-	           size of a square bordering all future components */
-	        knockoutMeasure = TRUE;
-	        knockoutLimitXmin = HUGE_VAL;
-	        knockoutLimitYmin = HUGE_VAL;
-	        knockoutLimitXmax = -HUGE_VAL;
-	        knockoutLimitYmax = -HUGE_VAL;
-	        knockoutLayer = state->layer;
-	        break;
-	    default:
-		gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Unknown variable in knockout "
-			    "at line %ld in file \"%s\""),
-			*line_num_p, fd->filename);
-	    }
-	    op[0] = gerb_fgetc(fd);
-	}
-	break;
-    case A2I('S','R'): /* Step and Repeat */
-        /* start by generating a new layer (duplicating previous layer settings */
-        state->layer = gerbv_image_return_new_layer (state->layer);
-	op[0] = gerb_fgetc(fd);
-	if (op[0] == '*') { /* Disable previous SR parameters */
-	    state->layer->stepAndRepeat.X = 1;
-	    state->layer->stepAndRepeat.Y = 1;
-	    state->layer->stepAndRepeat.dist_X = 0.0;
-	    state->layer->stepAndRepeat.dist_Y = 0.0;
-	    break;
-	}
-	while ((op[0] != '*')&&(op[0] != EOF)) {
-	    switch (op[0]) {
-	    case 'X':
-		state->layer->stepAndRepeat.X = gerb_fgetint(fd, NULL);
-		break;
-	    case 'Y':
-		state->layer->stepAndRepeat.Y = gerb_fgetint(fd, NULL);
-		break;
-	    case 'I':
-		state->layer->stepAndRepeat.dist_X = gerb_fgetdouble(fd) / scale;
-		break;
-	    case 'J':
-		state->layer->stepAndRepeat.dist_Y = gerb_fgetdouble(fd) / scale;
-		break;
-	    default:
-		gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-			_("Step-and-repeat parameter error "
-			   "at line %ld in file \"%s\""),
-			*line_num_p, fd->filename);
-	    }
-	    
-	    /*
-	     * Repeating 0 times in any direction would disable the whole plot, and
-	     * is probably not intended. At least one other tool (viewmate) seems
-	     * to interpret 0-time repeating as repeating just once too.
-	     */
-	    if(state->layer->stepAndRepeat.X == 0)
-		state->layer->stepAndRepeat.X = 1;
-	    if(state->layer->stepAndRepeat.Y == 0)
-		state->layer->stepAndRepeat.Y = 1;
-	    
-	    op[0] = gerb_fgetc(fd);
-	}
-	break;
-	/* is this an actual RS274X command??  It isn't explainined in the spec... */
-    case A2I('R','O'):
-	state->layer = gerbv_image_return_new_layer (state->layer);
-	
-	state->layer->rotation = DEG2RAD(gerb_fgetdouble(fd));
-	op[0] = gerb_fgetc(fd);
-	if (op[0] != '*') {
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Error in layer rotation command "
-		       "at line %ld in file \"%s\""),
-		    *line_num_p, fd->filename);
-	}
-	break;
-    default:
-	gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Unknown RS-274X extension found %%%s%s%% "
-		    "at line %ld in file \"%s\""),
-		gerbv_escape_char(op[0]), gerbv_escape_char(op[1]),
-		*line_num_p, fd->filename);
+            } else {
+                gerbv_stats_printf(
+                    error_list, GERBV_MESSAGE_ERROR, -1,
+                    _("Failed to parse aperture macro "
+                      "at line %ld in file \"%s\""),
+                    *line_num_p, fd->filename
+                );
+            }
+            // return, since we want to skip the later back-up loop
+            return;
+        /* Layer */
+        case A2I('L', 'N'): /* Layer Name */
+            state->layer       = gerbv_image_return_new_layer(state->layer);
+            state->layer->name = gerb_fgetstring(fd, '*');
+            break;
+        case A2I('L', 'P'): /* Layer Polarity */
+            state->layer = gerbv_image_return_new_layer(state->layer);
+            switch (gerb_fgetc(fd)) {
+                case 'D': /* Dark Polarity (default) */ state->layer->polarity = GERBV_POLARITY_DARK; break;
+                case 'C': /* Clear Polarity */ state->layer->polarity = GERBV_POLARITY_CLEAR; break;
+                default:
+                    gerbv_stats_printf(
+                        error_list, GERBV_MESSAGE_ERROR, -1,
+                        _("Unknown layer polarity '%s' "
+                          "at line %ld in file \"%s\""),
+                        gerbv_escape_char(op[0]), *line_num_p, fd->filename
+                    );
+            }
+            break;
+        case A2I('K', 'O'): /* Knock Out */
+            state->layer = gerbv_image_return_new_layer(state->layer);
+            gerber_update_any_running_knockout_measurements(image);
+            /* reset any previous knockout measurements */
+            knockoutMeasure = FALSE;
+            op[0]           = gerb_fgetc(fd);
+            if (op[0] == '*') { /* Disable previous SR parameters */
+                state->layer->knockout.type = GERBV_KNOCKOUT_TYPE_NOKNOCKOUT;
+                break;
+            } else if (op[0] == 'C') {
+                state->layer->knockout.polarity = GERBV_POLARITY_CLEAR;
+            } else if (op[0] == 'D') {
+                state->layer->knockout.polarity = GERBV_POLARITY_DARK;
+            } else {
+                gerbv_stats_printf(
+                    error_list, GERBV_MESSAGE_ERROR, -1,
+                    _("Knockout must supply a polarity (C, D, or *) "
+                      "at line %ld in file \"%s\""),
+                    *line_num_p, fd->filename
+                );
+            }
+            state->layer->knockout.lowerLeftX    = 0.0;
+            state->layer->knockout.lowerLeftY    = 0.0;
+            state->layer->knockout.width         = 0.0;
+            state->layer->knockout.height        = 0.0;
+            state->layer->knockout.border        = 0.0;
+            state->layer->knockout.firstInstance = TRUE;
+            op[0]                                = gerb_fgetc(fd);
+            while ((op[0] != '*') && (op[0] != EOF)) {
+                switch (op[0]) {
+                    case 'X':
+                        state->layer->knockout.type       = GERBV_KNOCKOUT_TYPE_FIXEDKNOCK;
+                        state->layer->knockout.lowerLeftX = gerb_fgetdouble(fd) / scale;
+                        break;
+                    case 'Y':
+                        state->layer->knockout.type       = GERBV_KNOCKOUT_TYPE_FIXEDKNOCK;
+                        state->layer->knockout.lowerLeftY = gerb_fgetdouble(fd) / scale;
+                        break;
+                    case 'I':
+                        state->layer->knockout.type  = GERBV_KNOCKOUT_TYPE_FIXEDKNOCK;
+                        state->layer->knockout.width = gerb_fgetdouble(fd) / scale;
+                        break;
+                    case 'J':
+                        state->layer->knockout.type   = GERBV_KNOCKOUT_TYPE_FIXEDKNOCK;
+                        state->layer->knockout.height = gerb_fgetdouble(fd) / scale;
+                        break;
+                    case 'K':
+                        state->layer->knockout.type   = GERBV_KNOCKOUT_TYPE_BORDER;
+                        state->layer->knockout.border = gerb_fgetdouble(fd) / scale;
+                        /* this is a bordered knockout, so we need to start measuring the
+                           size of a square bordering all future components */
+                        knockoutMeasure   = TRUE;
+                        knockoutLimitXmin = HUGE_VAL;
+                        knockoutLimitYmin = HUGE_VAL;
+                        knockoutLimitXmax = -HUGE_VAL;
+                        knockoutLimitYmax = -HUGE_VAL;
+                        knockoutLayer     = state->layer;
+                        break;
+                    default:
+                        gerbv_stats_printf(
+                            error_list, GERBV_MESSAGE_ERROR, -1,
+                            _("Unknown variable in knockout "
+                              "at line %ld in file \"%s\""),
+                            *line_num_p, fd->filename
+                        );
+                }
+                op[0] = gerb_fgetc(fd);
+            }
+            break;
+        case A2I('S', 'R'): /* Step and Repeat */
+            /* start by generating a new layer (duplicating previous layer settings */
+            state->layer = gerbv_image_return_new_layer(state->layer);
+            op[0]        = gerb_fgetc(fd);
+            if (op[0] == '*') { /* Disable previous SR parameters */
+                state->layer->stepAndRepeat.X      = 1;
+                state->layer->stepAndRepeat.Y      = 1;
+                state->layer->stepAndRepeat.dist_X = 0.0;
+                state->layer->stepAndRepeat.dist_Y = 0.0;
+                break;
+            }
+            while ((op[0] != '*') && (op[0] != EOF)) {
+                switch (op[0]) {
+                    case 'X': state->layer->stepAndRepeat.X = gerb_fgetint(fd, NULL); break;
+                    case 'Y': state->layer->stepAndRepeat.Y = gerb_fgetint(fd, NULL); break;
+                    case 'I': state->layer->stepAndRepeat.dist_X = gerb_fgetdouble(fd) / scale; break;
+                    case 'J': state->layer->stepAndRepeat.dist_Y = gerb_fgetdouble(fd) / scale; break;
+                    default:
+                        gerbv_stats_printf(
+                            error_list, GERBV_MESSAGE_ERROR, -1,
+                            _("Step-and-repeat parameter error "
+                              "at line %ld in file \"%s\""),
+                            *line_num_p, fd->filename
+                        );
+                }
+
+                /*
+                 * Repeating 0 times in any direction would disable the whole plot, and
+                 * is probably not intended. At least one other tool (viewmate) seems
+                 * to interpret 0-time repeating as repeating just once too.
+                 */
+                if (state->layer->stepAndRepeat.X == 0)
+                    state->layer->stepAndRepeat.X = 1;
+                if (state->layer->stepAndRepeat.Y == 0)
+                    state->layer->stepAndRepeat.Y = 1;
+
+                op[0] = gerb_fgetc(fd);
+            }
+            break;
+        /* is this an actual RS274X command??  It isn't explainined in the spec... */
+        case A2I('R', 'O'):
+            state->layer = gerbv_image_return_new_layer(state->layer);
+
+            state->layer->rotation = DEG2RAD(gerb_fgetdouble(fd));
+            op[0]                  = gerb_fgetc(fd);
+            if (op[0] != '*') {
+                gerbv_stats_printf(
+                    error_list, GERBV_MESSAGE_ERROR, -1,
+                    _("Error in layer rotation command "
+                      "at line %ld in file \"%s\""),
+                    *line_num_p, fd->filename
+                );
+            }
+            break;
+        default:
+            gerbv_stats_printf(
+                error_list, GERBV_MESSAGE_ERROR, -1,
+                _("Unknown RS-274X extension found %%%s%s%% "
+                  "at line %ld in file \"%s\""),
+                gerbv_escape_char(op[0]), gerbv_escape_char(op[1]), *line_num_p, fd->filename
+            );
     }
 
     // make sure we read until the trailing * character
     // first, backspace once in case we already read the trailing *
     gerb_ungetc(fd);
     do {
-    	tmp = gerb_fgetc(fd);
+        tmp = gerb_fgetc(fd);
     } while (tmp != EOF && tmp != '*');
 
     return;
 } /* parse_rs274x */
 
-
 /*
  * Stack declarations and operations to be used by the simple engine that
  * executes the parsed aperture macros.
  */
 typedef struct {
-    double *stack;
-    size_t sp;
-    size_t capacity;
+    double* stack;
+    size_t  sp;
+    size_t  capacity;
 } macro_stack_t;
 
+static macro_stack_t*
+new_stack(size_t stack_size) {
+    macro_stack_t* s;
 
-static macro_stack_t *
-new_stack(size_t stack_size)
-{
-    macro_stack_t *s;
-
-    s = (macro_stack_t *) g_new0 (macro_stack_t,1);
-    s->stack = (double *) g_new0 (double, stack_size);
-    s->sp = 0;
+    s           = (macro_stack_t*)g_new0(macro_stack_t, 1);
+    s->stack    = (double*)g_new0(double, stack_size);
+    s->sp       = 0;
     s->capacity = stack_size;
     return s;
 } /* new_stack */
 
-
 static void
-free_stack(macro_stack_t *s)
-{
+free_stack(macro_stack_t* s) {
     if (s && s->stack)
-	free(s->stack);
+        free(s->stack);
 
     if (s)
-	free(s);
+        free(s);
 
     return;
 } /* free_stack */
 
-
 static void
-push(macro_stack_t *s, double val)
-{
+push(macro_stack_t* s, double val) {
     if (s->sp >= s->capacity) {
         GERB_FATAL_ERROR(_("push will overflow stack capacity"));
         return;
@@ -1898,449 +1838,437 @@ push(macro_stack_t *s, double val)
     return;
 } /* push */
 
-
 static int
-pop(macro_stack_t *s, double *value)
-{
+pop(macro_stack_t* s, double* value) {
     /* Check if we try to pop an empty stack */
     if (s->sp == 0) {
-	return -1;
+        return -1;
     }
-    
+
     *value = s->stack[--s->sp];
     return 0;
 } /* pop */
 
-
 /* ------------------------------------------------------------------ */
 static int
-simplify_aperture_macro(gerbv_aperture_t *aperture, gdouble scale)
-{
-    const int extra_stack_size = 10;
-    macro_stack_t *s;
-    gerbv_instruction_t *ip;
-    int handled = 1, nuf_parameters = 0, i, j, clearOperatorUsed = FALSE;
-    double *lp; /* Local copy of parameters */
-    double tmp[2] = {0.0, 0.0};
-    gerbv_aperture_type_t type = GERBV_APTYPE_NONE;
-    gerbv_simplified_amacro_t *sam;
+simplify_aperture_macro(gerbv_aperture_t* aperture, gdouble scale) {
+    const int                  extra_stack_size = 10;
+    macro_stack_t*             s;
+    gerbv_instruction_t*       ip;
+    int                        handled = 1, nuf_parameters = 0, i, j, clearOperatorUsed = FALSE;
+    double*                    lp; /* Local copy of parameters */
+    double                     tmp[2] = { 0.0, 0.0 };
+    gerbv_aperture_type_t      type   = GERBV_APTYPE_NONE;
+    gerbv_simplified_amacro_t* sam;
 
     if (aperture == NULL)
-	GERB_FATAL_ERROR(_("aperture NULL in simplify aperture macro"));
+        GERB_FATAL_ERROR(_("aperture NULL in simplify aperture macro"));
 
     if (aperture->amacro == NULL)
-	GERB_FATAL_ERROR(_("aperture->amacro NULL in simplify aperture macro"));
+        GERB_FATAL_ERROR(_("aperture->amacro NULL in simplify aperture macro"));
 
     /* Allocate stack for VM */
     s = new_stack(aperture->amacro->nuf_push + extra_stack_size);
-    if (s == NULL) 
-	GERB_FATAL_ERROR("malloc stack failed in %s()", __FUNCTION__);
+    if (s == NULL)
+        GERB_FATAL_ERROR("malloc stack failed in %s()", __FUNCTION__);
 
     /* Make a copy of the parameter list that we can rewrite if necessary */
-    lp = g_new (double,APERTURE_PARAMETERS_MAX);
+    lp = g_new(double, APERTURE_PARAMETERS_MAX);
 
     memcpy(lp, aperture->parameter, sizeof(double) * APERTURE_PARAMETERS_MAX);
-    
-    for(ip = aperture->amacro->program; ip != NULL; ip = ip->next) {
-	switch(ip->opcode) {
-	case GERBV_OPCODE_NOP:
-	    break;
-	case GERBV_OPCODE_PUSH :
-	    push(s, ip->data.fval);
-	    break;
-        case GERBV_OPCODE_PPUSH : {
-	    ssize_t const idx = ip->data.ival - 1;
-	    if ((idx < 0) || (idx >= APERTURE_PARAMETERS_MAX))
-		GERB_FATAL_ERROR(_("Tried to access oob aperture"));
-	    push(s, lp[idx]);
-	    break;
-	}
-	case GERBV_OPCODE_PPOP: {
-	    if (pop(s, &tmp[0]) < 0)
-		GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
-	    ssize_t const idx = ip->data.ival - 1;
-	    if ((idx < 0) || (idx >= APERTURE_PARAMETERS_MAX))
-		GERB_FATAL_ERROR(_("Tried to access oob aperture"));
-	    lp[idx] = tmp[0];
-	    break;
-	}
-	case GERBV_OPCODE_ADD :
-	    if (pop(s, &tmp[0]) < 0)
-		GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
-	    if (pop(s, &tmp[1]) < 0)
-		GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
-	    push(s, tmp[1] + tmp[0]);
-	    break;
-	case GERBV_OPCODE_SUB :
-	    if (pop(s, &tmp[0]) < 0)
-		GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
-	    if (pop(s, &tmp[1]) < 0)
-		GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
-	    push(s, tmp[1] - tmp[0]);
-	    break;
-	case GERBV_OPCODE_MUL :
-	    if (pop(s, &tmp[0]) < 0)
-		GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
-	    if (pop(s, &tmp[1]) < 0)
-		GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
-	    push(s, tmp[1] * tmp[0]);
-	    break;
-	case GERBV_OPCODE_DIV :
-	    if (pop(s, &tmp[0]) < 0)
-		GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
-	    if (pop(s, &tmp[1]) < 0)
-		GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
-	    push(s, tmp[1] / tmp[0]);
-	    break;
-	case GERBV_OPCODE_PRIM :
-	    /* 
-	     * This handles the exposure thing in the aperture macro
-	     * The exposure is always the first element on stack independent
-	     * of aperture macro.
-	     */
-	    switch(ip->data.ival) {
-	    case 1:
-		dprintf("  Aperture macro circle [1] (");
-		type = GERBV_APTYPE_MACRO_CIRCLE;
-		nuf_parameters = 4;
-		break;
-	    case 3:
-		break;
-	    case 4 :
-		dprintf("  Aperture macro outline [4] (");
-		type = GERBV_APTYPE_MACRO_OUTLINE;
-		/*
-		 * Number of parameters are:
-		 * - number of points defined in entry 1 of the stack + 
-		 *   start point. Times two since it is both X and Y.
-		 * - Then three more; exposure,  nuf points and rotation.
-		 *
-		 * @warning Calculation must be guarded against signed integer
-		 *     overflow
-		 *
-		 * @see CVE-2021-40394
-		 */
-		int const sstack = (int)s->stack[1];
-		if ((sstack < 0) || (sstack >= INT_MAX / 4)) {
-			GERB_COMPILE_ERROR(_("Possible signed integer overflow "
-					"in calculating number of parameters "
-					"to aperture macro, will clamp to "
-					"(%d)"), APERTURE_PARAMETERS_MAX);
-			nuf_parameters = APERTURE_PARAMETERS_MAX;
-		} else {
-			nuf_parameters = (sstack + 1) * 2 + 3;
-		}
-		break;
-	    case 5 :
-		dprintf("  Aperture macro polygon [5] (");
-		type = GERBV_APTYPE_MACRO_POLYGON;
-		nuf_parameters = 6;
-		break;
-	    case 6 :
-		dprintf("  Aperture macro moire [6] (");
-		type = GERBV_APTYPE_MACRO_MOIRE;
-		nuf_parameters = 9;
-		break;
-	    case 7 :
-		dprintf("  Aperture macro thermal [7] (");
-		type = GERBV_APTYPE_MACRO_THERMAL;
-		nuf_parameters = 6;
-		break;
-	    case 2  :
-	    case 20 :
-		dprintf("  Aperture macro line 20/2 (");
-		type = GERBV_APTYPE_MACRO_LINE20;
-		nuf_parameters = 7;
-		break;
-	    case 21 :
-		dprintf("  Aperture macro line 21 (");
-		type = GERBV_APTYPE_MACRO_LINE21;
-		nuf_parameters = 6;
-		break;
-	    case 22 :
-		dprintf("  Aperture macro line 22 (");
-		type = GERBV_APTYPE_MACRO_LINE22;
-		nuf_parameters = 6;
-		break;
-	    default :
-		handled = 0;
-	    }
-
-	    if (type != GERBV_APTYPE_NONE) { 
-		if (nuf_parameters > APERTURE_PARAMETERS_MAX) {
-			GERB_COMPILE_ERROR(_("Number of parameters to aperture macro (%d) "
-					"are more than gerbv is able to store (%d)"),
-					nuf_parameters, APERTURE_PARAMETERS_MAX);
-			nuf_parameters = APERTURE_PARAMETERS_MAX;
-		}
-
-		/*
-		 * Create struct for simplified aperture macro and
-		 * start filling in the blanks.
-		 */
-		sam = g_new (gerbv_simplified_amacro_t, 1);
-		sam->type = type;
-		sam->next = NULL;
-		memset(sam->parameter, 0, 
-		       sizeof(double) * APERTURE_PARAMETERS_MAX);
-
-		/* CVE-2021-40400
-		 */
-		if (nuf_parameters > s->capacity) {
-			GERB_COMPILE_ERROR(_("Number of parameters to aperture macro (%d) "
-					"capped to stack capacity (%zu)"),
-					nuf_parameters, s->capacity);
-			nuf_parameters = s->capacity;
-		}
-		memcpy(sam->parameter, s->stack, 
-		       sizeof(double) *  nuf_parameters);
-		
-		/* convert any mm values to inches */
-		switch (type) {
-		    case GERBV_APTYPE_MACRO_CIRCLE:
-			if (fabs(sam->parameter[0]) < 0.001)
-			    clearOperatorUsed = TRUE;
-			sam->parameter[1]/=scale;
-			sam->parameter[2]/=scale;
-			sam->parameter[3]/=scale;
-			break;
-		    case GERBV_APTYPE_MACRO_OUTLINE:
-			if (fabs(sam->parameter[0]) < 0.001)
-			    clearOperatorUsed = TRUE;
-			for (j=2; j<nuf_parameters-1; j++){
-			    sam->parameter[j]/=scale;
-			}
-			break;
-		    case GERBV_APTYPE_MACRO_POLYGON:
-			if (fabs(sam->parameter[0]) < 0.001)
-			    clearOperatorUsed = TRUE;
-			sam->parameter[2]/=scale;
-			sam->parameter[3]/=scale;
-			sam->parameter[4]/=scale;
-			break;
-		    case GERBV_APTYPE_MACRO_MOIRE:
-			sam->parameter[0]/=scale;
-			sam->parameter[1]/=scale;
-			sam->parameter[2]/=scale;
-			sam->parameter[3]/=scale;
-			sam->parameter[4]/=scale;
-			sam->parameter[6]/=scale;
-			sam->parameter[7]/=scale;
-			break;
-		    case GERBV_APTYPE_MACRO_THERMAL:
-			sam->parameter[0]/=scale;
-			sam->parameter[1]/=scale;
-			sam->parameter[2]/=scale;
-			sam->parameter[3]/=scale;
-			sam->parameter[4]/=scale;
-			break;
-		    case GERBV_APTYPE_MACRO_LINE20:
-			if (fabs(sam->parameter[0]) < 0.001)
-			    clearOperatorUsed = TRUE;
-			sam->parameter[1]/=scale;
-			sam->parameter[2]/=scale;
-			sam->parameter[3]/=scale;
-			sam->parameter[4]/=scale;
-			sam->parameter[5]/=scale;
-			break;
-		    case GERBV_APTYPE_MACRO_LINE21:
-		    case GERBV_APTYPE_MACRO_LINE22:
-			if (fabs(sam->parameter[0]) < 0.001)
-			    clearOperatorUsed = TRUE;
-			sam->parameter[1]/=scale;
-			sam->parameter[2]/=scale;
-			sam->parameter[3]/=scale;
-			sam->parameter[4]/=scale;
-			break;
-		    default: 
-			break;			
-		}
-		/* 
-		 * Add this simplified aperture macro to the end of the list
-		 * of simplified aperture macros. If first entry, put it
-		 * in the top.
-		 */
-		if (aperture->simplified == NULL) {
-		    aperture->simplified = sam;
-		} else {
-		    gerbv_simplified_amacro_t *tmp_sam;
-		    tmp_sam = aperture->simplified;
-		    while (tmp_sam->next != NULL) {
-			tmp_sam = tmp_sam->next;
-		    }
-		    tmp_sam->next = sam;
-		}
+
+    for (ip = aperture->amacro->program; ip != NULL; ip = ip->next) {
+        switch (ip->opcode) {
+            case GERBV_OPCODE_NOP: break;
+            case GERBV_OPCODE_PUSH: push(s, ip->data.fval); break;
+            case GERBV_OPCODE_PPUSH:
+                {
+                    const ssize_t idx = ip->data.ival - 1;
+                    if ((idx < 0) || (idx >= APERTURE_PARAMETERS_MAX))
+                        GERB_FATAL_ERROR(_("Tried to access oob aperture"));
+                    push(s, lp[idx]);
+                    break;
+                }
+            case GERBV_OPCODE_PPOP:
+                {
+                    if (pop(s, &tmp[0]) < 0)
+                        GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
+                    const ssize_t idx = ip->data.ival - 1;
+                    if ((idx < 0) || (idx >= APERTURE_PARAMETERS_MAX))
+                        GERB_FATAL_ERROR(_("Tried to access oob aperture"));
+                    lp[idx] = tmp[0];
+                    break;
+                }
+            case GERBV_OPCODE_ADD:
+                if (pop(s, &tmp[0]) < 0)
+                    GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
+                if (pop(s, &tmp[1]) < 0)
+                    GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
+                push(s, tmp[1] + tmp[0]);
+                break;
+            case GERBV_OPCODE_SUB:
+                if (pop(s, &tmp[0]) < 0)
+                    GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
+                if (pop(s, &tmp[1]) < 0)
+                    GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
+                push(s, tmp[1] - tmp[0]);
+                break;
+            case GERBV_OPCODE_MUL:
+                if (pop(s, &tmp[0]) < 0)
+                    GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
+                if (pop(s, &tmp[1]) < 0)
+                    GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
+                push(s, tmp[1] * tmp[0]);
+                break;
+            case GERBV_OPCODE_DIV:
+                if (pop(s, &tmp[0]) < 0)
+                    GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
+                if (pop(s, &tmp[1]) < 0)
+                    GERB_FATAL_ERROR(_("Tried to pop an empty stack"));
+                push(s, tmp[1] / tmp[0]);
+                break;
+            case GERBV_OPCODE_PRIM:
+                /*
+                 * This handles the exposure thing in the aperture macro
+                 * The exposure is always the first element on stack independent
+                 * of aperture macro.
+                 */
+                switch (ip->data.ival) {
+                    case 1:
+                        dprintf("  Aperture macro circle [1] (");
+                        type           = GERBV_APTYPE_MACRO_CIRCLE;
+                        nuf_parameters = 4;
+                        break;
+                    case 3: break;
+                    case 4:
+                        dprintf("  Aperture macro outline [4] (");
+                        type = GERBV_APTYPE_MACRO_OUTLINE;
+                        /*
+                         * Number of parameters are:
+                         * - number of points defined in entry 1 of the stack +
+                         *   start point. Times two since it is both X and Y.
+                         * - Then three more; exposure,  nuf points and rotation.
+                         *
+                         * @warning Calculation must be guarded against signed integer
+                         *     overflow
+                         *
+                         * @see CVE-2021-40394
+                         */
+                        const int sstack = (int)s->stack[1];
+                        if ((sstack < 0) || (sstack >= INT_MAX / 4)) {
+                            GERB_COMPILE_ERROR(
+                                _("Possible signed integer overflow "
+                                  "in calculating number of parameters "
+                                  "to aperture macro, will clamp to "
+                                  "(%d)"),
+                                APERTURE_PARAMETERS_MAX
+                            );
+                            nuf_parameters = APERTURE_PARAMETERS_MAX;
+                        } else {
+                            nuf_parameters = (sstack + 1) * 2 + 3;
+                        }
+                        break;
+                    case 5:
+                        dprintf("  Aperture macro polygon [5] (");
+                        type           = GERBV_APTYPE_MACRO_POLYGON;
+                        nuf_parameters = 6;
+                        break;
+                    case 6:
+                        dprintf("  Aperture macro moire [6] (");
+                        type           = GERBV_APTYPE_MACRO_MOIRE;
+                        nuf_parameters = 9;
+                        break;
+                    case 7:
+                        dprintf("  Aperture macro thermal [7] (");
+                        type           = GERBV_APTYPE_MACRO_THERMAL;
+                        nuf_parameters = 6;
+                        break;
+                    case 2:
+                    case 20:
+                        dprintf("  Aperture macro line 20/2 (");
+                        type           = GERBV_APTYPE_MACRO_LINE20;
+                        nuf_parameters = 7;
+                        break;
+                    case 21:
+                        dprintf("  Aperture macro line 21 (");
+                        type           = GERBV_APTYPE_MACRO_LINE21;
+                        nuf_parameters = 6;
+                        break;
+                    case 22:
+                        dprintf("  Aperture macro line 22 (");
+                        type           = GERBV_APTYPE_MACRO_LINE22;
+                        nuf_parameters = 6;
+                        break;
+                    default: handled = 0;
+                }
+
+                if (type != GERBV_APTYPE_NONE) {
+                    if (nuf_parameters > APERTURE_PARAMETERS_MAX) {
+                        GERB_COMPILE_ERROR(
+                            _("Number of parameters to aperture macro (%d) "
+                              "are more than gerbv is able to store (%d)"),
+                            nuf_parameters, APERTURE_PARAMETERS_MAX
+                        );
+                        nuf_parameters = APERTURE_PARAMETERS_MAX;
+                    }
+
+                    /*
+                     * Create struct for simplified aperture macro and
+                     * start filling in the blanks.
+                     */
+                    sam       = g_new(gerbv_simplified_amacro_t, 1);
+                    sam->type = type;
+                    sam->next = NULL;
+                    memset(sam->parameter, 0, sizeof(double) * APERTURE_PARAMETERS_MAX);
+
+                    /* CVE-2021-40400
+                     */
+                    if (nuf_parameters > s->capacity) {
+                        GERB_COMPILE_ERROR(
+                            _("Number of parameters to aperture macro (%d) "
+                              "capped to stack capacity (%zu)"),
+                            nuf_parameters, s->capacity
+                        );
+                        nuf_parameters = s->capacity;
+                    }
+                    memcpy(sam->parameter, s->stack, sizeof(double) * nuf_parameters);
+
+                    /* convert any mm values to inches */
+                    switch (type) {
+                        case GERBV_APTYPE_MACRO_CIRCLE:
+                            if (fabs(sam->parameter[0]) < 0.001)
+                                clearOperatorUsed = TRUE;
+                            sam->parameter[1] /= scale;
+                            sam->parameter[2] /= scale;
+                            sam->parameter[3] /= scale;
+                            break;
+                        case GERBV_APTYPE_MACRO_OUTLINE:
+                            if (fabs(sam->parameter[0]) < 0.001)
+                                clearOperatorUsed = TRUE;
+                            for (j = 2; j < nuf_parameters - 1; j++) {
+                                sam->parameter[j] /= scale;
+                            }
+                            break;
+                        case GERBV_APTYPE_MACRO_POLYGON:
+                            if (fabs(sam->parameter[0]) < 0.001)
+                                clearOperatorUsed = TRUE;
+                            sam->parameter[2] /= scale;
+                            sam->parameter[3] /= scale;
+                            sam->parameter[4] /= scale;
+                            break;
+                        case GERBV_APTYPE_MACRO_MOIRE:
+                            sam->parameter[0] /= scale;
+                            sam->parameter[1] /= scale;
+                            sam->parameter[2] /= scale;
+                            sam->parameter[3] /= scale;
+                            sam->parameter[4] /= scale;
+                            sam->parameter[6] /= scale;
+                            sam->parameter[7] /= scale;
+                            break;
+                        case GERBV_APTYPE_MACRO_THERMAL:
+                            sam->parameter[0] /= scale;
+                            sam->parameter[1] /= scale;
+                            sam->parameter[2] /= scale;
+                            sam->parameter[3] /= scale;
+                            sam->parameter[4] /= scale;
+                            break;
+                        case GERBV_APTYPE_MACRO_LINE20:
+                            if (fabs(sam->parameter[0]) < 0.001)
+                                clearOperatorUsed = TRUE;
+                            sam->parameter[1] /= scale;
+                            sam->parameter[2] /= scale;
+                            sam->parameter[3] /= scale;
+                            sam->parameter[4] /= scale;
+                            sam->parameter[5] /= scale;
+                            break;
+                        case GERBV_APTYPE_MACRO_LINE21:
+                        case GERBV_APTYPE_MACRO_LINE22:
+                            if (fabs(sam->parameter[0]) < 0.001)
+                                clearOperatorUsed = TRUE;
+                            sam->parameter[1] /= scale;
+                            sam->parameter[2] /= scale;
+                            sam->parameter[3] /= scale;
+                            sam->parameter[4] /= scale;
+                            break;
+                        default: break;
+                    }
+                    /*
+                     * Add this simplified aperture macro to the end of the list
+                     * of simplified aperture macros. If first entry, put it
+                     * in the top.
+                     */
+                    if (aperture->simplified == NULL) {
+                        aperture->simplified = sam;
+                    } else {
+                        gerbv_simplified_amacro_t* tmp_sam;
+                        tmp_sam = aperture->simplified;
+                        while (tmp_sam->next != NULL) {
+                            tmp_sam = tmp_sam->next;
+                        }
+                        tmp_sam->next = sam;
+                    }
 
 #ifdef DEBUG
-		for (i = 0; i < nuf_parameters; i++) {
-		    dprintf("%f, ", s->stack[i]);
-		}
+                    for (i = 0; i < nuf_parameters; i++) {
+                        dprintf("%f, ", s->stack[i]);
+                    }
 #endif /* DEBUG */
-		dprintf(")\n");
-	    }
-
-	    /* 
-	     * Here we reset the stack pointer. It's not general correct
-	     * correct to do this, but since I know how the compiler works
-	     * I can do this. The correct way to do this should be to 
-	     * subtract number of used elements in each primitive operation.
-	     */
-	    s->sp = 0;
-	    break;
-	default :
-	    break;
-	}
+                    dprintf(")\n");
+                }
+
+                /*
+                 * Here we reset the stack pointer. It's not general correct
+                 * correct to do this, but since I know how the compiler works
+                 * I can do this. The correct way to do this should be to
+                 * subtract number of used elements in each primitive operation.
+                 */
+                s->sp = 0;
+                break;
+            default: break;
+        }
     }
     free_stack(s);
-    g_free (lp);
+    g_free(lp);
 
     /* store a flag to let the renderer know if it should expect any "clear"
        primatives */
-    aperture->parameter[0]= (gdouble) clearOperatorUsed;
+    aperture->parameter[0] = (gdouble)clearOperatorUsed;
     return handled;
 } /* simplify_aperture_macro */
 
-
 /* ------------------------------------------------------------------ */
-static int 
-parse_aperture_definition(gerb_file_t *fd, gerbv_aperture_t *aperture,
-			  gerbv_image_t *image, gdouble scale,
-			  long int *line_num_p)
-{
-    int ano, i;
-    char *ad;
-    char *token;
-    gerbv_amacro_t *curr_amacro;
-    gerbv_amacro_t *amacro = image->amacro;
-    gerbv_error_list_t *error_list = image->gerbv_stats->error_list;
-    gdouble tempHolder;
-    
+static int
+parse_aperture_definition(
+    gerb_file_t* fd, gerbv_aperture_t* aperture, gerbv_image_t* image, gdouble scale, long int* line_num_p
+) {
+    int                 ano, i;
+    char*               ad;
+    char*               token;
+    gerbv_amacro_t*     curr_amacro;
+    gerbv_amacro_t*     amacro     = image->amacro;
+    gerbv_error_list_t* error_list = image->gerbv_stats->error_list;
+    gdouble             tempHolder;
+
     if (gerb_fgetc(fd) != 'D') {
-	gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Found AD code with no following 'D' "
-		    "at line %ld in file \"%s\""),
-		*line_num_p, fd->filename);
-	return -1;
+        gerbv_stats_printf(
+            error_list, GERBV_MESSAGE_ERROR, -1,
+            _("Found AD code with no following 'D' "
+              "at line %ld in file \"%s\""),
+            *line_num_p, fd->filename
+        );
+        return -1;
     }
-    
+
     /*
      * Get aperture no
      */
     ano = gerb_fgetint(fd, NULL);
-    
+
     /*
      * Read in the whole aperture defintion and tokenize it
      */
     ad = gerb_fgetstring(fd, '*');
 
     if (ad == NULL) {
-	gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Invalid aperture definition at line %ld in file \"%s\", "
-		    "cannot find '*'"),
-		*line_num_p, fd->filename);
-	return -1;
+        gerbv_stats_printf(
+            error_list, GERBV_MESSAGE_ERROR, -1,
+            _("Invalid aperture definition at line %ld in file \"%s\", "
+              "cannot find '*'"),
+            *line_num_p, fd->filename
+        );
+        return -1;
     }
 
     token = strtok(ad, ",");
-    
+
     if (token == NULL) {
-	gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		_("Invalid aperture definition at line %ld in file \"%s\""),
-		*line_num_p, fd->filename);
-	return -1;
+        gerbv_stats_printf(
+            error_list, GERBV_MESSAGE_ERROR, -1, _("Invalid aperture definition at line %ld in file \"%s\""),
+            *line_num_p, fd->filename
+        );
+        return -1;
     }
     if (strlen(token) == 1) {
-	switch (token[0]) {
-	case 'C':
-	    aperture->type = GERBV_APTYPE_CIRCLE;
-	    break;
-	case 'R' :
-	    aperture->type = GERBV_APTYPE_RECTANGLE;
-	    break;
-	case 'O' :
-	    aperture->type = GERBV_APTYPE_OVAL;
-	    break;
-	case 'P' :
-	    aperture->type = GERBV_APTYPE_POLYGON;
-	    break;
-	}
-	/* Here a should a T be defined, but I don't know what it represents */
+        switch (token[0]) {
+            case 'C': aperture->type = GERBV_APTYPE_CIRCLE; break;
+            case 'R': aperture->type = GERBV_APTYPE_RECTANGLE; break;
+            case 'O': aperture->type = GERBV_APTYPE_OVAL; break;
+            case 'P': aperture->type = GERBV_APTYPE_POLYGON; break;
+        }
+        /* Here a should a T be defined, but I don't know what it represents */
     } else {
-	aperture->type = GERBV_APTYPE_MACRO;
-	/*
-	 * In aperture definition, point to the aperture macro 
-	 * used in the defintion
-	 */
-	curr_amacro = amacro;
-	while (curr_amacro) {
-	    if ((strlen(curr_amacro->name) == strlen(token)) &&
-		(strcmp(curr_amacro->name, token) == 0)) {
-		aperture->amacro = curr_amacro;
-		break;
-	    }
-	    curr_amacro = curr_amacro->next;
-	}
+        aperture->type = GERBV_APTYPE_MACRO;
+        /*
+         * In aperture definition, point to the aperture macro
+         * used in the defintion
+         */
+        curr_amacro = amacro;
+        while (curr_amacro) {
+            if ((strlen(curr_amacro->name) == strlen(token)) && (strcmp(curr_amacro->name, token) == 0)) {
+                aperture->amacro = curr_amacro;
+                break;
+            }
+            curr_amacro = curr_amacro->next;
+        }
     }
-    
+
     /*
      * Parse all parameters
      */
-    for (token = strtok(NULL, "X"), i = 0; token != NULL; 
-	 token = strtok(NULL, "X"), i++) {
-	if (i == APERTURE_PARAMETERS_MAX) {
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_ERROR, -1,
-		    _("Maximum number of allowed parameters exceeded "
-			"in aperture %d at line %ld in file \"%s\""),
-		    ano, *line_num_p, fd->filename);
-	    break;
-	}
-	errno = 0;
-
-	tempHolder = strtod(token, NULL);
-	/* convert any MM values to inches */
-	/* don't scale polygon angles or side numbers, or macro parmaeters */
-	if (!(((aperture->type == GERBV_APTYPE_POLYGON) && ((i==1) || (i==2)))||
-		(aperture->type == GERBV_APTYPE_MACRO))) {
-	    tempHolder /= scale;
-	}
-	
-	aperture->parameter[i] = tempHolder;
-	if (errno) {
-	    gerbv_stats_printf(error_list, GERBV_MESSAGE_WARNING, -1,
-		    _("Failed to read all parameters exceeded in "
-			"aperture %d at line %ld in file \"%s\""),
-		    ano, *line_num_p, fd->filename);
+    for (token = strtok(NULL, "X"), i = 0; token != NULL; token = strtok(NULL, "X"), i++) {
+        if (i == APERTURE_PARAMETERS_MAX) {
+            gerbv_stats_printf(
+                error_list, GERBV_MESSAGE_ERROR, -1,
+                _("Maximum number of allowed parameters exceeded "
+                  "in aperture %d at line %ld in file \"%s\""),
+                ano, *line_num_p, fd->filename
+            );
+            break;
+        }
+        errno = 0;
+
+        tempHolder = strtod(token, NULL);
+        /* convert any MM values to inches */
+        /* don't scale polygon angles or side numbers, or macro parmaeters */
+        if (!(((aperture->type == GERBV_APTYPE_POLYGON) && ((i == 1) || (i == 2)))
+              || (aperture->type == GERBV_APTYPE_MACRO))) {
+            tempHolder /= scale;
+        }
+
+        aperture->parameter[i] = tempHolder;
+        if (errno) {
+            gerbv_stats_printf(
+                error_list, GERBV_MESSAGE_WARNING, -1,
+                _("Failed to read all parameters exceeded in "
+                  "aperture %d at line %ld in file \"%s\""),
+                ano, *line_num_p, fd->filename
+            );
             aperture->parameter[i] = 0.0;
         }
     }
-    
+
     aperture->nuf_parameters = i;
-    
+
     gerb_ungetc(fd);
 
     if (aperture->type == GERBV_APTYPE_MACRO) {
-	dprintf("Simplifying aperture %d using aperture macro \"%s\"\n", ano,
-		aperture->amacro->name);
-	simplify_aperture_macro(aperture, scale);
-	dprintf("Done simplifying\n");
+        dprintf("Simplifying aperture %d using aperture macro \"%s\"\n", ano, aperture->amacro->name);
+        simplify_aperture_macro(aperture, scale);
+        dprintf("Done simplifying\n");
     }
-    
+
     g_free(ad);
-    
+
     return ano;
 } /* parse_aperture_definition */
 
-
 /* ------------------------------------------------------------------ */
-static void 
-calc_cirseg_sq(struct gerbv_net *net, int cw, 
-	       double delta_cp_x, double delta_cp_y)
-{
+static void
+calc_cirseg_sq(struct gerbv_net* net, int cw, double delta_cp_x, double delta_cp_y) {
     double d1x, d1y, d2x, d2y;
     double alfa, beta;
-    int quadrant = 0;
+    int    quadrant = 0;
 
-    
     /*
      * Quadrant detection (based on ccw, converted below if cw)
      *  Y ^
@@ -2349,66 +2277,56 @@ calc_cirseg_sq(struct gerbv_net *net, int cw,
      *    ---->X
      */
     if (net->start_x > net->stop_x)
-	/* 1st and 2nd quadrant */
-	if (net->start_y < net->stop_y)
-	    quadrant = 1;
-	else
-	    quadrant = 2;
+        /* 1st and 2nd quadrant */
+        if (net->start_y < net->stop_y)
+            quadrant = 1;
+        else
+            quadrant = 2;
     else
-	/* 3rd and 4th quadrant */
-	if (net->start_y > net->stop_y)
-	    quadrant = 3;
-	else
-	    quadrant = 4;
+        /* 3rd and 4th quadrant */
+        if (net->start_y > net->stop_y)
+            quadrant = 3;
+        else
+            quadrant = 4;
 
-    /* 
+    /*
      * If clockwise, rotate quadrant
      */
     if (cw) {
-	switch (quadrant) {
-	case 1 : 
-	    quadrant = 3;
-	    break;
-	case 2 : 
-	    quadrant = 4;
-	    break;
-	case 3 : 
-	    quadrant = 1;
-	    break;
-	case 4 : 
-	    quadrant = 2;
-	    break;
-	default : 
-	    GERB_COMPILE_ERROR(_("Unknow quadrant value while converting to cw"));
-	}
+        switch (quadrant) {
+            case 1: quadrant = 3; break;
+            case 2: quadrant = 4; break;
+            case 3: quadrant = 1; break;
+            case 4: quadrant = 2; break;
+            default: GERB_COMPILE_ERROR(_("Unknow quadrant value while converting to cw"));
+        }
     }
 
     /*
      * Calculate arc center point
      */
     switch (quadrant) {
-    case 1 :
-	net->cirseg->cp_x = net->start_x - delta_cp_x;
-	net->cirseg->cp_y = net->start_y - delta_cp_y;
-	break;
-    case 2 :
-	net->cirseg->cp_x = net->start_x + delta_cp_x;
-	net->cirseg->cp_y = net->start_y - delta_cp_y;
-	break;
-    case 3 : 
-	net->cirseg->cp_x = net->start_x + delta_cp_x;
-	net->cirseg->cp_y = net->start_y + delta_cp_y;
-	break;
-    case 4 :
-	net->cirseg->cp_x = net->start_x - delta_cp_x;
-	net->cirseg->cp_y = net->start_y + delta_cp_y;
-	break;
-    default :
-	GERB_COMPILE_ERROR(_("Strange quadrant: %d"), quadrant);
+        case 1:
+            net->cirseg->cp_x = net->start_x - delta_cp_x;
+            net->cirseg->cp_y = net->start_y - delta_cp_y;
+            break;
+        case 2:
+            net->cirseg->cp_x = net->start_x + delta_cp_x;
+            net->cirseg->cp_y = net->start_y - delta_cp_y;
+            break;
+        case 3:
+            net->cirseg->cp_x = net->start_x + delta_cp_x;
+            net->cirseg->cp_y = net->start_y + delta_cp_y;
+            break;
+        case 4:
+            net->cirseg->cp_x = net->start_x - delta_cp_x;
+            net->cirseg->cp_y = net->start_y + delta_cp_y;
+            break;
+        default: GERB_COMPILE_ERROR(_("Strange quadrant: %d"), quadrant);
     }
 
     /*
-     * Some good values 
+     * Some good values
      */
     d1x = fabs(net->start_x - net->cirseg->cp_x);
     d1y = fabs(net->start_y - net->cirseg->cp_y);
@@ -2421,55 +2339,51 @@ calc_cirseg_sq(struct gerbv_net *net, int cw,
     /*
      * Avoid divide by zero when sin(0) = 0 and cos(90) = 0
      */
-    net->cirseg->width = alfa < beta ? 
-	2 * (d1x / cos(alfa)) : 2 * (d2x / cos(beta));
-    net->cirseg->height = alfa > beta ? 
-	2 * (d1y / sin(alfa)) : 2 * (d2y / sin(beta));
-
-    if (alfa < GERBV_PRECISION_ANGLE_RAD
-    &&  beta < GERBV_PRECISION_ANGLE_RAD) {
-	net->cirseg->height = 0;
+    net->cirseg->width  = alfa < beta ? 2 * (d1x / cos(alfa)) : 2 * (d2x / cos(beta));
+    net->cirseg->height = alfa > beta ? 2 * (d1y / sin(alfa)) : 2 * (d2y / sin(beta));
+
+    if (alfa < GERBV_PRECISION_ANGLE_RAD && beta < GERBV_PRECISION_ANGLE_RAD) {
+        net->cirseg->height = 0;
     }
 
     switch (quadrant) {
-    case 1 :
-	net->cirseg->angle1 = RAD2DEG(alfa);
-	net->cirseg->angle2 = RAD2DEG(beta);
-	break;
-    case 2 :
-	net->cirseg->angle1 = 180.0 - RAD2DEG(alfa);
-	net->cirseg->angle2 = 180.0 - RAD2DEG(beta);
-	break;
-    case 3 : 
-	net->cirseg->angle1 = 180.0 + RAD2DEG(alfa);
-	net->cirseg->angle2 = 180.0 + RAD2DEG(beta);
-	break;
-    case 4 :
-	net->cirseg->angle1 = 360.0 - RAD2DEG(alfa);
-	net->cirseg->angle2 = 360.0 - RAD2DEG(beta);
-	break;
-    default :
-	GERB_COMPILE_ERROR(_("Strange quadrant: %d"), quadrant);
+        case 1:
+            net->cirseg->angle1 = RAD2DEG(alfa);
+            net->cirseg->angle2 = RAD2DEG(beta);
+            break;
+        case 2:
+            net->cirseg->angle1 = 180.0 - RAD2DEG(alfa);
+            net->cirseg->angle2 = 180.0 - RAD2DEG(beta);
+            break;
+        case 3:
+            net->cirseg->angle1 = 180.0 + RAD2DEG(alfa);
+            net->cirseg->angle2 = 180.0 + RAD2DEG(beta);
+            break;
+        case 4:
+            net->cirseg->angle1 = 360.0 - RAD2DEG(alfa);
+            net->cirseg->angle2 = 360.0 - RAD2DEG(beta);
+            break;
+        default: GERB_COMPILE_ERROR(_("Strange quadrant: %d"), quadrant);
     }
 
     if (net->cirseg->width < 0.0)
-	GERB_COMPILE_WARNING(_("Negative width [%f] in quadrant %d [%f][%f]"),
-			     net->cirseg->width, quadrant, RAD2DEG(alfa), RAD2DEG(beta));
-    
+        GERB_COMPILE_WARNING(
+            _("Negative width [%f] in quadrant %d [%f][%f]"), net->cirseg->width, quadrant, RAD2DEG(alfa), RAD2DEG(beta)
+        );
+
     if (net->cirseg->height < 0.0)
-	GERB_COMPILE_WARNING(_("Negative height [%f] in quadrant %d [%f][%f]"),
-			     net->cirseg->height, quadrant, RAD2DEG(alfa), RAD2DEG(beta));
+        GERB_COMPILE_WARNING(
+            _("Negative height [%f] in quadrant %d [%f][%f]"), net->cirseg->height, quadrant, RAD2DEG(alfa),
+            RAD2DEG(beta)
+        );
 
     return;
 
 } /* calc_cirseg_sq */
 
-
 /* Multiquadrant circular interpolation */
-static void 
-calc_cirseg_mq(struct gerbv_net *net, int cw, 
-	       double delta_cp_x, double delta_cp_y)
-{
+static void
+calc_cirseg_mq(struct gerbv_net* net, int cw, double delta_cp_x, double delta_cp_y) {
     double d1x, d1y, d2x, d2y;
     double alfa, beta;
 
@@ -2477,7 +2391,7 @@ calc_cirseg_mq(struct gerbv_net *net, int cw,
     net->cirseg->cp_y = net->start_y + delta_cp_y;
 
     /*
-     * Some good values 
+     * Some good values
      */
     d1x = -delta_cp_x;
     d1y = -delta_cp_y;
@@ -2489,10 +2403,14 @@ calc_cirseg_mq(struct gerbv_net *net, int cw,
      * but containing opposite signs. These values cause essentially a
      * "signed zero" effect, which makes atan2 results unpredictable.
      */
-    if (fabs(d1x) < DBL_EPSILON) d1x = 0;
-    if (fabs(d1y) < DBL_EPSILON) d1y = 0;
-    if (fabs(d2x) < DBL_EPSILON) d2x = 0;
-    if (fabs(d2y) < DBL_EPSILON) d2y = 0;
+    if (fabs(d1x) < DBL_EPSILON)
+        d1x = 0;
+    if (fabs(d1y) < DBL_EPSILON)
+        d1y = 0;
+    if (fabs(d2x) < DBL_EPSILON)
+        d2x = 0;
+    if (fabs(d2y) < DBL_EPSILON)
+        d2y = 0;
 
     net->cirseg->width = hypot(delta_cp_x, delta_cp_y);
     net->cirseg->width *= 2.0;
@@ -2508,12 +2426,12 @@ calc_cirseg_mq(struct gerbv_net *net, int cw,
      * Make sure it's always positive angles
      */
     if (alfa < 0.0) {
-	alfa += M_PI + M_PI;
-	beta += M_PI + M_PI;
+        alfa += M_PI + M_PI;
+        beta += M_PI + M_PI;
     }
 
     if (beta < 0.0)
-	beta += M_PI + M_PI;
+        beta += M_PI + M_PI;
 
     /*
      * This is a sanity check for angles after the nature of atan2.
@@ -2523,11 +2441,11 @@ calc_cirseg_mq(struct gerbv_net *net, int cw,
      * uses them. But what the heck, it works for me.
      */
     if (cw) {
-	if (alfa - beta < DBL_EPSILON)
-	    beta -= M_PI + M_PI;
+        if (alfa - beta < DBL_EPSILON)
+            beta -= M_PI + M_PI;
     } else {
-	if (beta - alfa < DBL_EPSILON)
-	    beta += M_PI + M_PI;
+        if (beta - alfa < DBL_EPSILON)
+            beta += M_PI + M_PI;
     }
 
     net->cirseg->angle1 = RAD2DEG(alfa);
@@ -2536,194 +2454,169 @@ calc_cirseg_mq(struct gerbv_net *net, int cw,
 
 /* Calculate circular interpolation bounding box */
 static void
-calc_cirseg_bbox(const gerbv_cirseg_t *cirseg,
-		double apert_size_x, double apert_size_y,
-		gerbv_render_size_t *bbox)
-{
-	gdouble x, y, ang1, ang2, step_pi_2;
-
-	/* For bounding box calculation only half of aperture size is used */
-	apert_size_x /= 2;
-	apert_size_y /= 2;
-
-	ang1 = DEG2RAD(MIN(cirseg->angle1, cirseg->angle2));
-	ang2 = DEG2RAD(MAX(cirseg->angle1, cirseg->angle2));
-
-	/* Start arc point */
-	x = cirseg->cp_x + cirseg->width*cos(ang1)/2;
-	y = cirseg->cp_y + cirseg->width*sin(ang1)/2;
-	gerber_update_min_and_max(bbox, x, y,
-				apert_size_x, apert_size_x,
-				apert_size_y, apert_size_y);
-
-	/* Middle arc points */
-	for (step_pi_2 = (ang1/M_PI_2 + 1)*M_PI_2;
-				step_pi_2 < MIN(ang2, ang1 + 2*M_PI);
-				step_pi_2 += M_PI_2) {
-		x = cirseg->cp_x + cirseg->width*cos(step_pi_2)/2;
-		y = cirseg->cp_y + cirseg->width*sin(step_pi_2)/2;
-		gerber_update_min_and_max(bbox, x, y,
-					apert_size_x, apert_size_x,
-					apert_size_y, apert_size_y);
-	}
-
-	/* Stop arc point */
-	x = cirseg->cp_x + cirseg->width*cos(ang2)/2;
-	y = cirseg->cp_y + cirseg->width*sin(ang2)/2;
-	gerber_update_min_and_max(bbox, x, y,
-				apert_size_x, apert_size_x,
-				apert_size_y, apert_size_y);
+calc_cirseg_bbox(const gerbv_cirseg_t* cirseg, double apert_size_x, double apert_size_y, gerbv_render_size_t* bbox) {
+    gdouble x, y, ang1, ang2, step_pi_2;
+
+    /* For bounding box calculation only half of aperture size is used */
+    apert_size_x /= 2;
+    apert_size_y /= 2;
+
+    ang1 = DEG2RAD(MIN(cirseg->angle1, cirseg->angle2));
+    ang2 = DEG2RAD(MAX(cirseg->angle1, cirseg->angle2));
+
+    /* Start arc point */
+    x = cirseg->cp_x + cirseg->width * cos(ang1) / 2;
+    y = cirseg->cp_y + cirseg->width * sin(ang1) / 2;
+    gerber_update_min_and_max(bbox, x, y, apert_size_x, apert_size_x, apert_size_y, apert_size_y);
+
+    /* Middle arc points */
+    for (step_pi_2 = (ang1 / M_PI_2 + 1) * M_PI_2; step_pi_2 < MIN(ang2, ang1 + 2 * M_PI); step_pi_2 += M_PI_2) {
+        x = cirseg->cp_x + cirseg->width * cos(step_pi_2) / 2;
+        y = cirseg->cp_y + cirseg->width * sin(step_pi_2) / 2;
+        gerber_update_min_and_max(bbox, x, y, apert_size_x, apert_size_x, apert_size_y, apert_size_y);
+    }
+
+    /* Stop arc point */
+    x = cirseg->cp_x + cirseg->width * cos(ang2) / 2;
+    y = cirseg->cp_y + cirseg->width * sin(ang2) / 2;
+    gerber_update_min_and_max(bbox, x, y, apert_size_x, apert_size_x, apert_size_y, apert_size_y);
 }
 
 static void
-gerber_update_any_running_knockout_measurements (gerbv_image_t *image)
-{
+gerber_update_any_running_knockout_measurements(gerbv_image_t* image) {
     if (knockoutMeasure) {
-	knockoutLayer->knockout.lowerLeftX = knockoutLimitXmin;
-	knockoutLayer->knockout.lowerLeftY = knockoutLimitYmin;
-	knockoutLayer->knockout.width = knockoutLimitXmax - knockoutLimitXmin;
-	knockoutLayer->knockout.height = knockoutLimitYmax - knockoutLimitYmin;
-	knockoutMeasure = FALSE;
+        knockoutLayer->knockout.lowerLeftX = knockoutLimitXmin;
+        knockoutLayer->knockout.lowerLeftY = knockoutLimitYmin;
+        knockoutLayer->knockout.width      = knockoutLimitXmax - knockoutLimitXmin;
+        knockoutLayer->knockout.height     = knockoutLimitYmax - knockoutLimitYmin;
+        knockoutMeasure                    = FALSE;
     }
 }
 
-
 static void
-gerber_calculate_final_justify_effects(gerbv_image_t *image)
-{
+gerber_calculate_final_justify_effects(gerbv_image_t* image) {
     gdouble translateA = 0.0, translateB = 0.0;
-    
+
     if (image->info->imageJustifyTypeA != GERBV_JUSTIFY_NOJUSTIFY) {
-	if (image->info->imageJustifyTypeA == GERBV_JUSTIFY_CENTERJUSTIFY)
-	    translateA = (image->info->max_x - image->info->min_x) / 2.0;
-	else
-	    translateA = -image->info->min_x;
+        if (image->info->imageJustifyTypeA == GERBV_JUSTIFY_CENTERJUSTIFY)
+            translateA = (image->info->max_x - image->info->min_x) / 2.0;
+        else
+            translateA = -image->info->min_x;
     }
     if (image->info->imageJustifyTypeB != GERBV_JUSTIFY_NOJUSTIFY) {
-	if (image->info->imageJustifyTypeB == GERBV_JUSTIFY_CENTERJUSTIFY)
-	    translateB = (image->info->max_y - image->info->min_y) / 2.0;
-	else
-	    translateB = -image->info->min_y;
+        if (image->info->imageJustifyTypeB == GERBV_JUSTIFY_CENTERJUSTIFY)
+            translateB = (image->info->max_y - image->info->min_y) / 2.0;
+        else
+            translateB = -image->info->min_y;
     }
 
     /* update the min/max values so the autoscale function can correctly
        centered a justified image */
-    image->info->min_x += translateA+ image->info->imageJustifyOffsetA;
-    image->info->max_x += translateA+ image->info->imageJustifyOffsetA;
-    image->info->min_y += translateB+ image->info->imageJustifyOffsetB;
-    image->info->max_y += translateB+ image->info->imageJustifyOffsetB;
- 
+    image->info->min_x += translateA + image->info->imageJustifyOffsetA;
+    image->info->max_x += translateA + image->info->imageJustifyOffsetA;
+    image->info->min_y += translateB + image->info->imageJustifyOffsetB;
+    image->info->max_y += translateB + image->info->imageJustifyOffsetB;
+
     /* store the absolute offset for the justify so we can quickly offset
        the rendered picture during drawing */
-    image->info->imageJustifyOffsetActualA = translateA + 
-	image->info->imageJustifyOffsetA;
-    image->info->imageJustifyOffsetActualB = translateB + 
-	image->info->imageJustifyOffsetB;
+    image->info->imageJustifyOffsetActualA = translateA + image->info->imageJustifyOffsetA;
+    image->info->imageJustifyOffsetActualB = translateB + image->info->imageJustifyOffsetB;
 } /* gerber_calculate_final_justify_effects */
 
-
 void
-gerber_update_image_min_max (gerbv_render_size_t *boundingBox,
-		double repeat_off_X, double repeat_off_Y,
-		gerbv_image_t* image)
-{
-	image->info->min_x = MIN(image->info->min_x, boundingBox->left);
-	image->info->min_y = MIN(image->info->min_y, boundingBox->bottom);
-	image->info->max_x = MAX(image->info->max_x,
-			boundingBox->right + repeat_off_X);
-	image->info->max_y = MAX(image->info->max_y,
-			boundingBox->top + repeat_off_Y);
+gerber_update_image_min_max(
+    gerbv_render_size_t* boundingBox, double repeat_off_X, double repeat_off_Y, gerbv_image_t* image
+) {
+    image->info->min_x = MIN(image->info->min_x, boundingBox->left);
+    image->info->min_y = MIN(image->info->min_y, boundingBox->bottom);
+    image->info->max_x = MAX(image->info->max_x, boundingBox->right + repeat_off_X);
+    image->info->max_y = MAX(image->info->max_y, boundingBox->top + repeat_off_Y);
 }
 
 void
-gerber_update_min_and_max(gerbv_render_size_t *boundingBox,
-			  gdouble x, gdouble y, gdouble apertureSizeX1,
-			  gdouble apertureSizeX2,gdouble apertureSizeY1,
-			  gdouble apertureSizeY2)
-{
+gerber_update_min_and_max(
+    gerbv_render_size_t* boundingBox, gdouble x, gdouble y, gdouble apertureSizeX1, gdouble apertureSizeX2,
+    gdouble apertureSizeY1, gdouble apertureSizeY2
+) {
     gdouble ourX1 = x - apertureSizeX1, ourY1 = y - apertureSizeY1;
     gdouble ourX2 = x + apertureSizeX2, ourY2 = y + apertureSizeY2;
-    
+
     /* transform the point to the final rendered position, accounting
        for any scaling, offsets, mirroring, etc */
     /* NOTE: we need to already add/subtract in the aperture size since
        the final rendering may be scaled */
-    cairo_matrix_transform_point (&currentMatrix, &ourX1, &ourY1);
-    cairo_matrix_transform_point (&currentMatrix, &ourX2, &ourY2);
+    cairo_matrix_transform_point(&currentMatrix, &ourX1, &ourY1);
+    cairo_matrix_transform_point(&currentMatrix, &ourX2, &ourY2);
 
     /* check both points against the min/max, since depending on the rotation,
        mirroring, etc, either point could possibly be a min or max */
 
-    boundingBox->left =   MIN(boundingBox->left,   ourX1);
-    boundingBox->left =   MIN(boundingBox->left,   ourX2);
-    boundingBox->right =  MAX(boundingBox->right,  ourX1);
-    boundingBox->right =  MAX(boundingBox->right,  ourX2);
+    boundingBox->left   = MIN(boundingBox->left, ourX1);
+    boundingBox->left   = MIN(boundingBox->left, ourX2);
+    boundingBox->right  = MAX(boundingBox->right, ourX1);
+    boundingBox->right  = MAX(boundingBox->right, ourX2);
     boundingBox->bottom = MIN(boundingBox->bottom, ourY1);
     boundingBox->bottom = MIN(boundingBox->bottom, ourY2);
-    boundingBox->top =    MAX(boundingBox->top,    ourY1);
-    boundingBox->top =    MAX(boundingBox->top,    ourY2);
+    boundingBox->top    = MAX(boundingBox->top, ourY1);
+    boundingBox->top    = MAX(boundingBox->top, ourY2);
 } /* gerber_update_min_and_max */
 
 static gboolean
-add_trailing_zeros_if_omitted(int *coord, int omitted_num,
-		gerbv_format_t *format)
-{
-	if (format
-	&&  format->omit_zeros == GERBV_OMIT_ZEROS_TRAILING
-	&&  omitted_num > 0) {
-		for (int i = 0; i < omitted_num; i++)
-			*coord *= 10;
-
-		return TRUE;
-	}
-
-	return FALSE;
+add_trailing_zeros_if_omitted(int* coord, int omitted_num, gerbv_format_t* format) {
+    if (format && format->omit_zeros == GERBV_OMIT_ZEROS_TRAILING && omitted_num > 0) {
+        for (int i = 0; i < omitted_num; i++)
+            *coord *= 10;
+
+        return TRUE;
+    }
+
+    return FALSE;
 } /* add_trailing_zeros_if_omitted() */
 
 /** Return Gerber D-code name by code number. */
-const char *gerber_d_code_name(int d_code)
-{
-	switch (d_code) {
-	case 1:  return N_("exposure on");
-	case 2:  return N_("exposure off");
-	case 3:  return N_("flash aperture");
-	default: return N_("unknown D-code");
-	}
+const char*
+gerber_d_code_name(int d_code) {
+    switch (d_code) {
+        case 1: return N_("exposure on");
+        case 2: return N_("exposure off");
+        case 3: return N_("flash aperture");
+        default: return N_("unknown D-code");
+    }
 } /* gerber_d_code_name() */
 
 /** Return Gerber G-code name by code number. */
-const char *gerber_g_code_name(int g_code)
-{
-	switch (g_code) {
-	case  0: return  N_("move");
-	case  1: return  N_("1X linear interpolation");
-	case  2: return  N_("CW interpolation");
-	case  3: return  N_("CCW interpolation");
-	case  4: return  N_("comment/ignore block");
-	case 10: return  N_("10X linear interpolation");
-	case 11: return  N_("0.1X linear interpolation");
-	case 12: return  N_("0.01X linear interpolation");
-	case 36: return  N_("poly fill on");
-	case 37: return  N_("poly fill off");
-	case 54: return  N_("tool prepare");
-	case 55: return  N_("flash prepare");
-	case 70: return  N_("units = inches");
-	case 71: return  N_("units = mm");
-	case 74: return  N_("disable 360 circ. interpolation");
-	case 75: return  N_("enable 360 circ. interpolation");
-	case 90: return  N_("absolute units");
-	case 91: return  N_("incremental units");
-	default: return  N_("unknown G-code");
-	}
+const char*
+gerber_g_code_name(int g_code) {
+    switch (g_code) {
+        case 0: return N_("move");
+        case 1: return N_("1X linear interpolation");
+        case 2: return N_("CW interpolation");
+        case 3: return N_("CCW interpolation");
+        case 4: return N_("comment/ignore block");
+        case 10: return N_("10X linear interpolation");
+        case 11: return N_("0.1X linear interpolation");
+        case 12: return N_("0.01X linear interpolation");
+        case 36: return N_("poly fill on");
+        case 37: return N_("poly fill off");
+        case 54: return N_("tool prepare");
+        case 55: return N_("flash prepare");
+        case 70: return N_("units = inches");
+        case 71: return N_("units = mm");
+        case 74: return N_("disable 360 circ. interpolation");
+        case 75: return N_("enable 360 circ. interpolation");
+        case 90: return N_("absolute units");
+        case 91: return N_("incremental units");
+        default: return N_("unknown G-code");
+    }
 } /* gerber_g_code_name() */
 
 /** Return Gerber M-code name by code number. */
-const char *gerber_m_code_name(int m_code)
-{
-	switch (m_code) {
-	case 0:  return N_("program stop (obsolete)");
-	case 1:  return N_("optional stop (obsolete)");
-	case 2:  return N_("end of file");
-	default: return N_("unknown M-code");
-	}
+const char*
+gerber_m_code_name(int m_code) {
+    switch (m_code) {
+        case 0: return N_("program stop (obsolete)");
+        case 1: return N_("optional stop (obsolete)");
+        case 2: return N_("end of file");
+        default: return N_("unknown M-code");
+    }
 } /* gerber_m_code_name() */
diff --git a/src/gerber.h b/src/gerber.h
index b8bf99b..cc0218d 100644
--- a/src/gerber.h
+++ b/src/gerber.h
@@ -39,46 +39,46 @@ extern "C" {
 #include "gerb_file.h"
 
 typedef struct gerb_state {
-    int curr_x;
-    int curr_y;
-    int prev_x;
-    int prev_y;
-    int delta_cp_x;
-    int delta_cp_y;
-    int curr_aperture;
-    int changed;
+    int                    curr_x;
+    int                    curr_y;
+    int                    prev_x;
+    int                    prev_y;
+    int                    delta_cp_x;
+    int                    delta_cp_y;
+    int                    curr_aperture;
+    int                    changed;
     gerbv_aperture_state_t aperture_state;
-    gerbv_interpolation_t interpolation;
-    gerbv_interpolation_t prev_interpolation;
-    gerbv_net_t *parea_start_node;
-    gerbv_layer_t *layer;
-    gerbv_netstate_t *state;
-    int in_parea_fill;
-    int mq_on;		/* Is multiquadrant circular iterpolation */
+    gerbv_interpolation_t  interpolation;
+    gerbv_interpolation_t  prev_interpolation;
+    gerbv_net_t*           parea_start_node;
+    gerbv_layer_t*         layer;
+    gerbv_netstate_t*      state;
+    int                    in_parea_fill;
+    int                    mq_on; /* Is multiquadrant circular iterpolation */
 } gerb_state_t;
 
 /*
  * parse gerber file pointed to by fd
  */
-gerbv_image_t *parse_gerb(gerb_file_t *fd, gchar *directoryPath);
-gboolean gerber_is_rs274x_p(gerb_file_t *fd, gboolean *returnFoundBinary);
-gboolean gerber_is_rs274d_p(gerb_file_t *fd);
-gerbv_net_t *
-gerber_create_new_net (gerbv_net_t *currentNet, gerbv_layer_t *layer, gerbv_netstate_t *state);
+gerbv_image_t* parse_gerb(gerb_file_t* fd, gchar* directoryPath);
+gboolean       gerber_is_rs274x_p(gerb_file_t* fd, gboolean* returnFoundBinary);
+gboolean       gerber_is_rs274d_p(gerb_file_t* fd);
+gerbv_net_t*   gerber_create_new_net(gerbv_net_t* currentNet, gerbv_layer_t* layer, gerbv_netstate_t* state);
 
-gboolean
-gerber_create_new_aperture (gerbv_image_t *image, int *indexNumber,
-		gerbv_aperture_type_t apertureType, gdouble parameter1, gdouble parameter2);
-		
-void gerber_update_image_min_max (gerbv_render_size_t *boundingBox, double repeat_off_X,
-		double repeat_off_Y, gerbv_image_t* image);
-void gerber_update_min_and_max(gerbv_render_size_t *boundingBox,
-			  gdouble x, gdouble y, gdouble apertureSizeX1,
-			  gdouble apertureSizeX2,gdouble apertureSizeY1,
-			  gdouble apertureSizeY2);
-const char *gerber_d_code_name(int d_code);
-const char *gerber_g_code_name(int g_code);
-const char *gerber_m_code_name(int m_code);
+gboolean gerber_create_new_aperture(
+    gerbv_image_t* image, int* indexNumber, gerbv_aperture_type_t apertureType, gdouble parameter1, gdouble parameter2
+);
+
+void gerber_update_image_min_max(
+    gerbv_render_size_t* boundingBox, double repeat_off_X, double repeat_off_Y, gerbv_image_t* image
+);
+void gerber_update_min_and_max(
+    gerbv_render_size_t* boundingBox, gdouble x, gdouble y, gdouble apertureSizeX1, gdouble apertureSizeX2,
+    gdouble apertureSizeY1, gdouble apertureSizeY2
+);
+const char* gerber_d_code_name(int d_code);
+const char* gerber_g_code_name(int g_code);
+const char* gerber_m_code_name(int m_code);
 #ifdef __cplusplus
 }
 #endif
diff --git a/src/gerbv.c b/src/gerbv.c
index db10cc9..7834c65 100644
--- a/src/gerbv.c
+++ b/src/gerbv.c
@@ -20,8 +20,7 @@
  * along with this program; if not, write to the Free Software
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA
  */
- 
- 
+
 /** \file gerbv.c
     \brief This file contains high-level functions for the libgerbv library
     \ingroup libgerbv
@@ -36,19 +35,19 @@
 #include <errno.h>
 
 #ifdef HAVE_LIBGEN_H
-# include <libgen.h> /* dirname */
+#include <libgen.h> /* dirname */
 #endif
 
 #ifdef HAVE_STRING_H
-# include <string.h>
+#include <string.h>
 #endif
 
 #ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
 #endif
 
 #ifdef HAVE_GETOPT_H
-# include <getopt.h>
+#include <getopt.h>
 #endif
 
 #include <pango/pango.h>
@@ -64,289 +63,275 @@
 #include "pick-and-place.h"
 
 /* DEBUG printing.  #define DEBUG 1 in config.h to use this fcn. */
-#define dprintf if(DEBUG) printf
+#define dprintf \
+    if (DEBUG)  \
+    printf
 
 /** Return string name of gerbv_aperture_type_t aperture type. */
-const char *gerbv_aperture_type_name(gerbv_aperture_type_t type)
-{
-	/* These are the names of the valid apertures.  Please keep this in
-	 * sync with the gerbv_aperture_type_t enum defined in gerbv.h */
-	const char *names[] = {
-		N_("none"),
-		N_("circle"),
-		N_("rectangle"),
-		N_("oval"),		/* ovular (obround) aperture */
-		N_("polygon"),		/* polygon aperture */
-		N_("macro"),		/* RS274X macro */
-		N_("circle macro"),	/* RS274X circle macro */
-		N_("outline macro"),	/* RS274X outline macro */
-		N_("polygon macro"),	/* RS274X polygon macro */
-		N_("moire macro"),	/* RS274X moire macro */
-		N_("thermal macro"),	/* RS274X thermal macro */
-		N_("line20 macro"),	/* RS274X line (code 20) macro */
-		N_("line21 macro"),	/* RS274X line (code 21) macro */
-		N_("line22 macro"),	/* RS274X line (code 22) macro */
-	};
-
-	if (type >=0 && type < sizeof(names)/sizeof(names[0]))
-		return names[type];
-
-	return N_("<undefined>");
+const char*
+gerbv_aperture_type_name(gerbv_aperture_type_t type) {
+    /* These are the names of the valid apertures.  Please keep this in
+     * sync with the gerbv_aperture_type_t enum defined in gerbv.h */
+    const char* names[] = {
+        N_("none"),          N_("circle"), N_("rectangle"), N_("oval"), /* ovular (obround) aperture */
+        N_("polygon"),                                                  /* polygon aperture */
+        N_("macro"),                                                    /* RS274X macro */
+        N_("circle macro"),                                             /* RS274X circle macro */
+        N_("outline macro"),                                            /* RS274X outline macro */
+        N_("polygon macro"),                                            /* RS274X polygon macro */
+        N_("moire macro"),                                              /* RS274X moire macro */
+        N_("thermal macro"),                                            /* RS274X thermal macro */
+        N_("line20 macro"),                                             /* RS274X line (code 20) macro */
+        N_("line21 macro"),                                             /* RS274X line (code 21) macro */
+        N_("line22 macro"),                                             /* RS274X line (code 22) macro */
+    };
+
+    if (type >= 0 && type < sizeof(names) / sizeof(names[0]))
+        return names[type];
+
+    return N_("<undefined>");
 }
 
 /** Return string name of gerbv_interpolation_t interpolation. */
-const char *gerbv_interpolation_name(gerbv_interpolation_t interp)
-{
-	/* These are the names of the interpolation method.  Please keep this
-	 * in sync with the gerbv_interpolation_t enum defined in gerbv.h */
-	const char *names[] = {
-		N_("1X linear"),
-		N_("10X linear"),
-		N_("0.1X linear"),
-		N_("0.01X linear"),
-		N_("CW circular"),
-		N_("CCW circular"),
-		N_("poly area start"),
-		N_("poly area stop"),
-		N_("deleted"),
-	};
-
-	if (interp >= 0 && interp < sizeof(names)/sizeof(names[0]))
-		return names[interp];
-
-	return N_("<undefined>");
+const char*
+gerbv_interpolation_name(gerbv_interpolation_t interp) {
+    /* These are the names of the interpolation method.  Please keep this
+     * in sync with the gerbv_interpolation_t enum defined in gerbv.h */
+    const char* names[] = {
+        N_("1X linear"),    N_("10X linear"),      N_("0.1X linear"),    N_("0.01X linear"), N_("CW circular"),
+        N_("CCW circular"), N_("poly area start"), N_("poly area stop"), N_("deleted"),
+    };
+
+    if (interp >= 0 && interp < sizeof(names) / sizeof(names[0]))
+        return names[interp];
+
+    return N_("<undefined>");
 }
 
-#define NUMBER_OF_DEFAULT_COLORS 18
+#define NUMBER_OF_DEFAULT_COLORS          18
 #define NUMBER_OF_DEFAULT_TRANSFORMATIONS 20
 
 static int defaultColorIndex = 0;
 
 /* ------------------------------------------------------------------ */
 static gerbv_layer_color defaultColors[NUMBER_OF_DEFAULT_COLORS] = {
-	{115,115,222,177},
-	{255,127,115,177},
-	{193,0,224,177},
-	{117,242,103,177},
-	{0,195,195,177},
-	{213,253,51,177},
-	{209,27,104,177},
-	{255,197,51,177},
-	{186,186,186,177},
-	{211,211,255,177},
-	{253,210,206,177},
-	{236,194,242,177},
-	{208,249,204,177},
-	{183,255,255,177},
-	{241,255,183,177},
-	{255,202,225,177},
-	{253,238,197,177},
-	{226,226,226,177}
+    {115, 115, 222, 177},
+    {255, 127, 115, 177},
+    {193,   0, 224, 177},
+    {117, 242, 103, 177},
+    {  0, 195, 195, 177},
+    {213, 253,  51, 177},
+    {209,  27, 104, 177},
+    {255, 197,  51, 177},
+    {186, 186, 186, 177},
+    {211, 211, 255, 177},
+    {253, 210, 206, 177},
+    {236, 194, 242, 177},
+    {208, 249, 204, 177},
+    {183, 255, 255, 177},
+    {241, 255, 183, 177},
+    {255, 202, 225, 177},
+    {253, 238, 197, 177},
+    {226, 226, 226, 177}
 };
 
 /* ------------------------------------------------------------------ */
 static gerbv_user_transformation_t defaultTransformations[NUMBER_OF_DEFAULT_TRANSFORMATIONS] = {
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},	
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},		
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},	
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
 };
 
 /* ------------------------------------------------------------------ */
-gerbv_project_t *
-gerbv_create_project (void) {
-	gerbv_project_t *returnProject= (gerbv_project_t *) g_new0(gerbv_project_t,1);
-	
-	/* default to using the current directory path for our starting guesses
-		on future file loads */
-	returnProject->path = g_get_current_dir ();
-	/* Will be updated to 0 when first Gerber is loaded */
-	returnProject->last_loaded = -1;
-	returnProject->max_files = 1;
-	returnProject->check_before_delete = TRUE;
-	returnProject->file = g_new0 (gerbv_fileinfo_t *, returnProject->max_files);
-
-	return returnProject;
+gerbv_project_t*
+gerbv_create_project(void) {
+    gerbv_project_t* returnProject = (gerbv_project_t*)g_new0(gerbv_project_t, 1);
+
+    /* default to using the current directory path for our starting guesses
+        on future file loads */
+    returnProject->path = g_get_current_dir();
+    /* Will be updated to 0 when first Gerber is loaded */
+    returnProject->last_loaded         = -1;
+    returnProject->max_files           = 1;
+    returnProject->check_before_delete = TRUE;
+    returnProject->file                = g_new0(gerbv_fileinfo_t*, returnProject->max_files);
+
+    return returnProject;
 }
 
 /* ------------------------------------------------------------------ */
 void
-gerbv_destroy_project (gerbv_project_t *gerbvProject)
-{
-	int i;
-	
-	/* destroy all the files attached to the project */
-	for(i = gerbvProject->last_loaded; i >= 0; i--) {
-		if (gerbvProject->file[i]) {
-			gerbv_destroy_fileinfo (gerbvProject->file[i]);
-			g_free(gerbvProject->file[i]);
-		}
-	}
-	/* destroy strings */
-	g_free (gerbvProject->path);
-	g_free (gerbvProject->execname);
-	g_free (gerbvProject->execpath);
-	g_free (gerbvProject->project);
-	/* destroy the fileinfo array */
-	g_free (gerbvProject->file);
-	g_free (gerbvProject);
+gerbv_destroy_project(gerbv_project_t* gerbvProject) {
+    int i;
+
+    /* destroy all the files attached to the project */
+    for (i = gerbvProject->last_loaded; i >= 0; i--) {
+        if (gerbvProject->file[i]) {
+            gerbv_destroy_fileinfo(gerbvProject->file[i]);
+            g_free(gerbvProject->file[i]);
+        }
+    }
+    /* destroy strings */
+    g_free(gerbvProject->path);
+    g_free(gerbvProject->execname);
+    g_free(gerbvProject->execpath);
+    g_free(gerbvProject->project);
+    /* destroy the fileinfo array */
+    g_free(gerbvProject->file);
+    g_free(gerbvProject);
 }
 
 /* ------------------------------------------------------------------ */
 void
-gerbv_destroy_fileinfo (gerbv_fileinfo_t *fileInfo){
-	gerbv_destroy_image (fileInfo->image);
-	g_free (fileInfo->fullPathname);
-	g_free (fileInfo->name);
-	if (fileInfo->privateRenderData) {
-		cairo_surface_destroy ((cairo_surface_t *)
-			fileInfo->privateRenderData);
-	}			
+gerbv_destroy_fileinfo(gerbv_fileinfo_t* fileInfo) {
+    gerbv_destroy_image(fileInfo->image);
+    g_free(fileInfo->fullPathname);
+    g_free(fileInfo->name);
+    if (fileInfo->privateRenderData) {
+        cairo_surface_destroy((cairo_surface_t*)fileInfo->privateRenderData);
+    }
 }
 
 /* ------------------------------------------------------------------ */
-void 
-gerbv_open_layer_from_filename(gerbv_project_t *gerbvProject, gchar const* filename)
-{
-  gint idx_loaded;
-  dprintf("Opening filename = %s\n", filename);
-  
-  if (gerbv_open_image(gerbvProject, filename, ++gerbvProject->last_loaded, FALSE, NULL, 0, TRUE) == -1) {
-    GERB_COMPILE_WARNING(_("Could not read \"%s\" (loaded %d)"),
-		    filename, gerbvProject->last_loaded);
-    gerbvProject->last_loaded--;
-  } else {
-    idx_loaded = gerbvProject->last_loaded;
-    gerbvProject->file[idx_loaded]->layer_dirty = FALSE;
-    dprintf("     Successfully opened file!\n");	
-  }
+void
+gerbv_open_layer_from_filename(gerbv_project_t* gerbvProject, const gchar* filename) {
+    gint idx_loaded;
+    dprintf("Opening filename = %s\n", filename);
+
+    if (gerbv_open_image(gerbvProject, filename, ++gerbvProject->last_loaded, FALSE, NULL, 0, TRUE) == -1) {
+        GERB_COMPILE_WARNING(_("Could not read \"%s\" (loaded %d)"), filename, gerbvProject->last_loaded);
+        gerbvProject->last_loaded--;
+    } else {
+        idx_loaded                                  = gerbvProject->last_loaded;
+        gerbvProject->file[idx_loaded]->layer_dirty = FALSE;
+        dprintf("     Successfully opened file!\n");
+    }
 } /* gerbv_open_layer_from_filename */
 
 /* ------------------------------------------------------------------ */
-void 
-gerbv_open_layer_from_filename_with_color(gerbv_project_t *gerbvProject, gchar const* filename,
-		guint16 red, guint16 green, guint16 blue, guint16 alpha)
-{
-  gint idx_loaded;
-  dprintf("Opening filename = %s\n", filename);
-  
-  if (gerbv_open_image(gerbvProject, filename, ++gerbvProject->last_loaded, FALSE, NULL, 0, TRUE) == -1) {
-    GERB_COMPILE_WARNING(_("Could not read \"%s\" (loaded %d)"),
-		    filename, gerbvProject->last_loaded);
-    gerbvProject->last_loaded--;
-  } else {
-    idx_loaded = gerbvProject->last_loaded;
-    gerbvProject->file[idx_loaded]->layer_dirty = FALSE;
-    GdkColor colorTemplate = {0, red, green, blue};
-    gerbvProject->file[idx_loaded]->color = colorTemplate;
-    gerbvProject->file[idx_loaded]->alpha = alpha;
-    dprintf("     Successfully opened file!\n");	
-  }
-} /* gerbv_open_layer_from_filename_with_color */  
-    
+void
+gerbv_open_layer_from_filename_with_color(
+    gerbv_project_t* gerbvProject, const gchar* filename, guint16 red, guint16 green, guint16 blue, guint16 alpha
+) {
+    gint idx_loaded;
+    dprintf("Opening filename = %s\n", filename);
+
+    if (gerbv_open_image(gerbvProject, filename, ++gerbvProject->last_loaded, FALSE, NULL, 0, TRUE) == -1) {
+        GERB_COMPILE_WARNING(_("Could not read \"%s\" (loaded %d)"), filename, gerbvProject->last_loaded);
+        gerbvProject->last_loaded--;
+    } else {
+        idx_loaded                                  = gerbvProject->last_loaded;
+        gerbvProject->file[idx_loaded]->layer_dirty = FALSE;
+        GdkColor colorTemplate                      = { 0, red, green, blue };
+        gerbvProject->file[idx_loaded]->color       = colorTemplate;
+        gerbvProject->file[idx_loaded]->alpha       = alpha;
+        dprintf("     Successfully opened file!\n");
+    }
+} /* gerbv_open_layer_from_filename_with_color */
+
 /* ------------------------------------------------------------------ */
-gboolean 
-gerbv_save_layer_from_index(gerbv_project_t *gerbvProject, gint index, gchar *filename) 
-{
-	gerbv_fileinfo_t *file = gerbvProject->file[index];
-	gerbv_user_transformation_t *trans = &file->transform;
-
-	switch (file->image->layertype) {
-	case GERBV_LAYERTYPE_RS274X:
-		if (trans) {
-			/* NOTE: mirrored file is not yet supported */
-			if (trans->mirrorAroundX || trans->mirrorAroundY) {
-				GERB_COMPILE_ERROR(_("Exporting mirrored file "
-							"is not supported!"));
-				return FALSE;
-			}
-
-			/* NOTE: inverted file is not yet supported */
-			if (trans->inverted) {
-				GERB_COMPILE_ERROR(_("Exporting inverted file "
-							"is not supported!"));
-				return FALSE;
-			}
-		}
-
-		gerbv_export_rs274x_file_from_image (filename,
-				file->image, trans);
-		break;
-
-	case GERBV_LAYERTYPE_DRILL:
-		if (trans) {
-			/* NOTE: inverted file is not yet supported */
-			if (trans->inverted) {
-				GERB_COMPILE_ERROR(_("Exporting inverted file "
-							"is not supported!"));
-				return FALSE;
-			}
-		}
-
-		gerbv_export_drill_file_from_image (filename,
-				file->image, trans);
-		break;
-	default:
-		return FALSE;
-	}
-
-	file->layer_dirty = FALSE;
-
-	return TRUE;
-}
+gboolean
+gerbv_save_layer_from_index(gerbv_project_t* gerbvProject, gint index, gchar* filename) {
+    gerbv_fileinfo_t*            file  = gerbvProject->file[index];
+    gerbv_user_transformation_t* trans = &file->transform;
+
+    switch (file->image->layertype) {
+        case GERBV_LAYERTYPE_RS274X:
+            if (trans) {
+                /* NOTE: mirrored file is not yet supported */
+                if (trans->mirrorAroundX || trans->mirrorAroundY) {
+                    GERB_COMPILE_ERROR(
+                        _("Exporting mirrored file "
+                          "is not supported!")
+                    );
+                    return FALSE;
+                }
+
+                /* NOTE: inverted file is not yet supported */
+                if (trans->inverted) {
+                    GERB_COMPILE_ERROR(
+                        _("Exporting inverted file "
+                          "is not supported!")
+                    );
+                    return FALSE;
+                }
+            }
+
+            gerbv_export_rs274x_file_from_image(filename, file->image, trans);
+            break;
+
+        case GERBV_LAYERTYPE_DRILL:
+            if (trans) {
+                /* NOTE: inverted file is not yet supported */
+                if (trans->inverted) {
+                    GERB_COMPILE_ERROR(
+                        _("Exporting inverted file "
+                          "is not supported!")
+                    );
+                    return FALSE;
+                }
+            }
+
+            gerbv_export_drill_file_from_image(filename, file->image, trans);
+            break;
+        default: return FALSE;
+    }
 
+    file->layer_dirty = FALSE;
+
+    return TRUE;
+}
 
 /* ------------------------------------------------------------------ */
 int
-gerbv_revert_file(gerbv_project_t *gerbvProject, int idx){
-  int rv;
-  
-  rv = gerbv_open_image(gerbvProject, gerbvProject->file[idx]->fullPathname, idx, TRUE, NULL, 0, TRUE);
-  gerbvProject->file[idx]->layer_dirty = FALSE;
-  return rv;
+gerbv_revert_file(gerbv_project_t* gerbvProject, int idx) {
+    int rv;
+
+    rv = gerbv_open_image(gerbvProject, gerbvProject->file[idx]->fullPathname, idx, TRUE, NULL, 0, TRUE);
+    gerbvProject->file[idx]->layer_dirty = FALSE;
+    return rv;
 }
 
 /* ------------------------------------------------------------------ */
-void 
-gerbv_revert_all_files(gerbv_project_t *gerbvProject) 
-{
-  int idx;
-  
-  for (idx = 0; idx <= gerbvProject->last_loaded; idx++) {
-    if (gerbvProject->file[idx] && gerbvProject->file[idx]->fullPathname) {
-      (void) gerbv_revert_file (gerbvProject, idx);
-      gerbvProject->file[idx]->layer_dirty = FALSE;
+void
+gerbv_revert_all_files(gerbv_project_t* gerbvProject) {
+    int idx;
+
+    for (idx = 0; idx <= gerbvProject->last_loaded; idx++) {
+        if (gerbvProject->file[idx] && gerbvProject->file[idx]->fullPathname) {
+            (void)gerbv_revert_file(gerbvProject, idx);
+            gerbvProject->file[idx]->layer_dirty = FALSE;
+        }
     }
-  }
 } /* gerbv_revert_all_files */
 
 /* ------------------------------------------------------------------ */
-void 
-gerbv_unload_layer(gerbv_project_t *gerbvProject, int index) 
-{
+void
+gerbv_unload_layer(gerbv_project_t* gerbvProject, int index) {
     gint i;
 
-    gerbv_destroy_fileinfo (gerbvProject->file[index]);
-    
+    gerbv_destroy_fileinfo(gerbvProject->file[index]);
+
     /* slide all later layers down to fill the empty slot */
-    for (i=index; i<(gerbvProject->last_loaded); i++) {
-	gerbvProject->file[i]=gerbvProject->file[i+1];
+    for (i = index; i < (gerbvProject->last_loaded); i++) {
+        gerbvProject->file[i] = gerbvProject->file[i + 1];
     }
     /* make sure the final spot is clear */
     gerbvProject->file[gerbvProject->last_loaded] = NULL;
@@ -354,106 +339,103 @@ gerbv_unload_layer(gerbv_project_t *gerbvProject, int index)
 } /* gerbv_unload_layer */
 
 /* ------------------------------------------------------------------ */
-void 
-gerbv_unload_all_layers (gerbv_project_t *gerbvProject) 
-{
+void
+gerbv_unload_all_layers(gerbv_project_t* gerbvProject) {
     int index;
 
     /* Must count down since gerbv_unload_layer collapses
      * layers down.  Otherwise, layers slide past the index */
-    for (index = gerbvProject->last_loaded ; index >= 0; index--) {
-	if (gerbvProject->file[index] && gerbvProject->file[index]->name) {
-	    gerbv_unload_layer (gerbvProject, index);
-	}
+    for (index = gerbvProject->last_loaded; index >= 0; index--) {
+        if (gerbvProject->file[index] && gerbvProject->file[index]->name) {
+            gerbv_unload_layer(gerbvProject, index);
+        }
     }
 } /* gerbv_unload_all_layers */
 
-
 /* ------------------------------------------------------------------ */
-void 
-gerbv_change_layer_order(gerbv_project_t *gerbvProject, gint oldPosition, gint newPosition) 
-{
-    gerbv_fileinfo_t *temp_file;
-    int index;
-    
+void
+gerbv_change_layer_order(gerbv_project_t* gerbvProject, gint oldPosition, gint newPosition) {
+    gerbv_fileinfo_t* temp_file;
+    int               index;
+
     temp_file = gerbvProject->file[oldPosition];
-	
-    if (oldPosition < newPosition){
-	for (index = oldPosition; index < newPosition; index++) {
-	    gerbvProject->file[index] = gerbvProject->file[index + 1];
-	}
+
+    if (oldPosition < newPosition) {
+        for (index = oldPosition; index < newPosition; index++) {
+            gerbvProject->file[index] = gerbvProject->file[index + 1];
+        }
     } else {
-	for (index = oldPosition; index > newPosition; index--) {
-	    gerbvProject->file[index] = gerbvProject->file[index - 1];
-	}
+        for (index = oldPosition; index > newPosition; index--) {
+            gerbvProject->file[index] = gerbvProject->file[index - 1];
+        }
     }
     gerbvProject->file[newPosition] = temp_file;
 } /* gerbv_change_layer_order */
 
-
 /* ------------------------------------------------------------------ */
 gint
-gerbv_add_parsed_image_to_project (gerbv_project_t *gerbvProject, gerbv_image_t *parsed_image,
-			gchar const* filename, gchar const* baseName, int idx, int reload){
+gerbv_add_parsed_image_to_project(
+    gerbv_project_t* gerbvProject, gerbv_image_t* parsed_image, const gchar* filename, const gchar* baseName, int idx,
+    int reload
+) {
     gerb_verify_error_t error = GERB_IMAGE_OK;
-    int r, g, b; 
-    
+    int                 r, g, b;
+
     dprintf("In open_image, now error check file....\n");
     error = gerbv_image_verify(parsed_image);
 
     if (error) {
-	if (error & GERB_IMAGE_MISSING_NETLIST) {
-	    GERB_COMPILE_ERROR(_("Missing netlist - aborting file read"));
-	    gerbv_destroy_image(parsed_image);
-	    return -1;
-	}
-	/* if the error was one of the following, try to open up the file anyways in case
-	   the file is a poorly formatted RS-274X file */
-	if (error & GERB_IMAGE_MISSING_FORMAT)
-	    g_warning(_("Missing format in file...trying to load anyways\n"));
-	if (error & GERB_IMAGE_MISSING_APERTURES) {
-	    g_warning(_("Missing apertures/drill sizes...trying to load anyways\n"));
-	    /* step through the file and check for aperture references. For each one found, create
-	       a dummy aperture holder to visually draw something on the screen */
-	    gerbv_image_create_dummy_apertures (parsed_image);
-	}
-	if (error & GERB_IMAGE_MISSING_INFO)
-	    g_warning(_("Missing info...trying to load anyways\n"));
+        if (error & GERB_IMAGE_MISSING_NETLIST) {
+            GERB_COMPILE_ERROR(_("Missing netlist - aborting file read"));
+            gerbv_destroy_image(parsed_image);
+            return -1;
+        }
+        /* if the error was one of the following, try to open up the file anyways in case
+           the file is a poorly formatted RS-274X file */
+        if (error & GERB_IMAGE_MISSING_FORMAT)
+            g_warning(_("Missing format in file...trying to load anyways\n"));
+        if (error & GERB_IMAGE_MISSING_APERTURES) {
+            g_warning(_("Missing apertures/drill sizes...trying to load anyways\n"));
+            /* step through the file and check for aperture references. For each one found, create
+               a dummy aperture holder to visually draw something on the screen */
+            gerbv_image_create_dummy_apertures(parsed_image);
+        }
+        if (error & GERB_IMAGE_MISSING_INFO)
+            g_warning(_("Missing info...trying to load anyways\n"));
     }
-    
+
     /*
      * If reload, just exchange the image. Else we have to allocate
      * a new memory before we define anything more.
      */
     if (reload) {
-	gerbv_destroy_image(gerbvProject->file[idx]->image);
-	gerbvProject->file[idx]->image = parsed_image;
-	return 0;
+        gerbv_destroy_image(gerbvProject->file[idx]->image);
+        gerbvProject->file[idx]->image = parsed_image;
+        return 0;
     } else {
-	/* Load new file. */
-	gerbvProject->file[idx] = (gerbv_fileinfo_t *) g_new0 (gerbv_fileinfo_t, 1);
-	gerbvProject->file[idx]->image = parsed_image;
+        /* Load new file. */
+        gerbvProject->file[idx]        = (gerbv_fileinfo_t*)g_new0(gerbv_fileinfo_t, 1);
+        gerbvProject->file[idx]->image = parsed_image;
     }
-    
+
     /*
      * Store filename for eventual reload
      */
-    gerbvProject->file[idx]->fullPathname = g_strdup (filename);
-    gerbvProject->file[idx]->name = g_strdup (baseName);
-    
-    
-    r = defaultColors[defaultColorIndex % NUMBER_OF_DEFAULT_COLORS].red*257;
-    g = defaultColors[defaultColorIndex % NUMBER_OF_DEFAULT_COLORS].green*257;
-    b = defaultColors[defaultColorIndex % NUMBER_OF_DEFAULT_COLORS].blue*257;
-
-    GdkColor colorTemplate = {0, r, g, b};
-    gerbvProject->file[idx]->color = colorTemplate;
-    gerbvProject->file[idx]->alpha = defaultColors[defaultColorIndex % NUMBER_OF_DEFAULT_COLORS].alpha*257;
+    gerbvProject->file[idx]->fullPathname = g_strdup(filename);
+    gerbvProject->file[idx]->name         = g_strdup(baseName);
+
+    r = defaultColors[defaultColorIndex % NUMBER_OF_DEFAULT_COLORS].red * 257;
+    g = defaultColors[defaultColorIndex % NUMBER_OF_DEFAULT_COLORS].green * 257;
+    b = defaultColors[defaultColorIndex % NUMBER_OF_DEFAULT_COLORS].blue * 257;
+
+    GdkColor colorTemplate             = { 0, r, g, b };
+    gerbvProject->file[idx]->color     = colorTemplate;
+    gerbvProject->file[idx]->alpha     = defaultColors[defaultColorIndex % NUMBER_OF_DEFAULT_COLORS].alpha * 257;
     gerbvProject->file[idx]->isVisible = TRUE;
     gerbvProject->file[idx]->transform = defaultTransformations[defaultColorIndex % NUMBER_OF_DEFAULT_TRANSFORMATIONS];
     /* update the number of files if we need to */
     if (gerbvProject->last_loaded <= idx) {
-	gerbvProject->last_loaded = idx;
+        gerbvProject->last_loaded = idx;
     }
     defaultColorIndex++;
     return 1;
@@ -461,50 +443,46 @@ gerbv_add_parsed_image_to_project (gerbv_project_t *gerbvProject, gerbv_image_t
 
 /* ------------------------------------------------------------------ */
 int
-gerbv_open_image(gerbv_project_t *gerbvProject, gchar const* filename, int idx, int reload,
-		gerbv_HID_Attribute *fattr, int n_fattr, gboolean forceLoadFile)
-{
-    gerb_file_t *fd;
-    gerbv_image_t *parsed_image = NULL, *parsed_image2 = NULL;
-    gint retv = -1;
-    gboolean isPnpFile = FALSE, foundBinary;
-    gerbv_HID_Attribute *attr_list = NULL;
-    int n_attr = 0;
+gerbv_open_image(
+    gerbv_project_t* gerbvProject, const gchar* filename, int idx, int reload, gerbv_HID_Attribute* fattr, int n_fattr,
+    gboolean forceLoadFile
+) {
+    gerb_file_t*         fd;
+    gerbv_image_t *      parsed_image = NULL, *parsed_image2 = NULL;
+    gint                 retv      = -1;
+    gboolean             isPnpFile = FALSE, foundBinary;
+    gerbv_HID_Attribute* attr_list = NULL;
+    int                  n_attr    = 0;
     /* If we're reloading, we'll pass in our file format attribute list
      * since this is our hook for letting the user override the fileformat.
      */
-    if (reload)
-	{
-	    /* We're reloading so use the attribute list in memory */
-	    attr_list =  gerbvProject->file[idx]->image->info->attr_list;
-	    n_attr =  gerbvProject->file[idx]->image->info->n_attr;
-	}
-    else
-	{
-	    /* We're not reloading so use the attribute list read from the 
-	     * project file if given or NULL otherwise.
-	     */
-	    attr_list = fattr;
-	    n_attr = n_fattr;
-	}
-    /* if we don't have enough spots, then grow the file list by 2 to account for the possible 
+    if (reload) {
+        /* We're reloading so use the attribute list in memory */
+        attr_list = gerbvProject->file[idx]->image->info->attr_list;
+        n_attr    = gerbvProject->file[idx]->image->info->n_attr;
+    } else {
+        /* We're not reloading so use the attribute list read from the
+         * project file if given or NULL otherwise.
+         */
+        attr_list = fattr;
+        n_attr    = n_fattr;
+    }
+    /* if we don't have enough spots, then grow the file list by 2 to account for the possible
        loading of two images for PNP files */
-    if ((idx+1) >= gerbvProject->max_files) {
-	gerbvProject->file = g_renew (gerbv_fileinfo_t *,
-			gerbvProject->file, gerbvProject->max_files + 2);
+    if ((idx + 1) >= gerbvProject->max_files) {
+        gerbvProject->file = g_renew(gerbv_fileinfo_t*, gerbvProject->file, gerbvProject->max_files + 2);
 
-	gerbvProject->file[gerbvProject->max_files] = NULL;
-	gerbvProject->file[gerbvProject->max_files+1] = NULL;
-	gerbvProject->max_files += 2;
+        gerbvProject->file[gerbvProject->max_files]     = NULL;
+        gerbvProject->file[gerbvProject->max_files + 1] = NULL;
+        gerbvProject->max_files += 2;
     }
-    
+
     dprintf("In open_image, about to try opening filename = %s\n", filename);
-    
+
     fd = gerb_fopen(filename);
     if (fd == NULL) {
-	GERB_COMPILE_ERROR(_("Trying to open \"%s\": %s"),
-			filename, strerror(errno));
-	return -1;
+        GERB_COMPILE_ERROR(_("Trying to open \"%s\": %s"), filename, strerror(errno));
+        return -1;
     }
 
     dprintf("In open_image, successfully opened file.  Now check its type....\n");
@@ -515,82 +493,84 @@ gerbv_open_image(gerbv_project_t *gerbvProject, gchar const* filename, int idx,
        ahead and try to load it anyways) */
 
     if (gerber_is_rs274x_p(fd, &foundBinary)) {
-	dprintf("Found RS-274X file\n");
-	if (!foundBinary || forceLoadFile) {
-		/* figure out the directory path in case parse_gerb needs to
-		 * load any include files */
-		gchar *currentLoadDirectory = g_path_get_dirname (filename);
-		parsed_image = parse_gerb(fd, currentLoadDirectory);
-		g_free (currentLoadDirectory);
-	}
-    } else if(drill_file_p(fd, &foundBinary)) {
-	dprintf("Found drill file\n");
-	if (!foundBinary || forceLoadFile)
-	    parsed_image = parse_drillfile(fd, attr_list, n_attr, reload);
-	
+        dprintf("Found RS-274X file\n");
+        if (!foundBinary || forceLoadFile) {
+            /* figure out the directory path in case parse_gerb needs to
+             * load any include files */
+            gchar* currentLoadDirectory = g_path_get_dirname(filename);
+            parsed_image                = parse_gerb(fd, currentLoadDirectory);
+            g_free(currentLoadDirectory);
+        }
+    } else if (drill_file_p(fd, &foundBinary)) {
+        dprintf("Found drill file\n");
+        if (!foundBinary || forceLoadFile)
+            parsed_image = parse_drillfile(fd, attr_list, n_attr, reload);
+
     } else if (pick_and_place_check_file_type(fd, &foundBinary)) {
-	dprintf("Found pick-n-place file\n");
-	if (!foundBinary || forceLoadFile) {
-		if (!reload) {
-			pick_and_place_parse_file_to_images(fd, &parsed_image, &parsed_image2);
-		} else {
-			switch (gerbvProject->file[idx]->image->layertype) {
-			case GERBV_LAYERTYPE_PICKANDPLACE_TOP:
-				/* Non NULL pointer is used as "not to reload" mark */
-				parsed_image2 = (void *)!NULL;
-				pick_and_place_parse_file_to_images(fd, &parsed_image, &parsed_image2);
-				parsed_image2 = NULL;
-				break;
-			case GERBV_LAYERTYPE_PICKANDPLACE_BOT:
-				/* Non NULL pointer is used as "not to reload" mark */
-				parsed_image2 = (void *)!NULL;
-				pick_and_place_parse_file_to_images(fd, &parsed_image2, &parsed_image);
-				parsed_image2 = NULL;
-				break;
-			default:
-				GERB_COMPILE_ERROR(_("%s: unknown pick-and-place board side to reload"), filename);
-			}
-		}
-			
-		isPnpFile = TRUE;
-	}
+        dprintf("Found pick-n-place file\n");
+        if (!foundBinary || forceLoadFile) {
+            if (!reload) {
+                pick_and_place_parse_file_to_images(fd, &parsed_image, &parsed_image2);
+            } else {
+                switch (gerbvProject->file[idx]->image->layertype) {
+                    case GERBV_LAYERTYPE_PICKANDPLACE_TOP:
+                        /* Non NULL pointer is used as "not to reload" mark */
+                        parsed_image2 = (void*)!NULL;
+                        pick_and_place_parse_file_to_images(fd, &parsed_image, &parsed_image2);
+                        parsed_image2 = NULL;
+                        break;
+                    case GERBV_LAYERTYPE_PICKANDPLACE_BOT:
+                        /* Non NULL pointer is used as "not to reload" mark */
+                        parsed_image2 = (void*)!NULL;
+                        pick_and_place_parse_file_to_images(fd, &parsed_image2, &parsed_image);
+                        parsed_image2 = NULL;
+                        break;
+                    default: GERB_COMPILE_ERROR(_("%s: unknown pick-and-place board side to reload"), filename);
+                }
+            }
+
+            isPnpFile = TRUE;
+        }
     } else if (gerber_is_rs274d_p(fd)) {
-	gchar *str = g_strdup_printf(_("Most likely found a RS-274D file "
-			"\"%s\" ... trying to open anyways\n"), filename);
-	dprintf("%s", str);
-	g_warning("%s", str);
-	g_free (str);
-
-	if (!foundBinary || forceLoadFile) {
-		/* figure out the directory path in case parse_gerb needs to
-		 * load any include files */
-		gchar *currentLoadDirectory = g_path_get_dirname (filename);
-		parsed_image = parse_gerb(fd, currentLoadDirectory);
-		g_free (currentLoadDirectory);
-	}
+        gchar* str = g_strdup_printf(
+            _("Most likely found a RS-274D file "
+              "\"%s\" ... trying to open anyways\n"),
+            filename
+        );
+        dprintf("%s", str);
+        g_warning("%s", str);
+        g_free(str);
+
+        if (!foundBinary || forceLoadFile) {
+            /* figure out the directory path in case parse_gerb needs to
+             * load any include files */
+            gchar* currentLoadDirectory = g_path_get_dirname(filename);
+            parsed_image                = parse_gerb(fd, currentLoadDirectory);
+            g_free(currentLoadDirectory);
+        }
     } else {
-	/* This is not a known file */
-	dprintf("Unknown filetype");
-	GERB_COMPILE_ERROR(_("%s: Unknown file type."), filename);
-	parsed_image = NULL;
+        /* This is not a known file */
+        dprintf("Unknown filetype");
+        GERB_COMPILE_ERROR(_("%s: Unknown file type."), filename);
+        parsed_image = NULL;
     }
-    
+
     gerb_fclose(fd);
     if (parsed_image == NULL) {
-	return -1;
+        return -1;
     }
-    
+
     if (parsed_image) {
-	/* strip the filename to the base */
-	gchar *baseName = g_path_get_basename (filename);
-	gchar *displayedName;
-	if (isPnpFile)
-		displayedName = g_strconcat (baseName, _(" (top)"), NULL);
-	else
-		displayedName = g_strdup (baseName);
-    	retv = gerbv_add_parsed_image_to_project (gerbvProject, parsed_image, filename, displayedName, idx, reload);
-    	g_free (baseName);
-    	g_free (displayedName);
+        /* strip the filename to the base */
+        gchar* baseName = g_path_get_basename(filename);
+        gchar* displayedName;
+        if (isPnpFile)
+            displayedName = g_strconcat(baseName, _(" (top)"), NULL);
+        else
+            displayedName = g_strdup(baseName);
+        retv = gerbv_add_parsed_image_to_project(gerbvProject, parsed_image, filename, displayedName, idx, reload);
+        g_free(baseName);
+        g_free(displayedName);
     }
 
     /* Set layer_dirty flag to FALSE */
@@ -599,522 +579,499 @@ gerbv_open_image(gerbv_project_t *gerbvProject, gchar const* filename, int idx,
     /* for PNP place files, we may need to add a second image for the other
        board side */
     if (parsed_image2) {
-      /* strip the filename to the base */
-	gchar *baseName = g_path_get_basename (filename);
-	gchar *displayedName;
-	displayedName = g_strconcat (baseName, _(" (bottom)"), NULL);
-    	retv = gerbv_add_parsed_image_to_project (gerbvProject, parsed_image2, filename, displayedName, idx + 1, reload);
-    	g_free (baseName);
-    	g_free (displayedName);
+        /* strip the filename to the base */
+        gchar* baseName = g_path_get_basename(filename);
+        gchar* displayedName;
+        displayedName = g_strconcat(baseName, _(" (bottom)"), NULL);
+        retv = gerbv_add_parsed_image_to_project(gerbvProject, parsed_image2, filename, displayedName, idx + 1, reload);
+        g_free(baseName);
+        g_free(displayedName);
     }
 
     return retv;
 } /* open_image */
 
-gerbv_image_t *
-gerbv_create_rs274x_image_from_filename (gchar const* filename){
-	gerbv_image_t *returnImage;
-	gerb_file_t *fd;
-	
-	fd = gerb_fopen(filename);
-	if (fd == NULL) {
-		GERB_COMPILE_ERROR(_("Trying to open \"%s\": %s"),
-				filename, strerror(errno));
-		return NULL;
-	}
-	gchar *currentLoadDirectory = g_path_get_dirname (filename);
-	returnImage = parse_gerb(fd, currentLoadDirectory);
-	g_free (currentLoadDirectory);
-	gerb_fclose(fd);
-	return returnImage;
+gerbv_image_t*
+gerbv_create_rs274x_image_from_filename(const gchar* filename) {
+    gerbv_image_t* returnImage;
+    gerb_file_t*   fd;
+
+    fd = gerb_fopen(filename);
+    if (fd == NULL) {
+        GERB_COMPILE_ERROR(_("Trying to open \"%s\": %s"), filename, strerror(errno));
+        return NULL;
+    }
+    gchar* currentLoadDirectory = g_path_get_dirname(filename);
+    returnImage                 = parse_gerb(fd, currentLoadDirectory);
+    g_free(currentLoadDirectory);
+    gerb_fclose(fd);
+    return returnImage;
 }
 
-static inline int isnormal_or_zero(double x)
-{
-	int cl = fpclassify(x);
-	return cl == FP_NORMAL || cl == FP_ZERO;
+static inline int
+isnormal_or_zero(double x) {
+    int cl = fpclassify(x);
+    return cl == FP_NORMAL || cl == FP_ZERO;
 }
 
 /* ------------------------------------------------------------------ */
 void
-gerbv_render_get_boundingbox(gerbv_project_t *gerbvProject, gerbv_render_size_t *boundingbox)
-{
-	double x1=HUGE_VAL,y1=HUGE_VAL, x2=-HUGE_VAL,y2=-HUGE_VAL;
-	int i;
-	gerbv_image_info_t *info;
-	gdouble minX, minY, maxX, maxY;
-	
-	for(i = 0; i <= gerbvProject->last_loaded; i++) {
-		if (gerbvProject->file[i] && gerbvProject->file[i]->isVisible){
-			
-			
-			info = gerbvProject->file[i]->image->info;
-			/* 
-			* Find the biggest image and use as a size reference
-			*/
-			/* cairo info already has offset calculated into min/max */
-			
-			minX = info->min_x;
-			minY = info->min_y;
-			maxX = info->max_x;
-			maxY = info->max_y;
-
-			if (!isnormal_or_zero(minX) || !isnormal_or_zero(minY)
-			 || !isnormal_or_zero(maxX) || !isnormal_or_zero(maxY)) {
-				continue;
-			}
-
-			/* transform the bounding box based on the user transform */
-			cairo_matrix_t fullMatrix;
-			cairo_matrix_init (&fullMatrix, 1, 0, 0, 1, 0, 0);
-
-			cairo_matrix_translate (&fullMatrix, gerbvProject->file[i]->transform.translateX,
-				gerbvProject->file[i]->transform.translateY);
-			// don't use mirroring for the scale matrix
-			gdouble scaleX = gerbvProject->file[i]->transform.scaleX;
-			gdouble scaleY = gerbvProject->file[i]->transform.scaleY;
-			if (gerbvProject->file[i]->transform.mirrorAroundX)
-				scaleY *= -1;
-			if (gerbvProject->file[i]->transform.mirrorAroundY)
-				scaleX *= -1;
-			cairo_matrix_scale (&fullMatrix, scaleX, scaleY);
-			cairo_matrix_rotate (&fullMatrix, gerbvProject->file[i]->transform.rotation);	
-			
-			cairo_matrix_transform_point (&fullMatrix, &minX, &minY);
-			cairo_matrix_transform_point (&fullMatrix, &maxX, &maxY);
-			/* compare to both min and max, since a mirror transform may have made the "max"
-			    number smaller than the "min" */
-			x1 = MIN(x1, minX);
-			x1 = MIN(x1, maxX);
-			y1 = MIN(y1, minY);
-			y1 = MIN(y1, maxY);
-			x2 = MAX(x2, minX);
-			x2 = MAX(x2, maxX);
-			y2 = MAX(y2, minY);
-			y2 = MAX(y2, maxY);
-		}
-	}
-	boundingbox->left    = x1;
-	boundingbox->right   = x2;
-	boundingbox->top    = y1;
-	boundingbox->bottom = y2;
+gerbv_render_get_boundingbox(gerbv_project_t* gerbvProject, gerbv_render_size_t* boundingbox) {
+    double              x1 = HUGE_VAL, y1 = HUGE_VAL, x2 = -HUGE_VAL, y2 = -HUGE_VAL;
+    int                 i;
+    gerbv_image_info_t* info;
+    gdouble             minX, minY, maxX, maxY;
+
+    for (i = 0; i <= gerbvProject->last_loaded; i++) {
+        if (gerbvProject->file[i] && gerbvProject->file[i]->isVisible) {
+
+            info = gerbvProject->file[i]->image->info;
+            /*
+             * Find the biggest image and use as a size reference
+             */
+            /* cairo info already has offset calculated into min/max */
+
+            minX = info->min_x;
+            minY = info->min_y;
+            maxX = info->max_x;
+            maxY = info->max_y;
+
+            if (!isnormal_or_zero(minX) || !isnormal_or_zero(minY) || !isnormal_or_zero(maxX)
+                || !isnormal_or_zero(maxY)) {
+                continue;
+            }
+
+            /* transform the bounding box based on the user transform */
+            cairo_matrix_t fullMatrix;
+            cairo_matrix_init(&fullMatrix, 1, 0, 0, 1, 0, 0);
+
+            cairo_matrix_translate(
+                &fullMatrix, gerbvProject->file[i]->transform.translateX, gerbvProject->file[i]->transform.translateY
+            );
+            // don't use mirroring for the scale matrix
+            gdouble scaleX = gerbvProject->file[i]->transform.scaleX;
+            gdouble scaleY = gerbvProject->file[i]->transform.scaleY;
+            if (gerbvProject->file[i]->transform.mirrorAroundX)
+                scaleY *= -1;
+            if (gerbvProject->file[i]->transform.mirrorAroundY)
+                scaleX *= -1;
+            cairo_matrix_scale(&fullMatrix, scaleX, scaleY);
+            cairo_matrix_rotate(&fullMatrix, gerbvProject->file[i]->transform.rotation);
+
+            cairo_matrix_transform_point(&fullMatrix, &minX, &minY);
+            cairo_matrix_transform_point(&fullMatrix, &maxX, &maxY);
+            /* compare to both min and max, since a mirror transform may have made the "max"
+                number smaller than the "min" */
+            x1 = MIN(x1, minX);
+            x1 = MIN(x1, maxX);
+            y1 = MIN(y1, minY);
+            y1 = MIN(y1, maxY);
+            x2 = MAX(x2, minX);
+            x2 = MAX(x2, maxX);
+            y2 = MAX(y2, minY);
+            y2 = MAX(y2, maxY);
+        }
+    }
+    boundingbox->left   = x1;
+    boundingbox->right  = x2;
+    boundingbox->top    = y1;
+    boundingbox->bottom = y2;
 }
 
 /* ------------------------------------------------------------------ */
 void
-gerbv_render_zoom_to_fit_display (gerbv_project_t *gerbvProject, gerbv_render_info_t *renderInfo)
-{
-	gerbv_render_size_t bb;
-	double width, height;
-	double x_scale, y_scale;
-
-	/* Grab maximal width and height of all layers */
-	gerbv_render_get_boundingbox(gerbvProject, &bb);
-	width = bb.right - bb.left;
-	height = bb.bottom - bb.top;
-	/* add in a 5% buffer around the drawing */
-	width *= 1.05;
-	height *=1.05;
-
-	/* if the values aren't sane (probably we have no models loaded), then
-	   put in some defaults */
-	if (!isnormal(width)||!isnormal(height)||((width < 0.01) && (height < 0.01))) {
-		renderInfo->lowerLeftX = 0.0;
-		renderInfo->lowerLeftY = 0.0;
-		renderInfo->scaleFactorX = 200;
-		renderInfo->scaleFactorY = renderInfo->scaleFactorX;
-		return;
-	}
-	/*
-	* Calculate scale for both x axis and y axis
-	*/
-	x_scale = renderInfo->displayWidth / width;
-	y_scale = renderInfo->displayHeight / height;
-	/*
-	* Take the scale that fits both directions with some extra checks
-	*/
-	renderInfo->scaleFactorX = MIN(x_scale, y_scale);
-	renderInfo->scaleFactorX = MIN((gdouble)GERBV_SCALE_MAX,
-			renderInfo->scaleFactorX);
-	renderInfo->scaleFactorX = MAX((gdouble)GERBV_SCALE_MIN,
-			renderInfo->scaleFactorX);
-	renderInfo->scaleFactorY = renderInfo->scaleFactorX;
-	renderInfo->lowerLeftX = ((bb.left + bb.right) / 2.0) -
-		((double) renderInfo->displayWidth / 2.0 / renderInfo->scaleFactorX);
-	renderInfo->lowerLeftY = ((bb.top + bb.bottom) / 2.0) -
-		((double) renderInfo->displayHeight / 2.0 / renderInfo->scaleFactorY);
+gerbv_render_zoom_to_fit_display(gerbv_project_t* gerbvProject, gerbv_render_info_t* renderInfo) {
+    gerbv_render_size_t bb;
+    double              width, height;
+    double              x_scale, y_scale;
+
+    /* Grab maximal width and height of all layers */
+    gerbv_render_get_boundingbox(gerbvProject, &bb);
+    width  = bb.right - bb.left;
+    height = bb.bottom - bb.top;
+    /* add in a 5% buffer around the drawing */
+    width *= 1.05;
+    height *= 1.05;
+
+    /* if the values aren't sane (probably we have no models loaded), then
+       put in some defaults */
+    if (!isnormal(width) || !isnormal(height) || ((width < 0.01) && (height < 0.01))) {
+        renderInfo->lowerLeftX   = 0.0;
+        renderInfo->lowerLeftY   = 0.0;
+        renderInfo->scaleFactorX = 200;
+        renderInfo->scaleFactorY = renderInfo->scaleFactorX;
+        return;
+    }
+    /*
+     * Calculate scale for both x axis and y axis
+     */
+    x_scale = renderInfo->displayWidth / width;
+    y_scale = renderInfo->displayHeight / height;
+    /*
+     * Take the scale that fits both directions with some extra checks
+     */
+    renderInfo->scaleFactorX = MIN(x_scale, y_scale);
+    renderInfo->scaleFactorX = MIN((gdouble)GERBV_SCALE_MAX, renderInfo->scaleFactorX);
+    renderInfo->scaleFactorX = MAX((gdouble)GERBV_SCALE_MIN, renderInfo->scaleFactorX);
+    renderInfo->scaleFactorY = renderInfo->scaleFactorX;
+    renderInfo->lowerLeftX =
+        ((bb.left + bb.right) / 2.0) - ((double)renderInfo->displayWidth / 2.0 / renderInfo->scaleFactorX);
+    renderInfo->lowerLeftY =
+        ((bb.top + bb.bottom) / 2.0) - ((double)renderInfo->displayHeight / 2.0 / renderInfo->scaleFactorY);
 }
 
 /* ------------------------------------------------------------------ */
 void
-gerbv_render_translate_to_fit_display (gerbv_project_t *gerbvProject, gerbv_render_info_t *renderInfo) {
-	gerbv_render_size_t bb;
-
-	/* Grab maximal width and height of all layers */
-	gerbv_render_get_boundingbox(gerbvProject, &bb);
-	renderInfo->lowerLeftX = ((bb.left + bb.right) / 2.0) -
-		((double) renderInfo->displayWidth / 2.0 / renderInfo->scaleFactorX);
-	renderInfo->lowerLeftY = ((bb.top + bb.bottom) / 2.0) -
-		((double) renderInfo->displayHeight / 2.0 / renderInfo->scaleFactorY);
+gerbv_render_translate_to_fit_display(gerbv_project_t* gerbvProject, gerbv_render_info_t* renderInfo) {
+    gerbv_render_size_t bb;
+
+    /* Grab maximal width and height of all layers */
+    gerbv_render_get_boundingbox(gerbvProject, &bb);
+    renderInfo->lowerLeftX =
+        ((bb.left + bb.right) / 2.0) - ((double)renderInfo->displayWidth / 2.0 / renderInfo->scaleFactorX);
+    renderInfo->lowerLeftY =
+        ((bb.top + bb.bottom) / 2.0) - ((double)renderInfo->displayHeight / 2.0 / renderInfo->scaleFactorY);
 }
 
 /* ------------------------------------------------------------------ */
 void
-gerbv_render_to_pixmap_using_gdk (gerbv_project_t *gerbvProject, GdkPixmap *pixmap,
-		gerbv_render_info_t *renderInfo, gerbv_selection_info_t *selectionInfo,
-		GdkColor *selectionColor){
-	GdkGC *gc = gdk_gc_new(pixmap);
-	GdkPixmap *colorStamp, *clipmask;
-	int i;
-	
-	/* 
-	 * Remove old pixmap, allocate a new one, draw the background.
-	 */
-	if (!gerbvProject->background.pixel)
-	 	gdk_colormap_alloc_color(gdk_colormap_get_system(), &gerbvProject->background, FALSE, TRUE);
-	gdk_gc_set_foreground(gc, &gerbvProject->background);
-	gdk_draw_rectangle(pixmap, gc, TRUE, 0, 0, -1, -1);
-
-	/*
-	 * Allocate the pixmap and the clipmask (a one pixel pixmap)
-	 */
-	colorStamp = gdk_pixmap_new(pixmap, renderInfo->displayWidth,
-						renderInfo->displayHeight, -1);
-	clipmask = gdk_pixmap_new(NULL, renderInfo->displayWidth,
-						renderInfo->displayHeight, 1);
-							
-	/* 
-	* This now allows drawing several layers on top of each other.
-	* Higher layer numbers have higher priority in the Z-order. 
-	*/
-	for(i = gerbvProject->last_loaded; i >= 0; i--) {
-		if (gerbvProject->file[i] && gerbvProject->file[i]->isVisible) {
-			/*
-			* Fill up image with all the foreground color. Excess pixels
-			* will be removed by clipmask.
-			*/
-			if (!gerbvProject->file[i]->color.pixel)
-	 			gdk_colormap_alloc_color(gdk_colormap_get_system(), &gerbvProject->file[i]->color, FALSE, TRUE);
-			gdk_gc_set_foreground(gc, &gerbvProject->file[i]->color);
-			
-			/* switch back to regular draw function for the initial
-			   bitmap clear */
-			gdk_gc_set_function(gc, GDK_COPY);
-			gdk_draw_rectangle(colorStamp, gc, TRUE, 0, 0, -1, -1);
-			
-			if (renderInfo->renderType == GERBV_RENDER_TYPE_GDK) {
-				gdk_gc_set_function(gc, GDK_COPY);
-			}
-			else if (renderInfo->renderType == GERBV_RENDER_TYPE_GDK_XOR) {
-				gdk_gc_set_function(gc, GDK_XOR);
-			}
-			/*
-			* Translation is to get it inside the allocated pixmap,
-			* which is not always centered perfectly for GTK/X.
-			*/
-			dprintf("  .... calling image2pixmap on image %d...\n", i);
-			// Dirty scaling solution when using GDK; simply use scaling factor for x-axis, ignore y-axis
-			draw_gdk_image_to_pixmap(&clipmask, gerbvProject->file[i]->image,
-				renderInfo->scaleFactorX, -(renderInfo->lowerLeftX * renderInfo->scaleFactorX),
-				(renderInfo->lowerLeftY * renderInfo->scaleFactorY) + renderInfo->displayHeight,
-				DRAW_IMAGE, NULL, renderInfo, gerbvProject->file[i]->transform);
-
-			/* 
-			* Set clipmask and draw the clipped out image onto the
-			* screen pixmap. Afterwards we remove the clipmask, else
-			* it will screw things up when run this loop again.
-			*/
-			gdk_gc_set_clip_mask(gc, clipmask);
-			gdk_gc_set_clip_origin(gc, 0, 0);
-			gdk_draw_drawable(pixmap, gc, colorStamp, 0, 0, 0, 0, -1, -1);
-			gdk_gc_set_clip_mask(gc, NULL);
-		}
-	}
-
-	/* Render the selection group to the top of the output */
-	if (selectionInfo && selectionInfo->selectedNodeArray
-	&& (selection_length (selectionInfo) != 0)) {
-		if (!selectionColor->pixel)
-	 		gdk_colormap_alloc_color(gdk_colormap_get_system(), selectionColor, FALSE, TRUE);
-
-		gdk_gc_set_foreground(gc, selectionColor);
-		gdk_gc_set_function(gc, GDK_COPY);
-		gdk_draw_rectangle(colorStamp, gc, TRUE, 0, 0, -1, -1);
-
-		gerbv_selection_item_t sItem;
-		gerbv_fileinfo_t *file;
-		int j;
-		guint k;
-
-		for (j = gerbvProject->last_loaded; j >= 0; j--) {
-			file = gerbvProject->file[j]; 
-			if (!file || (!gerbvProject->show_invisible_selection && !file->isVisible))
-				continue;
-
-			for (k = 0; k < selection_length (selectionInfo); k++) {
-				sItem = selection_get_item_by_index (selectionInfo, k);
-
-				if (file->image != sItem.image)
-					continue;
-
-				/* Have selected image(s) on this layer, draw it */
-				draw_gdk_image_to_pixmap(&clipmask, file->image,
-					renderInfo->scaleFactorX,
-					-(renderInfo->lowerLeftX * renderInfo->scaleFactorX),
-					(renderInfo->lowerLeftY * renderInfo->scaleFactorY) + renderInfo->displayHeight,
-					DRAW_SELECTIONS, selectionInfo,
-					renderInfo, file->transform);
-
-				gdk_gc_set_clip_mask(gc, clipmask);
-				gdk_gc_set_clip_origin(gc, 0, 0);
-				gdk_draw_drawable(pixmap, gc, colorStamp, 0, 0, 0, 0, -1, -1);
-				gdk_gc_set_clip_mask(gc, NULL);
-
-				break;
-			}
-		}
-	}
-
-	gdk_pixmap_unref(colorStamp);
-	gdk_pixmap_unref(clipmask);
-	gdk_gc_unref(gc);
+gerbv_render_to_pixmap_using_gdk(
+    gerbv_project_t* gerbvProject, GdkPixmap* pixmap, gerbv_render_info_t* renderInfo,
+    gerbv_selection_info_t* selectionInfo, GdkColor* selectionColor
+) {
+    GdkGC*     gc = gdk_gc_new(pixmap);
+    GdkPixmap *colorStamp, *clipmask;
+    int        i;
+
+    /*
+     * Remove old pixmap, allocate a new one, draw the background.
+     */
+    if (!gerbvProject->background.pixel)
+        gdk_colormap_alloc_color(gdk_colormap_get_system(), &gerbvProject->background, FALSE, TRUE);
+    gdk_gc_set_foreground(gc, &gerbvProject->background);
+    gdk_draw_rectangle(pixmap, gc, TRUE, 0, 0, -1, -1);
+
+    /*
+     * Allocate the pixmap and the clipmask (a one pixel pixmap)
+     */
+    colorStamp = gdk_pixmap_new(pixmap, renderInfo->displayWidth, renderInfo->displayHeight, -1);
+    clipmask   = gdk_pixmap_new(NULL, renderInfo->displayWidth, renderInfo->displayHeight, 1);
+
+    /*
+     * This now allows drawing several layers on top of each other.
+     * Higher layer numbers have higher priority in the Z-order.
+     */
+    for (i = gerbvProject->last_loaded; i >= 0; i--) {
+        if (gerbvProject->file[i] && gerbvProject->file[i]->isVisible) {
+            /*
+             * Fill up image with all the foreground color. Excess pixels
+             * will be removed by clipmask.
+             */
+            if (!gerbvProject->file[i]->color.pixel)
+                gdk_colormap_alloc_color(gdk_colormap_get_system(), &gerbvProject->file[i]->color, FALSE, TRUE);
+            gdk_gc_set_foreground(gc, &gerbvProject->file[i]->color);
+
+            /* switch back to regular draw function for the initial
+               bitmap clear */
+            gdk_gc_set_function(gc, GDK_COPY);
+            gdk_draw_rectangle(colorStamp, gc, TRUE, 0, 0, -1, -1);
+
+            if (renderInfo->renderType == GERBV_RENDER_TYPE_GDK) {
+                gdk_gc_set_function(gc, GDK_COPY);
+            } else if (renderInfo->renderType == GERBV_RENDER_TYPE_GDK_XOR) {
+                gdk_gc_set_function(gc, GDK_XOR);
+            }
+            /*
+             * Translation is to get it inside the allocated pixmap,
+             * which is not always centered perfectly for GTK/X.
+             */
+            dprintf("  .... calling image2pixmap on image %d...\n", i);
+            // Dirty scaling solution when using GDK; simply use scaling factor for x-axis, ignore y-axis
+            draw_gdk_image_to_pixmap(
+                &clipmask, gerbvProject->file[i]->image, renderInfo->scaleFactorX,
+                -(renderInfo->lowerLeftX * renderInfo->scaleFactorX),
+                (renderInfo->lowerLeftY * renderInfo->scaleFactorY) + renderInfo->displayHeight, DRAW_IMAGE, NULL,
+                renderInfo, gerbvProject->file[i]->transform
+            );
+
+            /*
+             * Set clipmask and draw the clipped out image onto the
+             * screen pixmap. Afterwards we remove the clipmask, else
+             * it will screw things up when run this loop again.
+             */
+            gdk_gc_set_clip_mask(gc, clipmask);
+            gdk_gc_set_clip_origin(gc, 0, 0);
+            gdk_draw_drawable(pixmap, gc, colorStamp, 0, 0, 0, 0, -1, -1);
+            gdk_gc_set_clip_mask(gc, NULL);
+        }
+    }
+
+    /* Render the selection group to the top of the output */
+    if (selectionInfo && selectionInfo->selectedNodeArray && (selection_length(selectionInfo) != 0)) {
+        if (!selectionColor->pixel)
+            gdk_colormap_alloc_color(gdk_colormap_get_system(), selectionColor, FALSE, TRUE);
+
+        gdk_gc_set_foreground(gc, selectionColor);
+        gdk_gc_set_function(gc, GDK_COPY);
+        gdk_draw_rectangle(colorStamp, gc, TRUE, 0, 0, -1, -1);
+
+        gerbv_selection_item_t sItem;
+        gerbv_fileinfo_t*      file;
+        int                    j;
+        guint                  k;
+
+        for (j = gerbvProject->last_loaded; j >= 0; j--) {
+            file = gerbvProject->file[j];
+            if (!file || (!gerbvProject->show_invisible_selection && !file->isVisible))
+                continue;
+
+            for (k = 0; k < selection_length(selectionInfo); k++) {
+                sItem = selection_get_item_by_index(selectionInfo, k);
+
+                if (file->image != sItem.image)
+                    continue;
+
+                /* Have selected image(s) on this layer, draw it */
+                draw_gdk_image_to_pixmap(
+                    &clipmask, file->image, renderInfo->scaleFactorX,
+                    -(renderInfo->lowerLeftX * renderInfo->scaleFactorX),
+                    (renderInfo->lowerLeftY * renderInfo->scaleFactorY) + renderInfo->displayHeight, DRAW_SELECTIONS,
+                    selectionInfo, renderInfo, file->transform
+                );
+
+                gdk_gc_set_clip_mask(gc, clipmask);
+                gdk_gc_set_clip_origin(gc, 0, 0);
+                gdk_draw_drawable(pixmap, gc, colorStamp, 0, 0, 0, 0, -1, -1);
+                gdk_gc_set_clip_mask(gc, NULL);
+
+                break;
+            }
+        }
+    }
+
+    gdk_pixmap_unref(colorStamp);
+    gdk_pixmap_unref(clipmask);
+    gdk_gc_unref(gc);
 }
 
 /* ------------------------------------------------------------------ */
 void
-gerbv_render_all_layers_to_cairo_target_for_vector_output (
-		gerbv_project_t *gerbvProject, cairo_t *cr,
-		gerbv_render_info_t *renderInfo)
-{
-	GdkColor *bg = &gerbvProject->background;
-	int i;
-	double r, g, b;
-
-	gerbv_render_cairo_set_scale_and_translation (cr, renderInfo);
-
-	/* Fill the background with the appropriate not white and not black
-	 * color for backward culpability. */ 
-	if ((bg->red != 0xffff || bg->green != 0xffff || bg->blue != 0xffff)
-	 && (bg->red != 0x0000 || bg->green != 0x0000 || bg->blue != 0x0000)) {
-		r = (double) bg->red/G_MAXUINT16;
-		g = (double) bg->green/G_MAXUINT16;
-		b = (double) bg->blue/G_MAXUINT16;
-		cairo_set_source_rgba (cr, r, g, b, 1);
-		cairo_paint (cr);
-
-		/* Set cairo user data with background color information, to be
-		 * used for clear color. */
-		cairo_set_user_data (cr, (cairo_user_data_key_t *)0, &r, NULL);
-		cairo_set_user_data (cr, (cairo_user_data_key_t *)1, &g, NULL);
-		cairo_set_user_data (cr, (cairo_user_data_key_t *)2, &b, NULL);
-	}
-
-	for (i = gerbvProject->last_loaded; i >= 0; i--) {
-		if (gerbvProject->file[i] && gerbvProject->file[i]->isVisible) {
-			gerbv_render_layer_to_cairo_target_without_transforming(
-					cr, gerbvProject->file[i],
-					renderInfo, FALSE);
-		}
-	}
+gerbv_render_all_layers_to_cairo_target_for_vector_output(
+    gerbv_project_t* gerbvProject, cairo_t* cr, gerbv_render_info_t* renderInfo
+) {
+    GdkColor* bg = &gerbvProject->background;
+    int       i;
+    double    r, g, b;
+
+    gerbv_render_cairo_set_scale_and_translation(cr, renderInfo);
+
+    /* Fill the background with the appropriate not white and not black
+     * color for backward culpability. */
+    if ((bg->red != 0xffff || bg->green != 0xffff || bg->blue != 0xffff)
+        && (bg->red != 0x0000 || bg->green != 0x0000 || bg->blue != 0x0000)) {
+        r = (double)bg->red / G_MAXUINT16;
+        g = (double)bg->green / G_MAXUINT16;
+        b = (double)bg->blue / G_MAXUINT16;
+        cairo_set_source_rgba(cr, r, g, b, 1);
+        cairo_paint(cr);
+
+        /* Set cairo user data with background color information, to be
+         * used for clear color. */
+        cairo_set_user_data(cr, (cairo_user_data_key_t*)0, &r, NULL);
+        cairo_set_user_data(cr, (cairo_user_data_key_t*)1, &g, NULL);
+        cairo_set_user_data(cr, (cairo_user_data_key_t*)2, &b, NULL);
+    }
+
+    for (i = gerbvProject->last_loaded; i >= 0; i--) {
+        if (gerbvProject->file[i] && gerbvProject->file[i]->isVisible) {
+            gerbv_render_layer_to_cairo_target_without_transforming(cr, gerbvProject->file[i], renderInfo, FALSE);
+        }
+    }
 }
 
 /* ------------------------------------------------------------------ */
 void
-gerbv_render_all_layers_to_cairo_target (gerbv_project_t *gerbvProject,
-		cairo_t *cr, gerbv_render_info_t *renderInfo)
-{
-	int i;
-
-	/* Fill the background with the appropriate color. */
-	cairo_set_source_rgba (cr,
-			(double) gerbvProject->background.red/G_MAXUINT16,
-			(double) gerbvProject->background.green/G_MAXUINT16,
-			(double) gerbvProject->background.blue/G_MAXUINT16, 1);
-	cairo_paint (cr);
-
-	for (i = gerbvProject->last_loaded; i >= 0; i--) {
-		if (gerbvProject->file[i] && gerbvProject->file[i]->isVisible) {
-			cairo_push_group (cr);
-			gerbv_render_layer_to_cairo_target (cr,
-					gerbvProject->file[i], renderInfo);
-			cairo_pop_group_to_source (cr);
-			cairo_paint_with_alpha (cr, (double)
-					gerbvProject->file[i]->alpha/G_MAXUINT16);
-		}
-	}
+gerbv_render_all_layers_to_cairo_target(gerbv_project_t* gerbvProject, cairo_t* cr, gerbv_render_info_t* renderInfo) {
+    int i;
+
+    /* Fill the background with the appropriate color. */
+    cairo_set_source_rgba(
+        cr, (double)gerbvProject->background.red / G_MAXUINT16, (double)gerbvProject->background.green / G_MAXUINT16,
+        (double)gerbvProject->background.blue / G_MAXUINT16, 1
+    );
+    cairo_paint(cr);
+
+    for (i = gerbvProject->last_loaded; i >= 0; i--) {
+        if (gerbvProject->file[i] && gerbvProject->file[i]->isVisible) {
+            cairo_push_group(cr);
+            gerbv_render_layer_to_cairo_target(cr, gerbvProject->file[i], renderInfo);
+            cairo_pop_group_to_source(cr);
+            cairo_paint_with_alpha(cr, (double)gerbvProject->file[i]->alpha / G_MAXUINT16);
+        }
+    }
 }
 
 /* ------------------------------------------------------------------ */
 void
-gerbv_render_layer_to_cairo_target (cairo_t *cr, gerbv_fileinfo_t *fileInfo,
-						gerbv_render_info_t *renderInfo) {
-	gerbv_render_cairo_set_scale_and_translation(cr, renderInfo);
-	gerbv_render_layer_to_cairo_target_without_transforming(cr, fileInfo, renderInfo, TRUE);
+gerbv_render_layer_to_cairo_target(cairo_t* cr, gerbv_fileinfo_t* fileInfo, gerbv_render_info_t* renderInfo) {
+    gerbv_render_cairo_set_scale_and_translation(cr, renderInfo);
+    gerbv_render_layer_to_cairo_target_without_transforming(cr, fileInfo, renderInfo, TRUE);
 }
 
 /* ------------------------------------------------------------------ */
 void
-gerbv_render_cairo_set_scale_and_translation(cairo_t *cr, gerbv_render_info_t *renderInfo){
-	gdouble translateX, translateY;
-	
-	translateX = (renderInfo->lowerLeftX * renderInfo->scaleFactorX);
-	translateY = (renderInfo->lowerLeftY * renderInfo->scaleFactorY);
-	
-	/* renderTypes 0 and 1 use GDK rendering, so we shouldn't have made it
-	   this far */
-	if (renderInfo->renderType == GERBV_RENDER_TYPE_CAIRO_NORMAL) {
-		cairo_set_tolerance (cr, 1.0);
-		cairo_set_antialias (cr, CAIRO_ANTIALIAS_NONE);
-	}
-	else if (renderInfo->renderType == GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY) {
-		cairo_set_tolerance (cr, 0.1);
-		cairo_set_antialias (cr, CAIRO_ANTIALIAS_DEFAULT);
-	}
-
-	/* translate the draw area before drawing.  We must translate the whole
-	   drawing down an additional displayHeight to account for the negative
-	   y flip done later */
-	cairo_translate (cr, -translateX, translateY + renderInfo->displayHeight);
-	/* scale the drawing by the specified scale factor (inverting y since
-		cairo y axis points down) */
-	cairo_scale (cr, renderInfo->scaleFactorX, -renderInfo->scaleFactorY);
+gerbv_render_cairo_set_scale_and_translation(cairo_t* cr, gerbv_render_info_t* renderInfo) {
+    gdouble translateX, translateY;
+
+    translateX = (renderInfo->lowerLeftX * renderInfo->scaleFactorX);
+    translateY = (renderInfo->lowerLeftY * renderInfo->scaleFactorY);
+
+    /* renderTypes 0 and 1 use GDK rendering, so we shouldn't have made it
+       this far */
+    if (renderInfo->renderType == GERBV_RENDER_TYPE_CAIRO_NORMAL) {
+        cairo_set_tolerance(cr, 1.0);
+        cairo_set_antialias(cr, CAIRO_ANTIALIAS_NONE);
+    } else if (renderInfo->renderType == GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY) {
+        cairo_set_tolerance(cr, 0.1);
+        cairo_set_antialias(cr, CAIRO_ANTIALIAS_DEFAULT);
+    }
+
+    /* translate the draw area before drawing.  We must translate the whole
+       drawing down an additional displayHeight to account for the negative
+       y flip done later */
+    cairo_translate(cr, -translateX, translateY + renderInfo->displayHeight);
+    /* scale the drawing by the specified scale factor (inverting y since
+        cairo y axis points down) */
+    cairo_scale(cr, renderInfo->scaleFactorX, -renderInfo->scaleFactorY);
 }
 
 /* ------------------------------------------------------------------ */
 void
-gerbv_render_layer_to_cairo_target_without_transforming(cairo_t *cr, gerbv_fileinfo_t *fileInfo, gerbv_render_info_t *renderInfo, gboolean pixelOutput) {
-	cairo_set_source_rgba (cr, (double) fileInfo->color.red/G_MAXUINT16,
-		(double) fileInfo->color.green/G_MAXUINT16,
-		(double) fileInfo->color.blue/G_MAXUINT16, 1);
-	
-	/* translate, rotate, and modify the image based on the layer-specific transformation struct */
-	cairo_save (cr);
-	
-	draw_image_to_cairo_target (cr, fileInfo->image,
-		1.0/MAX(renderInfo->scaleFactorX, renderInfo->scaleFactorY), DRAW_IMAGE, NULL,
-		renderInfo, TRUE, fileInfo->transform, pixelOutput);
-	cairo_restore (cr);
+gerbv_render_layer_to_cairo_target_without_transforming(
+    cairo_t* cr, gerbv_fileinfo_t* fileInfo, gerbv_render_info_t* renderInfo, gboolean pixelOutput
+) {
+    cairo_set_source_rgba(
+        cr, (double)fileInfo->color.red / G_MAXUINT16, (double)fileInfo->color.green / G_MAXUINT16,
+        (double)fileInfo->color.blue / G_MAXUINT16, 1
+    );
+
+    /* translate, rotate, and modify the image based on the layer-specific transformation struct */
+    cairo_save(cr);
+
+    draw_image_to_cairo_target(
+        cr, fileInfo->image, 1.0 / MAX(renderInfo->scaleFactorX, renderInfo->scaleFactorY), DRAW_IMAGE, NULL,
+        renderInfo, TRUE, fileInfo->transform, pixelOutput
+    );
+    cairo_restore(cr);
 }
 
 void
-gerbv_attribute_destroy_HID_attribute (gerbv_HID_Attribute *attributeList, int n_attr)
-{
-  int i;
-
-  /* free the string attributes */
-  for (i = 0 ; i < n_attr ; i++) {
-    if ( (attributeList[i].type == HID_String ||
-	  attributeList[i].type == HID_Label) &&
-	attributeList[i].default_val.str_value != NULL) {
-      free (attributeList[i].default_val.str_value);
+gerbv_attribute_destroy_HID_attribute(gerbv_HID_Attribute* attributeList, int n_attr) {
+    int i;
+
+    /* free the string attributes */
+    for (i = 0; i < n_attr; i++) {
+        if ((attributeList[i].type == HID_String || attributeList[i].type == HID_Label)
+            && attributeList[i].default_val.str_value != NULL) {
+            free(attributeList[i].default_val.str_value);
+        }
     }
-  }
 
-  /* and free the attribute list */
-  if (attributeList != NULL) {
-    free (attributeList);
-  }
+    /* and free the attribute list */
+    if (attributeList != NULL) {
+        free(attributeList);
+    }
 }
 
-
 /* allocate memory and make a copy of an attribute list */
-gerbv_HID_Attribute *
-gerbv_attribute_dup (gerbv_HID_Attribute *attributeList, int n_attr)
-{
-  gerbv_HID_Attribute *nl;
-  int i;
-
-  nl = (gerbv_HID_Attribute *) malloc (n_attr * sizeof (gerbv_HID_Attribute));
-  if (nl == NULL) {
-    fprintf (stderr, "malloc failed in %s()\n", __FUNCTION__);
-    exit (1);
-  }
-
-  /* copy the attribute list being sure to strdup the strings */
-  for (i = 0 ; i < n_attr ; i++) {
-
-    if (attributeList[i].type == HID_String ||
-	attributeList[i].type == HID_Label) {
-
-      if (attributeList[i].default_val.str_value != NULL) {
-	nl[i].default_val.str_value = strdup (attributeList[i].default_val.str_value);
-      } else {
-	nl[i].default_val.str_value = NULL;
-      }
+gerbv_HID_Attribute*
+gerbv_attribute_dup(gerbv_HID_Attribute* attributeList, int n_attr) {
+    gerbv_HID_Attribute* nl;
+    int                  i;
+
+    nl = (gerbv_HID_Attribute*)malloc(n_attr * sizeof(gerbv_HID_Attribute));
+    if (nl == NULL) {
+        fprintf(stderr, "malloc failed in %s()\n", __FUNCTION__);
+        exit(1);
+    }
 
-    } else {
-      nl[i] = attributeList[i];
+    /* copy the attribute list being sure to strdup the strings */
+    for (i = 0; i < n_attr; i++) {
+
+        if (attributeList[i].type == HID_String || attributeList[i].type == HID_Label) {
+
+            if (attributeList[i].default_val.str_value != NULL) {
+                nl[i].default_val.str_value = strdup(attributeList[i].default_val.str_value);
+            } else {
+                nl[i].default_val.str_value = NULL;
+            }
+
+        } else {
+            nl[i] = attributeList[i];
+        }
     }
-  }
 
-  return nl;
+    return nl;
 }
 
-gerbv_fileinfo_t *
-gerbv_get_fileinfo_for_image(const gerbv_image_t *image,
-		const gerbv_project_t *project)
-{
-	int i;
+gerbv_fileinfo_t*
+gerbv_get_fileinfo_for_image(const gerbv_image_t* image, const gerbv_project_t* project) {
+    int i;
 
-	for (i = 0; i <= project->last_loaded; i++) {
-		if (project->file[i]->image == image)
-			return project->file[i];
-	}
+    for (i = 0; i <= project->last_loaded; i++) {
+        if (project->file[i]->image == image)
+            return project->file[i];
+    }
 
-	return NULL;	
+    return NULL;
 }
 
 inline void
-gerbv_rotate_coord(double *x, double *y, double rad)
-{
-	double x0 = *x;
+gerbv_rotate_coord(double* x, double* y, double rad) {
+    double x0 = *x;
 
-	*x = x0*cos(rad) - *y*sin(rad);
-	*y = x0*sin(rad) + *y*cos(rad);
+    *x = x0 * cos(rad) - *y * sin(rad);
+    *y = x0 * sin(rad) + *y * cos(rad);
 }
 
 void
-gerbv_transform_coord(double *x, double *y,
-			const gerbv_user_transformation_t *trans)
-{
+gerbv_transform_coord(double* x, double* y, const gerbv_user_transformation_t* trans) {
 
-	*x = trans->scaleX * *x;
-	*y = trans->scaleY * *y;
+    *x = trans->scaleX * *x;
+    *y = trans->scaleY * *y;
 
-	gerbv_rotate_coord(x, y, trans->rotation);
+    gerbv_rotate_coord(x, y, trans->rotation);
 
-	if (trans->mirrorAroundY)
-		*x = -*x;
+    if (trans->mirrorAroundY)
+        *x = -*x;
 
-	if (trans->mirrorAroundX)
-		*y = -*y;
+    if (trans->mirrorAroundX)
+        *y = -*y;
 
-	*x += trans->translateX;
-	*y += trans->translateY;
+    *x += trans->translateX;
+    *y += trans->translateY;
 }
 
 int
-gerbv_transform_coord_for_image(double *x, double *y,
-		const gerbv_image_t *image, const gerbv_project_t *project)
-{
-	gerbv_fileinfo_t *fileinfo =
-		gerbv_get_fileinfo_for_image(image, project);
+gerbv_transform_coord_for_image(double* x, double* y, const gerbv_image_t* image, const gerbv_project_t* project) {
+    gerbv_fileinfo_t* fileinfo = gerbv_get_fileinfo_for_image(image, project);
 
-	if (fileinfo == NULL) {
-		dprintf("%s(): NULL fileinfo\n", __func__);
-		return -1;
-	}
+    if (fileinfo == NULL) {
+        dprintf("%s(): NULL fileinfo\n", __func__);
+        return -1;
+    }
 
-	gerbv_transform_coord(x, y, &fileinfo->transform);
+    gerbv_transform_coord(x, y, &fileinfo->transform);
 
-	return 0;
+    return 0;
 }
 
 gboolean
-gerbv_endswith(const char *path, const char *ext) {
+gerbv_endswith(const char* path, const char* ext) {
     int plen = strlen(path);
     int elen = strlen(ext);
-    if ( plen < elen ) return FALSE;                    // false if string too short to check
-    return (strcmp(path+plen-elen, ext) == 0) ? TRUE    // true if last chars match extension
-                                              : FALSE;
+    if (plen < elen)
+        return FALSE;                                     // false if string too short to check
+    return (strcmp(path + plen - elen, ext) == 0) ? TRUE  // true if last chars match extension
+                                                  : FALSE;
 }
diff --git a/src/gerbv.h b/src/gerbv.h
index 3ba4ba6..7b69629 100644
--- a/src/gerbv.h
+++ b/src/gerbv.h
@@ -66,7 +66,7 @@ For help with using the standalone Gerbv software, please refer to the man page
 #define __GERBV_H__
 
 #ifdef HAVE_CONFIG_H
-# include "config.h"
+#include "config.h"
 #endif
 
 #include <glib.h>
@@ -75,7 +75,7 @@ For help with using the standalone Gerbv software, please refer to the man page
 #include <gdk/gdkkeysyms.h>
 
 #ifndef RENDER_USING_GDK
-# include <cairo.h>
+#include <cairo.h>
 #endif
 
 #if defined(__cplusplus)
@@ -92,365 +92,389 @@ extern "C" {
  * start/end point gives
  */
 #define APERTURE_PARAMETERS_MAX 10006
-#define GERBV_SCALE_MIN 10
-#define GERBV_SCALE_MAX 40000
-#define MAX_ERRMSGLEN 25
-#define MAX_COORDLEN 28
-#define MAX_DISTLEN 180
-#define MAX_STATUSMSGLEN (MAX_ERRMSGLEN+MAX_COORDLEN+MAX_DISTLEN)
+#define GERBV_SCALE_MIN         10
+#define GERBV_SCALE_MAX         40000
+#define MAX_ERRMSGLEN           25
+#define MAX_COORDLEN            28
+#define MAX_DISTLEN             180
+#define MAX_STATUSMSGLEN        (MAX_ERRMSGLEN + MAX_COORDLEN + MAX_DISTLEN)
 
 /*
  * Files only have a limited precision in their data, so when interpreting
  * layer rotations or linear size that have been read from a project file, we
  * have to tolerate a certain amount of error.
  */
-#define GERBV_PRECISION_ANGLE_RAD	1e-6
-#define GERBV_PRECISION_LINEAR_INCH	1e-6
+#define GERBV_PRECISION_ANGLE_RAD   1e-6
+#define GERBV_PRECISION_LINEAR_INCH 1e-6
 
 /* Macros to convert between unscaled gerber coordinates and other units */
 /* XXX NOTE: Currently unscaled units are assumed as inch, this is not
    XXX necessarily true for all files */
-#define COORD2INS(c) (c)
+#define COORD2INS(c)  (c)
 #define COORD2MILS(c) ((c)*1000.0)
-#define COORD2MMS(c) ((c)*25.4)
-
-#define DEG2RAD(d) ((d)*M_PI/180.0)
-#define RAD2DEG(r) ((r)*180.0*M_1_PI)
-
-#define GERB_FATAL_ERROR(...) g_log(NULL, G_LOG_LEVEL_ERROR, __VA_ARGS__)
-#define GERB_COMPILE_ERROR(...)  g_log(NULL, G_LOG_LEVEL_CRITICAL, __VA_ARGS__)
-#define GERB_COMPILE_WARNING(...)  g_log(NULL, G_LOG_LEVEL_WARNING, __VA_ARGS__)
-#define GERB_MESSAGE(...)  g_log(NULL, G_LOG_LEVEL_MESSAGE, __VA_ARGS__)
-
-/*! The aperture macro commands */  
-typedef enum {GERBV_OPCODE_NOP, /*!< no operation */
-	      GERBV_OPCODE_PUSH, /*!< push the instruction onto the stack */
-	      GERBV_OPCODE_PPUSH, /*!< push parameter onto stack */ 
-	      GERBV_OPCODE_PPOP, /*!< pop parameter from stack */ 
-	      GERBV_OPCODE_ADD, /*!< mathmatical add operation */
-	      GERBV_OPCODE_SUB, /*!< mathmatical subtract operation */
-	      GERBV_OPCODE_MUL, /*!< mathmatical multiply operation */
-	      GERBV_OPCODE_DIV, /*!< mathmatical divide operation */
-	      GERBV_OPCODE_PRIM /*!< draw macro primative */
+#define COORD2MMS(c)  ((c)*25.4)
+
+#define DEG2RAD(d) ((d)*M_PI / 180.0)
+#define RAD2DEG(r) ((r)*180.0 * M_1_PI)
+
+#define GERB_FATAL_ERROR(...)     g_log(NULL, G_LOG_LEVEL_ERROR, __VA_ARGS__)
+#define GERB_COMPILE_ERROR(...)   g_log(NULL, G_LOG_LEVEL_CRITICAL, __VA_ARGS__)
+#define GERB_COMPILE_WARNING(...) g_log(NULL, G_LOG_LEVEL_WARNING, __VA_ARGS__)
+#define GERB_MESSAGE(...)         g_log(NULL, G_LOG_LEVEL_MESSAGE, __VA_ARGS__)
+
+/*! The aperture macro commands */
+typedef enum {
+    GERBV_OPCODE_NOP,   /*!< no operation */
+    GERBV_OPCODE_PUSH,  /*!< push the instruction onto the stack */
+    GERBV_OPCODE_PPUSH, /*!< push parameter onto stack */
+    GERBV_OPCODE_PPOP,  /*!< pop parameter from stack */
+    GERBV_OPCODE_ADD,   /*!< mathmatical add operation */
+    GERBV_OPCODE_SUB,   /*!< mathmatical subtract operation */
+    GERBV_OPCODE_MUL,   /*!< mathmatical multiply operation */
+    GERBV_OPCODE_DIV,   /*!< mathmatical divide operation */
+    GERBV_OPCODE_PRIM   /*!< draw macro primative */
 } gerbv_opcodes_t;
 
-/*! The different message types used in libgerbv */   
-typedef enum {GERBV_MESSAGE_FATAL, /*!< processing cannot continue */
-		GERBV_MESSAGE_ERROR, /*!< something went wrong, but processing can still continue */
-		GERBV_MESSAGE_WARNING, /*!< something was encountered that may provide the wrong output */
-		GERBV_MESSAGE_NOTE /*!< an irregularity was encountered, but needs no intervention */
+/*! The different message types used in libgerbv */
+typedef enum {
+    GERBV_MESSAGE_FATAL,   /*!< processing cannot continue */
+    GERBV_MESSAGE_ERROR,   /*!< something went wrong, but processing can still continue */
+    GERBV_MESSAGE_WARNING, /*!< something was encountered that may provide the wrong output */
+    GERBV_MESSAGE_NOTE     /*!< an irregularity was encountered, but needs no intervention */
 } gerbv_message_type_t;
 
 /*! The different aperture types available.
  *  Please keep these in sync with the aperture names defined in
  *  gerbv_aperture_type_name() in gerbv.c */
 typedef enum {
-		GERBV_APTYPE_NONE, /*!< no aperture used */
-		GERBV_APTYPE_CIRCLE, /*!< a round aperture */
-		GERBV_APTYPE_RECTANGLE, /*!< a rectangular aperture */
-		GERBV_APTYPE_OVAL, /*!< an ovular (obround) aperture */
-		GERBV_APTYPE_POLYGON, /*!< a polygon aperture */
-		GERBV_APTYPE_MACRO, /*!< a RS274X macro */
-			GERBV_APTYPE_MACRO_CIRCLE, /*!< a RS274X circle macro */
-			GERBV_APTYPE_MACRO_OUTLINE, /*!< a RS274X outline macro */
-			GERBV_APTYPE_MACRO_POLYGON, /*!< a RS274X polygon macro */
-			GERBV_APTYPE_MACRO_MOIRE, /*!< a RS274X moire macro */
-			GERBV_APTYPE_MACRO_THERMAL, /*!< a RS274X thermal macro */
-			GERBV_APTYPE_MACRO_LINE20, /*!< a RS274X vector line (code 20) macro */
-			GERBV_APTYPE_MACRO_LINE21, /*!< a RS274X centered line (code 21) macro */
-			GERBV_APTYPE_MACRO_LINE22 /*!< a RS274X lower left line (code 22) macro */
+    GERBV_APTYPE_NONE,          /*!< no aperture used */
+    GERBV_APTYPE_CIRCLE,        /*!< a round aperture */
+    GERBV_APTYPE_RECTANGLE,     /*!< a rectangular aperture */
+    GERBV_APTYPE_OVAL,          /*!< an ovular (obround) aperture */
+    GERBV_APTYPE_POLYGON,       /*!< a polygon aperture */
+    GERBV_APTYPE_MACRO,         /*!< a RS274X macro */
+    GERBV_APTYPE_MACRO_CIRCLE,  /*!< a RS274X circle macro */
+    GERBV_APTYPE_MACRO_OUTLINE, /*!< a RS274X outline macro */
+    GERBV_APTYPE_MACRO_POLYGON, /*!< a RS274X polygon macro */
+    GERBV_APTYPE_MACRO_MOIRE,   /*!< a RS274X moire macro */
+    GERBV_APTYPE_MACRO_THERMAL, /*!< a RS274X thermal macro */
+    GERBV_APTYPE_MACRO_LINE20,  /*!< a RS274X vector line (code 20) macro */
+    GERBV_APTYPE_MACRO_LINE21,  /*!< a RS274X centered line (code 21) macro */
+    GERBV_APTYPE_MACRO_LINE22   /*!< a RS274X lower left line (code 22) macro */
 } gerbv_aperture_type_t;
 
-const char *gerbv_aperture_type_name(gerbv_aperture_type_t type);
+const char* gerbv_aperture_type_name(gerbv_aperture_type_t type);
 
 /*! The current state of the aperture drawing tool */
-typedef enum {GERBV_APERTURE_STATE_OFF, /*!< tool drawing is off, and nothing will be drawn */
-		GERBV_APERTURE_STATE_ON, /*!< tool drawing is on, and something will be drawn */
-		GERBV_APERTURE_STATE_FLASH /*!< tool is flashing, and will draw a single aperture */
+typedef enum {
+    GERBV_APERTURE_STATE_OFF,  /*!< tool drawing is off, and nothing will be drawn */
+    GERBV_APERTURE_STATE_ON,   /*!< tool drawing is on, and something will be drawn */
+    GERBV_APERTURE_STATE_FLASH /*!< tool is flashing, and will draw a single aperture */
 } gerbv_aperture_state_t;
 
 /*! The circle aperture macro parameter indexes */
 typedef enum {
-		CIRCLE_EXPOSURE,
-		CIRCLE_DIAMETER,
-		CIRCLE_CENTER_X,
-		CIRCLE_CENTER_Y,
+    CIRCLE_EXPOSURE,
+    CIRCLE_DIAMETER,
+    CIRCLE_CENTER_X,
+    CIRCLE_CENTER_Y,
 } gerbv_aptype_macro_circle_index_t;
 
 typedef enum {
-		OUTLINE_EXPOSURE,
-		OUTLINE_NUMBER_OF_POINTS,
-		OUTLINE_FIRST_X, /* x0 */
-		OUTLINE_FIRST_Y, /* y0 */
-		/* x1, y1, x2, y2, ..., rotation */
-		OUTLINE_ROTATION, /* Rotation index is correct if outline has
-				     no point except first */
+    OUTLINE_EXPOSURE,
+    OUTLINE_NUMBER_OF_POINTS,
+    OUTLINE_FIRST_X, /* x0 */
+    OUTLINE_FIRST_Y, /* y0 */
+    /* x1, y1, x2, y2, ..., rotation */
+    OUTLINE_ROTATION, /* Rotation index is correct if outline has
+                 no point except first */
 } gerbv_aptype_macro_outline_index_t;
 
 /* Point number is from 0 (first) to (including) OUTLINE_NUMBER_OF_POINTS */
-#define OUTLINE_X_IDX_OF_POINT(number) (2*(number) + OUTLINE_FIRST_X)
-#define OUTLINE_Y_IDX_OF_POINT(number) (2*(number) + OUTLINE_FIRST_Y)
-#define	OUTLINE_ROTATION_IDX(param_array) \
-			((int)param_array[OUTLINE_NUMBER_OF_POINTS]*2 + \
-			OUTLINE_ROTATION)
+#define OUTLINE_X_IDX_OF_POINT(number)    (2 * (number) + OUTLINE_FIRST_X)
+#define OUTLINE_Y_IDX_OF_POINT(number)    (2 * (number) + OUTLINE_FIRST_Y)
+#define OUTLINE_ROTATION_IDX(param_array) ((int)param_array[OUTLINE_NUMBER_OF_POINTS] * 2 + OUTLINE_ROTATION)
 
 typedef enum {
-		POLYGON_EXPOSURE,
-		POLYGON_NUMBER_OF_POINTS,
-		POLYGON_CENTER_X,
-		POLYGON_CENTER_Y,
-		POLYGON_DIAMETER,
-		POLYGON_ROTATION,
+    POLYGON_EXPOSURE,
+    POLYGON_NUMBER_OF_POINTS,
+    POLYGON_CENTER_X,
+    POLYGON_CENTER_Y,
+    POLYGON_DIAMETER,
+    POLYGON_ROTATION,
 } gerbv_aptype_macro_polygon_index_t;
 
 typedef enum {
-		MOIRE_CENTER_X,
-		MOIRE_CENTER_Y,
-		MOIRE_OUTSIDE_DIAMETER,
-		MOIRE_CIRCLE_THICKNESS,
-		MOIRE_GAP_WIDTH,
-		MOIRE_NUMBER_OF_CIRCLES,
-		MOIRE_CROSSHAIR_THICKNESS,
-		MOIRE_CROSSHAIR_LENGTH,
-		MOIRE_ROTATION,
+    MOIRE_CENTER_X,
+    MOIRE_CENTER_Y,
+    MOIRE_OUTSIDE_DIAMETER,
+    MOIRE_CIRCLE_THICKNESS,
+    MOIRE_GAP_WIDTH,
+    MOIRE_NUMBER_OF_CIRCLES,
+    MOIRE_CROSSHAIR_THICKNESS,
+    MOIRE_CROSSHAIR_LENGTH,
+    MOIRE_ROTATION,
 } gerbv_aptype_macro_moire_index_t;
 
 typedef enum {
-		THERMAL_CENTER_X,
-		THERMAL_CENTER_Y,
-		THERMAL_OUTSIDE_DIAMETER,
-		THERMAL_INSIDE_DIAMETER,
-		THERMAL_CROSSHAIR_THICKNESS,
-		THERMAL_ROTATION,
+    THERMAL_CENTER_X,
+    THERMAL_CENTER_Y,
+    THERMAL_OUTSIDE_DIAMETER,
+    THERMAL_INSIDE_DIAMETER,
+    THERMAL_CROSSHAIR_THICKNESS,
+    THERMAL_ROTATION,
 } gerbv_aptype_macro_thermal_index_t;
 
 /*! The vector line aperture macro parameter indexes */
 typedef enum {
-		LINE20_EXPOSURE,
-		LINE20_LINE_WIDTH,
-		LINE20_WIDTH = LINE20_LINE_WIDTH,	/* Unification alias */
-		LINE20_START_X,
-		LINE20_START_Y,
-		LINE20_END_X,
-		LINE20_END_Y,
-		LINE20_ROTATION,
+    LINE20_EXPOSURE,
+    LINE20_LINE_WIDTH,
+    LINE20_WIDTH = LINE20_LINE_WIDTH, /* Unification alias */
+    LINE20_START_X,
+    LINE20_START_Y,
+    LINE20_END_X,
+    LINE20_END_Y,
+    LINE20_ROTATION,
 } gerbv_aptype_macro_line20_index_t;
 
 /*! The centered line aperture macro parameter indexes */
 typedef enum {
-		LINE21_EXPOSURE,
-		LINE21_WIDTH,
-		LINE21_HEIGHT,
-		LINE21_CENTER_X,
-		LINE21_CENTER_Y,
-		LINE21_ROTATION,
+    LINE21_EXPOSURE,
+    LINE21_WIDTH,
+    LINE21_HEIGHT,
+    LINE21_CENTER_X,
+    LINE21_CENTER_Y,
+    LINE21_ROTATION,
 } gerbv_aptype_macro_line21_index_t;
 
 /*! The lower left line aperture macro parameter indexes */
 typedef enum {
-		LINE22_EXPOSURE,
-		LINE22_WIDTH,
-		LINE22_HEIGHT,
-		LINE22_LOWER_LEFT_X,
-		LINE22_LOWER_LEFT_Y,
-		LINE22_ROTATION,
+    LINE22_EXPOSURE,
+    LINE22_WIDTH,
+    LINE22_HEIGHT,
+    LINE22_LOWER_LEFT_X,
+    LINE22_LOWER_LEFT_Y,
+    LINE22_ROTATION,
 } gerbv_aptype_macro_line22_index_t;
 
-
 /*! The current unit used */
-typedef enum {GERBV_UNIT_INCH, /*!< inches */
-		GERBV_UNIT_MM, /*!< mm */
-		GERBV_UNIT_UNSPECIFIED /*!< use default units */
+typedef enum {
+    GERBV_UNIT_INCH,       /*!< inches */
+    GERBV_UNIT_MM,         /*!< mm */
+    GERBV_UNIT_UNSPECIFIED /*!< use default units */
 } gerbv_unit_t;
 
 /*! The different drawing polarities available */
-typedef enum {GERBV_POLARITY_POSITIVE, /*!< draw "positive", using the current layer's polarity */
-		GERBV_POLARITY_NEGATIVE, /*!< draw "negative", reversing the current layer's polarity */
-		GERBV_POLARITY_DARK, /*!< add to the current rendering */
-		GERBV_POLARITY_CLEAR /*!< subtract from the current rendering */
+typedef enum {
+    GERBV_POLARITY_POSITIVE, /*!< draw "positive", using the current layer's polarity */
+    GERBV_POLARITY_NEGATIVE, /*!< draw "negative", reversing the current layer's polarity */
+    GERBV_POLARITY_DARK,     /*!< add to the current rendering */
+    GERBV_POLARITY_CLEAR     /*!< subtract from the current rendering */
 } gerbv_polarity_t;
 
 /*! The decimal point parsing style used */
-typedef enum {GERBV_OMIT_ZEROS_LEADING, /*!< omit extra zeros before the decimal point */
-		GERBV_OMIT_ZEROS_TRAILING, /*!< omit extra zeros after the decimal point */
-		GERBV_OMIT_ZEROS_EXPLICIT, /*!< explicitly specify how many decimal places are used */
-		GERBV_OMIT_ZEROS_UNSPECIFIED /*!< use the default parsing style */
+typedef enum {
+    GERBV_OMIT_ZEROS_LEADING,    /*!< omit extra zeros before the decimal point */
+    GERBV_OMIT_ZEROS_TRAILING,   /*!< omit extra zeros after the decimal point */
+    GERBV_OMIT_ZEROS_EXPLICIT,   /*!< explicitly specify how many decimal places are used */
+    GERBV_OMIT_ZEROS_UNSPECIFIED /*!< use the default parsing style */
 } gerbv_omit_zeros_t;
 
 /*! The coordinate system used */
-typedef enum {GERBV_COORDINATE_ABSOLUTE, /*!< all coordinates are absolute from a common origin */
-		GERBV_COORDINATE_INCREMENTAL /*!< all coordinates are relative to the previous coordinate */
+typedef enum {
+    GERBV_COORDINATE_ABSOLUTE,   /*!< all coordinates are absolute from a common origin */
+    GERBV_COORDINATE_INCREMENTAL /*!< all coordinates are relative to the previous coordinate */
 } gerbv_coordinate_t;
 
 /*! The interpolation methods available.
  *  Please keep these in sync with the interpolation names defined in
  *  gerbv_interpolation_name() in gerbv.c */
-typedef enum {GERBV_INTERPOLATION_LINEARx1, /*!< draw a line */
-		GERBV_INTERPOLATION_LINEARx10, /*!< draw a line */
-		GERBV_INTERPOLATION_LINEARx01, /*!< draw a line */
-		GERBV_INTERPOLATION_LINEARx001, /*!< draw a line */
-		GERBV_INTERPOLATION_CW_CIRCULAR, /*!< draw an arc in the clockwise direction */
-		GERBV_INTERPOLATION_CCW_CIRCULAR, /*!< draw an arc in the counter-clockwise direction */
-		GERBV_INTERPOLATION_PAREA_START, /*!< start a polygon draw */
-		GERBV_INTERPOLATION_PAREA_END, /*!< end a polygon draw */
-		GERBV_INTERPOLATION_DELETED /*!< the net has been deleted by the user, and will not be drawn */
+typedef enum {
+    GERBV_INTERPOLATION_LINEARx1,     /*!< draw a line */
+    GERBV_INTERPOLATION_LINEARx10,    /*!< draw a line */
+    GERBV_INTERPOLATION_LINEARx01,    /*!< draw a line */
+    GERBV_INTERPOLATION_LINEARx001,   /*!< draw a line */
+    GERBV_INTERPOLATION_CW_CIRCULAR,  /*!< draw an arc in the clockwise direction */
+    GERBV_INTERPOLATION_CCW_CIRCULAR, /*!< draw an arc in the counter-clockwise direction */
+    GERBV_INTERPOLATION_PAREA_START,  /*!< start a polygon draw */
+    GERBV_INTERPOLATION_PAREA_END,    /*!< end a polygon draw */
+    GERBV_INTERPOLATION_DELETED       /*!< the net has been deleted by the user, and will not be drawn */
 } gerbv_interpolation_t;
 
 /* For backward compatibility */
-enum {GERBV_INTERPOLATION_x10 = GERBV_INTERPOLATION_LINEARx10};
+enum {
+    GERBV_INTERPOLATION_x10 = GERBV_INTERPOLATION_LINEARx10
+};
 
-const char *gerbv_interpolation_name(gerbv_interpolation_t interp);
+const char* gerbv_interpolation_name(gerbv_interpolation_t interp);
 
-typedef enum {GERBV_ENCODING_NONE,
-		GERBV_ENCODING_ASCII,
-		GERBV_ENCODING_EBCDIC,
-		GERBV_ENCODING_BCD,
-		GERBV_ENCODING_ISO_ASCII,
-		GERBV_ENCODING_EIA
+typedef enum {
+    GERBV_ENCODING_NONE,
+    GERBV_ENCODING_ASCII,
+    GERBV_ENCODING_EBCDIC,
+    GERBV_ENCODING_BCD,
+    GERBV_ENCODING_ISO_ASCII,
+    GERBV_ENCODING_EIA
 } gerbv_encoding_t;
 
 /*! The different layer types used */
 typedef enum {
-		GERBV_LAYERTYPE_RS274X, /*!< the file is a RS274X file */
-		GERBV_LAYERTYPE_DRILL, /*!< the file is an Excellon drill file */
-		GERBV_LAYERTYPE_PICKANDPLACE_TOP, /*!< the file is a CSV pick and place file, top side */
-		GERBV_LAYERTYPE_PICKANDPLACE_BOT, /*!< the file is a CSV pick and place file, bottom side */
+    GERBV_LAYERTYPE_RS274X,           /*!< the file is a RS274X file */
+    GERBV_LAYERTYPE_DRILL,            /*!< the file is an Excellon drill file */
+    GERBV_LAYERTYPE_PICKANDPLACE_TOP, /*!< the file is a CSV pick and place file, top side */
+    GERBV_LAYERTYPE_PICKANDPLACE_BOT, /*!< the file is a CSV pick and place file, bottom side */
 } gerbv_layertype_t;
 
-typedef enum {GERBV_KNOCKOUT_TYPE_NOKNOCKOUT,
-		GERBV_KNOCKOUT_TYPE_FIXEDKNOCK,
-		GERBV_KNOCKOUT_TYPE_BORDER
+typedef enum {
+    GERBV_KNOCKOUT_TYPE_NOKNOCKOUT,
+    GERBV_KNOCKOUT_TYPE_FIXEDKNOCK,
+    GERBV_KNOCKOUT_TYPE_BORDER
 } gerbv_knockout_type_t;
 
-typedef enum {GERBV_MIRROR_STATE_NOMIRROR,
-		GERBV_MIRROR_STATE_FLIPA,
-		GERBV_MIRROR_STATE_FLIPB,
-		GERBV_MIRROR_STATE_FLIPAB
+typedef enum {
+    GERBV_MIRROR_STATE_NOMIRROR,
+    GERBV_MIRROR_STATE_FLIPA,
+    GERBV_MIRROR_STATE_FLIPB,
+    GERBV_MIRROR_STATE_FLIPAB
 } gerbv_mirror_state_t;
 
-typedef enum {GERBV_AXIS_SELECT_NOSELECT,
-		GERBV_AXIS_SELECT_SWAPAB
+typedef enum {
+    GERBV_AXIS_SELECT_NOSELECT,
+    GERBV_AXIS_SELECT_SWAPAB
 } gerbv_axis_select_t;
 
-typedef enum {GERBV_JUSTIFY_NOJUSTIFY,
-		GERBV_JUSTIFY_LOWERLEFT,
-		GERBV_JUSTIFY_CENTERJUSTIFY
+typedef enum {
+    GERBV_JUSTIFY_NOJUSTIFY,
+    GERBV_JUSTIFY_LOWERLEFT,
+    GERBV_JUSTIFY_CENTERJUSTIFY
 } gerbv_image_justify_type_t;
 
 /*! The different selection modes available */
-typedef enum {	GERBV_SELECTION_POINT_CLICK = 1, /*!< the user clicked on a single point */
-		GERBV_SELECTION_DRAG_BOX /*!< the user dragged a box to encompass one or more objects */
+typedef enum {
+    GERBV_SELECTION_POINT_CLICK = 1, /*!< the user clicked on a single point */
+    GERBV_SELECTION_DRAG_BOX         /*!< the user dragged a box to encompass one or more objects */
 } gerbv_selection_t;
 
 enum draw_mode {
-	DRAW_IMAGE = 0,
-	DRAW_SELECTIONS,
-	FIND_SELECTIONS,
-	FIND_SELECTIONS_TOGGLE,
+    DRAW_IMAGE = 0,
+    DRAW_SELECTIONS,
+    FIND_SELECTIONS,
+    FIND_SELECTIONS_TOGGLE,
 };
 
 /*! The different rendering modes available to libgerbv */
-typedef enum {GERBV_RENDER_TYPE_GDK, /*!< render using normal GDK drawing functions */
-		GERBV_RENDER_TYPE_GDK_XOR, /*!< use the GDK_XOR mask to draw a pseudo-transparent scene */
-		GERBV_RENDER_TYPE_CAIRO_NORMAL, /*!< use the cairo library */
-		GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY, /*!< use the cairo library with the smoothest edges */
-		GERBV_RENDER_TYPE_MAX /*!< End-of-enum indicator */
+typedef enum {
+    GERBV_RENDER_TYPE_GDK,                /*!< render using normal GDK drawing functions */
+    GERBV_RENDER_TYPE_GDK_XOR,            /*!< use the GDK_XOR mask to draw a pseudo-transparent scene */
+    GERBV_RENDER_TYPE_CAIRO_NORMAL,       /*!< use the cairo library */
+    GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY, /*!< use the cairo library with the smoothest edges */
+    GERBV_RENDER_TYPE_MAX                 /*!< End-of-enum indicator */
 } gerbv_render_types_t;
 
-/* 
+/*
  * The following typedef's are taken directly from src/hid.h in the
  * pcb project.  The names are kept the same to make it easier to
  * compare to pcb's sources.
  */
-    
+
 /* Used for HID attributes (exporting and printing, mostly).
    HA_boolean uses int_value, HA_enum sets int_value to the index and
    str_value to the enumeration string.  HID_Label just shows the
    default str_value.  HID_Mixed is a real_value followed by an enum,
-   like 0.5in or 100mm. 
+   like 0.5in or 100mm.
 */
 typedef struct {
-    int int_value;
-    char *str_value;
+    int    int_value;
+    char*  str_value;
     double real_value;
 } gerbv_HID_Attr_Val;
 
 typedef struct {
-    char *name;
-    char *help_text;
-    enum
-	{ HID_Label, HID_Integer, HID_Real, HID_String,
-	  HID_Boolean, HID_Enum, HID_Mixed, HID_Path
-	} type;
-    int min_val, max_val;	/* for integer and real */
-    gerbv_HID_Attr_Val default_val;	/* Also actual value for global attributes.  */
-    const char **enumerations;
+    char* name;
+    char* help_text;
+
+    enum {
+        HID_Label,
+        HID_Integer,
+        HID_Real,
+        HID_String,
+        HID_Boolean,
+        HID_Enum,
+        HID_Mixed,
+        HID_Path
+    } type;
+
+    int                min_val, max_val; /* for integer and real */
+    gerbv_HID_Attr_Val default_val;      /* Also actual value for global attributes.  */
+    const char**       enumerations;
     /* If set, this is used for global attributes (i.e. those set
        statically with REGISTER_ATTRIBUTES below) instead of changing
        the default_val.  Note that a HID_Mixed attribute must specify a
        pointer to gerbv_HID_Attr_Val here, and HID_Boolean assumes this is
        "char *" so the value should be initialized to zero, and may be
        set to non-zero (not always one).  */
-    void *value;
-    int hash; /* for detecting changes. */
+    void* value;
+    int   hash; /* for detecting changes. */
 } gerbv_HID_Attribute;
+
 /* end of HID attributes from PCB */
 
-/*! A linked list of errors found in the files */   
+/*! A linked list of errors found in the files */
 typedef struct error_list {
-    int layer;
-    gchar *error_text;
+    int                  layer;
+    gchar*               error_text;
     gerbv_message_type_t type;
-    struct error_list *next;
+    struct error_list*   next;
 } gerbv_error_list_t;
 
 typedef struct instruction {
     gerbv_opcodes_t opcode;
+
     union {
-	int ival;
-	float fval;
+        int   ival;
+        float fval;
     } data;
-    struct instruction *next;
+    struct instruction* next;
 } gerbv_instruction_t;
 
 typedef struct amacro {
-    gchar *name;
-    gerbv_instruction_t *program;
-    unsigned int nuf_push;  /* Nuf pushes in program to estimate stack size */
-    struct amacro *next;
+    gchar*               name;
+    gerbv_instruction_t* program;
+    unsigned int         nuf_push; /* Nuf pushes in program to estimate stack size */
+    struct amacro*       next;
 } gerbv_amacro_t;
 
 typedef struct gerbv_simplified_amacro {
-    gerbv_aperture_type_t type;
-    double parameter[APERTURE_PARAMETERS_MAX];
-    struct gerbv_simplified_amacro *next;
+    gerbv_aperture_type_t           type;
+    double                          parameter[APERTURE_PARAMETERS_MAX];
+    struct gerbv_simplified_amacro* next;
 } gerbv_simplified_amacro_t;
 
 typedef struct gerbv_aperture {
-    gerbv_aperture_type_t type;
-    gerbv_amacro_t *amacro;
-    gerbv_simplified_amacro_t *simplified;
-    double parameter[APERTURE_PARAMETERS_MAX];
-    int nuf_parameters;
-    gerbv_unit_t unit;
+    gerbv_aperture_type_t      type;
+    gerbv_amacro_t*            amacro;
+    gerbv_simplified_amacro_t* simplified;
+    double                     parameter[APERTURE_PARAMETERS_MAX];
+    int                        nuf_parameters;
+    gerbv_unit_t               unit;
 } gerbv_aperture_t;
 
-/* the gerb_aperture_list is used to keep track of 
+/* the gerb_aperture_list is used to keep track of
  * apertures used in stats reporting */
 typedef struct gerbv_aperture_list {
-    int number;
-    int layer;
-    int count;
-    gerbv_aperture_type_t type;
-    double parameter[5];
-    struct gerbv_aperture_list *next;
+    int                         number;
+    int                         layer;
+    int                         count;
+    gerbv_aperture_type_t       type;
+    double                      parameter[5];
+    struct gerbv_aperture_list* next;
 } gerbv_aperture_list_t;
 
 /*! Contains statistics on the various codes used in a RS274X file */
 typedef struct {
-    gerbv_error_list_t *error_list;
-    gerbv_aperture_list_t *aperture_list;
-    gerbv_aperture_list_t *D_code_list;
+    gerbv_error_list_t*    error_list;
+    gerbv_aperture_list_t* aperture_list;
+    gerbv_aperture_list_t* D_code_list;
 
     int layer_count;
     int G0;
@@ -476,7 +500,7 @@ typedef struct {
     int D1;
     int D2;
     int D3;
-/*    GHashTable *D_user_defined; */
+    /*    GHashTable *D_user_defined; */
     int D_unknown;
     int D_error;
 
@@ -498,21 +522,21 @@ typedef struct {
 
 /*! Linked list of drills found in active layers.  Used in reporting statistics */
 typedef struct drill_list {
-    int drill_num;
-    double drill_size;
-    gchar *drill_unit;
-    int drill_count;
-    struct drill_list *next;
+    int                drill_num;
+    double             drill_size;
+    gchar*             drill_unit;
+    int                drill_count;
+    struct drill_list* next;
 } gerbv_drill_list_t;
 
 /*! Struct holding statistics of drill commands used.  Used in reporting statistics */
 typedef struct {
     int layer_count;
-    
-    gerbv_error_list_t *error_list;
-    gerbv_drill_list_t *drill_list;
-    int comment;
-    int F;
+
+    gerbv_error_list_t* error_list;
+    gerbv_drill_list_t* drill_list;
+    int                 comment;
+    int                 F;
 
     int G00;
     int G01;
@@ -549,44 +573,44 @@ typedef struct {
     /* used to total up the drill count across all layers/sizes */
     int total_count;
 
-    char *detect;
+    char* detect;
 
 } gerbv_drill_stats_t;
 
 typedef struct {
-	gpointer image;		/* gerbv_image_t* */
-	gpointer net;		/* gerbv_net_t* */
+    gpointer image; /* gerbv_image_t* */
+    gpointer net;   /* gerbv_net_t* */
 } gerbv_selection_item_t;
 
 /*! Struct holding info about the last selection */
 typedef struct {
-	gerbv_selection_t type;
-	gdouble lowerLeftX;
-	gdouble lowerLeftY;
-	gdouble upperRightX;
-	gdouble upperRightY;
-	GArray *selectedNodeArray;
+    gerbv_selection_t type;
+    gdouble           lowerLeftX;
+    gdouble           lowerLeftY;
+    gdouble           upperRightX;
+    gdouble           upperRightY;
+    GArray*           selectedNodeArray;
 } gerbv_selection_info_t;
 
 /*!  Stores image transformation information, used to modify the rendered
 position/scale/etc of an image. */
 typedef struct {
-    gdouble translateX; /*!< the X translation (in inches) */
-    gdouble translateY; /*!< the Y translation (in inches) */
-    gdouble scaleX; /*!< the X scale factor (1.0 is default) */
-    gdouble scaleY; /*!< the Y scale factor (1.0 is default) */
-    gdouble rotation; /*!< the rotation of the layer around the origin (in radians) */
-    gboolean mirrorAroundX;  /*!< TRUE if the layer is mirrored around the X axis (vertical flip) */
-    gboolean mirrorAroundY;  /*!< TRUE if the layer is mirrored around the Y axis (vertical flip) */
-    gboolean inverted; /*!< TRUE if the image should be rendered "inverted" (light is dark and vice versa) */
+    gdouble  translateX;    /*!< the X translation (in inches) */
+    gdouble  translateY;    /*!< the Y translation (in inches) */
+    gdouble  scaleX;        /*!< the X scale factor (1.0 is default) */
+    gdouble  scaleY;        /*!< the Y scale factor (1.0 is default) */
+    gdouble  rotation;      /*!< the rotation of the layer around the origin (in radians) */
+    gboolean mirrorAroundX; /*!< TRUE if the layer is mirrored around the X axis (vertical flip) */
+    gboolean mirrorAroundY; /*!< TRUE if the layer is mirrored around the Y axis (vertical flip) */
+    gboolean inverted;      /*!< TRUE if the image should be rendered "inverted" (light is dark and vice versa) */
 } gerbv_user_transformation_t;
 
 /*!  This defines a box location and size (used to rendering logic) */
 typedef struct {
-    double left; /*!< the X coordinate of the left side */
-    double right; /*!< the X coordinate of the right side */
+    double left;   /*!< the X coordinate of the left side */
+    double right;  /*!< the X coordinate of the right side */
     double bottom; /*!< the Y coordinate of the bottom side */
-    double top; /*!< the Y coordinate of the top side */
+    double top;    /*!< the Y coordinate of the top side */
 } gerbv_render_size_t;
 
 typedef struct gerbv_cirseg {
@@ -599,60 +623,60 @@ typedef struct gerbv_cirseg {
 } gerbv_cirseg_t;
 
 typedef struct gerbv_step_and_repeat { /* SR parameters */
-    int X;
-    int Y;
+    int    X;
+    int    Y;
     double dist_X;
     double dist_Y;
 } gerbv_step_and_repeat_t;
- 
+
 typedef struct {
-    gboolean firstInstance;
+    gboolean              firstInstance;
     gerbv_knockout_type_t type;
-    gerbv_polarity_t polarity;
-    gdouble lowerLeftX;
-    gdouble lowerLeftY;
-    gdouble width;
-    gdouble height;
-    gdouble border;
+    gerbv_polarity_t      polarity;
+    gdouble               lowerLeftX;
+    gdouble               lowerLeftY;
+    gdouble               width;
+    gdouble               height;
+    gdouble               border;
 } gerbv_knockout_t;
- 
+
 /*!  The structure used to keep track of RS274X layer groups */
 typedef struct {
     gerbv_step_and_repeat_t stepAndRepeat; /*!< the current step and repeat group (refer to RS274X spec) */
-    gerbv_knockout_t knockout; /*!< the current knockout group (refer to RS274X spec) */
-    gdouble rotation; /*!< the current rotation around the origin */
-    gerbv_polarity_t polarity; /*!< the polarity of this layer */
-    gchar *name; /*!< the layer name (NULL for none) */
-    gpointer next; /*!< the next layer group in the array */
+    gerbv_knockout_t        knockout;      /*!< the current knockout group (refer to RS274X spec) */
+    gdouble                 rotation;      /*!< the current rotation around the origin */
+    gerbv_polarity_t        polarity;      /*!< the polarity of this layer */
+    gchar*                  name;          /*!< the layer name (NULL for none) */
+    gpointer                next;          /*!< the next layer group in the array */
 } gerbv_layer_t;
 
 /*!  The structure used to keep track of RS274X state groups */
 typedef struct {
-    gerbv_axis_select_t axisSelect; /*!< the AB to XY coordinate mapping (refer to RS274X spec) */
+    gerbv_axis_select_t  axisSelect;  /*!< the AB to XY coordinate mapping (refer to RS274X spec) */
     gerbv_mirror_state_t mirrorState; /*!< any mirroring around the X or Y axis */
-    gerbv_unit_t unit; /*!< the current length unit */
-    gdouble offsetA; /*!< the offset along the A axis (usually this is the X axis) */
-    gdouble offsetB; /*!< the offset along the B axis (usually this is the Y axis) */
-    gdouble scaleA; /*!< the scale factor in the A axis (usually this is the X axis) */
-    gdouble scaleB; /*!< the scale factor in the B axis (usually this is the Y axis) */
-    gpointer next; /*!< the next state group in the array */
+    gerbv_unit_t         unit;        /*!< the current length unit */
+    gdouble              offsetA;     /*!< the offset along the A axis (usually this is the X axis) */
+    gdouble              offsetB;     /*!< the offset along the B axis (usually this is the Y axis) */
+    gdouble              scaleA;      /*!< the scale factor in the A axis (usually this is the X axis) */
+    gdouble              scaleB;      /*!< the scale factor in the B axis (usually this is the Y axis) */
+    gpointer             next;        /*!< the next state group in the array */
 } gerbv_netstate_t;
 
 /*!  The structure used to hold a geometric entity (line/polygon/etc)*/
 typedef struct gerbv_net {
-    double start_x; /*!< the X coordinate of the start point */
-    double start_y; /*!< the Y coordinate of the start point */
-    double stop_x; /*!< the X coordinate of the end point */
-    double stop_y; /*!< the Y coordinate of the end point */
-    gerbv_render_size_t boundingBox; /*!< the bounding box containing this net (used for rendering optimizations) */
-    int aperture; /*!< the index of the aperture used for this entity */
+    double                 start_x;     /*!< the X coordinate of the start point */
+    double                 start_y;     /*!< the Y coordinate of the start point */
+    double                 stop_x;      /*!< the X coordinate of the end point */
+    double                 stop_y;      /*!< the Y coordinate of the end point */
+    gerbv_render_size_t    boundingBox; /*!< the bounding box containing this net (used for rendering optimizations) */
+    int                    aperture;    /*!< the index of the aperture used for this entity */
     gerbv_aperture_state_t aperture_state; /*!< the state of the aperture tool (on/off/etc) */
-    gerbv_interpolation_t interpolation; /*!< the path interpolation method (linear/etc) */
-    gerbv_cirseg_t *cirseg; /*!< information for arc nets */
-    struct gerbv_net *next; /*!< the next net in the array */
-    GString *label; /*!< a label string for this net */
-    gerbv_layer_t *layer; /*!< the RS274X layer this net belongs to */
-    gerbv_netstate_t *state; /*!< the RS274X state this net belongs to */
+    gerbv_interpolation_t  interpolation;  /*!< the path interpolation method (linear/etc) */
+    gerbv_cirseg_t*        cirseg;         /*!< information for arc nets */
+    struct gerbv_net*      next;           /*!< the next net in the array */
+    GString*               label;          /*!< a label string for this net */
+    gerbv_layer_t*         layer;          /*!< the RS274X layer this net belongs to */
+    gerbv_netstate_t*      state;          /*!< the RS274X state this net belongs to */
 } gerbv_net_t;
 
 /*! Struct holding info about interpreting the Gerber files read
@@ -660,476 +684,431 @@ typedef struct gerbv_net {
 typedef struct gerbv_format {
     gerbv_omit_zeros_t omit_zeros;
     gerbv_coordinate_t coordinate;
-    int x_int;
-    int x_dec;
-    int y_int;
-    int y_dec;
-    int lim_seqno; /* Length limit for codes of sequence number */
-    int lim_gf;    /* Length limit for codes of general function */
-    int lim_pf;    /* Length limit for codes of plot function */
-    int lim_mf;    /* Length limit for codes of miscellaneous function */
+    int                x_int;
+    int                x_dec;
+    int                y_int;
+    int                y_dec;
+    int                lim_seqno; /* Length limit for codes of sequence number */
+    int                lim_gf;    /* Length limit for codes of general function */
+    int                lim_pf;    /* Length limit for codes of plot function */
+    int                lim_mf;    /* Length limit for codes of miscellaneous function */
 } gerbv_format_t;
-	
 
 /*! Struct holding info about a particular image */
 typedef struct gerbv_image_info {
-    char *name;
-    gerbv_polarity_t polarity;
-    double min_x; /* Always in inches */
-    double min_y;
-    double max_x;
-    double max_y;
-    double offsetA;
-    double offsetB;
-    gerbv_encoding_t encoding;
-    double imageRotation;
+    char*                      name;
+    gerbv_polarity_t           polarity;
+    double                     min_x; /* Always in inches */
+    double                     min_y;
+    double                     max_x;
+    double                     max_y;
+    double                     offsetA;
+    double                     offsetB;
+    gerbv_encoding_t           encoding;
+    double                     imageRotation;
     gerbv_image_justify_type_t imageJustifyTypeA;
     gerbv_image_justify_type_t imageJustifyTypeB;
-    gdouble imageJustifyOffsetA;
-    gdouble imageJustifyOffsetB;
-    gdouble imageJustifyOffsetActualA;
-    gdouble imageJustifyOffsetActualB;
-    gchar *plotterFilm;
+    gdouble                    imageJustifyOffsetA;
+    gdouble                    imageJustifyOffsetB;
+    gdouble                    imageJustifyOffsetActualA;
+    gdouble                    imageJustifyOffsetActualB;
+    gchar*                     plotterFilm;
 
     /* Descriptive string for the type of file (rs274-x, drill, etc)
      * that this is
      */
-    gchar *type;
+    gchar* type;
 
     /* Attribute list that is used to hold all sorts of information
      * about how the layer is to be parsed.
-    */ 
-    gerbv_HID_Attribute *attr_list;
-    int n_attr;
+     */
+    gerbv_HID_Attribute* attr_list;
+    int                  n_attr;
 } gerbv_image_info_t;
 
 /*!  The structure used to hold a layer (RS274X, drill, or pick-and-place data) */
 typedef struct {
-  gerbv_layertype_t layertype; /*!< the type of layer (RS274X, drill, or pick-and-place) */
-  gerbv_aperture_t *aperture[APERTURE_MAX]; /*!< an array with all apertures used */
-  gerbv_layer_t *layers; /*!< an array of all RS274X layers used (only used in RS274X types) */
-  gerbv_netstate_t *states; /*!< an array of all RS274X states used (only used in RS274X types) */
-  gerbv_amacro_t *amacro; /*!< an array of all macros used (only used in RS274X types) */
-  gerbv_format_t *format; /*!< formatting info */
-  gerbv_image_info_t *info; /*!< miscellaneous info regarding the layer such as overall size, etc */
-  gerbv_net_t *netlist; /*!< an array of all geometric entities in the layer */
-  gerbv_stats_t *gerbv_stats; /*!< RS274X statistics for the layer */
-  gerbv_drill_stats_t *drill_stats;  /*!< Excellon drill statistics for the layer */
+    gerbv_layertype_t    layertype;              /*!< the type of layer (RS274X, drill, or pick-and-place) */
+    gerbv_aperture_t*    aperture[APERTURE_MAX]; /*!< an array with all apertures used */
+    gerbv_layer_t*       layers;                 /*!< an array of all RS274X layers used (only used in RS274X types) */
+    gerbv_netstate_t*    states;                 /*!< an array of all RS274X states used (only used in RS274X types) */
+    gerbv_amacro_t*      amacro;                 /*!< an array of all macros used (only used in RS274X types) */
+    gerbv_format_t*      format;                 /*!< formatting info */
+    gerbv_image_info_t*  info;        /*!< miscellaneous info regarding the layer such as overall size, etc */
+    gerbv_net_t*         netlist;     /*!< an array of all geometric entities in the layer */
+    gerbv_stats_t*       gerbv_stats; /*!< RS274X statistics for the layer */
+    gerbv_drill_stats_t* drill_stats; /*!< Excellon drill statistics for the layer */
 } gerbv_image_t;
 
 /*!  Holds information related to an individual layer that is part of a project */
 typedef struct {
-  gerbv_image_t *image; /*!< the image holding all the geometry of the layer */
-  GdkColor color; /*!< the color to render this layer with */
-  guint16 alpha; /*!< the transparency to render this layer with */
-  gboolean isVisible; /*!< TRUE if this layer should be rendered with the project */
-  gpointer privateRenderData; /*!< private data holder for the rendering backend */
-  gchar *fullPathname; /*!< this full pathname to the file */
-  gchar *name; /*!< the name used when referring to this layer (e.g. in a layer selection menu) */
-  gerbv_user_transformation_t transform; /*!< user-specified transformation for this layer (mirroring, translating, etc) */
-  gboolean layer_dirty;  /*!< True if layer has been modified since last save */
+    gerbv_image_t* image;             /*!< the image holding all the geometry of the layer */
+    GdkColor       color;             /*!< the color to render this layer with */
+    guint16        alpha;             /*!< the transparency to render this layer with */
+    gboolean       isVisible;         /*!< TRUE if this layer should be rendered with the project */
+    gpointer       privateRenderData; /*!< private data holder for the rendering backend */
+    gchar*         fullPathname;      /*!< this full pathname to the file */
+    gchar*         name; /*!< the name used when referring to this layer (e.g. in a layer selection menu) */
+    gerbv_user_transformation_t
+             transform;   /*!< user-specified transformation for this layer (mirroring, translating, etc) */
+    gboolean layer_dirty; /*!< True if layer has been modified since last save */
 } gerbv_fileinfo_t;
 
 /*!  The top-level structure used in libgerbv.  A gerbv_project_t groups together
 any number of layers, while keeping track of other basic paramters needed for rendering */
 typedef struct {
-  GdkColor  background; /*!< the background color used for rendering */
-  int max_files; /*!< the current number of fileinfos in the file array */
-  gerbv_fileinfo_t **file; /*!< the array for holding the child fileinfos */
-  int curr_index; /*!< the index of the currently active fileinfo */
-  int last_loaded; /*!< the (number-1) of fileinfos currently in the project */
-  int renderType; /*!< the type of renderer to use */
-  gboolean check_before_delete;  /*!< TRUE to ask before deleting objects */
-  gboolean show_invisible_selection; /*!< TRUE to show selected objects on invisible files */
-  gchar *path; /*!< the default path to load new files from */
-  gchar *execpath;    /*!< the path to executed version of Gerbv */
-  gchar *execname;    /*!< the path plus executible name for Gerbv */
-  gchar *project;     /*!< the default name for the private project file */
+    GdkColor           background;               /*!< the background color used for rendering */
+    int                max_files;                /*!< the current number of fileinfos in the file array */
+    gerbv_fileinfo_t** file;                     /*!< the array for holding the child fileinfos */
+    int                curr_index;               /*!< the index of the currently active fileinfo */
+    int                last_loaded;              /*!< the (number-1) of fileinfos currently in the project */
+    int                renderType;               /*!< the type of renderer to use */
+    gboolean           check_before_delete;      /*!< TRUE to ask before deleting objects */
+    gboolean           show_invisible_selection; /*!< TRUE to show selected objects on invisible files */
+    gchar*             path;                     /*!< the default path to load new files from */
+    gchar*             execpath;                 /*!< the path to executed version of Gerbv */
+    gchar*             execname;                 /*!< the path plus executible name for Gerbv */
+    gchar*             project;                  /*!< the default name for the private project file */
 } gerbv_project_t;
 
 /*! Color of layer */
-typedef struct{
+typedef struct {
     unsigned char red;
     unsigned char green;
     unsigned char blue;
     unsigned char alpha;
-}gerbv_layer_color;
+} gerbv_layer_color;
 
 /*!  This contains the rendering info for a scene */
 typedef struct {
-	gdouble scaleFactorX; /*!< the X direction scale factor */
-	gdouble scaleFactorY; /*!< the Y direction scale factor */
-	gdouble lowerLeftX; /*!< the X coordinate of the lower left corner (in real world coordinates, in inches) */
-	gdouble lowerLeftY; /*!< the Y coordinate of the lower left corner (in real world coordinates, in inches) */
-	gerbv_render_types_t renderType; /*!< the type of rendering to use */
-	gint displayWidth; /*!< the width of the scene (in pixels, or points depending on the surface type) */
-	gint displayHeight; /*!< the height of the scene (in pixels, or points depending on the surface type) */
-	gboolean show_cross_on_drill_holes; /*!< TRUE to show cross on drill holes */
+    gdouble scaleFactorX; /*!< the X direction scale factor */
+    gdouble scaleFactorY; /*!< the Y direction scale factor */
+    gdouble lowerLeftX;   /*!< the X coordinate of the lower left corner (in real world coordinates, in inches) */
+    gdouble lowerLeftY;   /*!< the Y coordinate of the lower left corner (in real world coordinates, in inches) */
+    gerbv_render_types_t renderType; /*!< the type of rendering to use */
+    gint     displayWidth;           /*!< the width of the scene (in pixels, or points depending on the surface type) */
+    gint     displayHeight; /*!< the height of the scene (in pixels, or points depending on the surface type) */
+    gboolean show_cross_on_drill_holes; /*!< TRUE to show cross on drill holes */
 } gerbv_render_info_t;
 
 //! Allocate a new gerbv_image structure
 //! \return the newly created image
-gerbv_image_t *gerbv_create_image(gerbv_image_t *image, /*!< the old image to free or NULL */
-		const gchar *type /*!< the type of image to create */
+gerbv_image_t* gerbv_create_image(
+    gerbv_image_t* image, /*!< the old image to free or NULL */
+    const gchar*   type   /*!< the type of image to create */
 );
 
 //! Free an image structure
-void gerbv_destroy_image(gerbv_image_t *image /*!< the image to free */
+void gerbv_destroy_image(gerbv_image_t* image /*!< the image to free */
 );
 
 //! Copy an image into an existing image, effectively merging the two together
-void
-gerbv_image_copy_image (gerbv_image_t *sourceImage, /*!< the source image */
-	gerbv_user_transformation_t *transform, /*!< the transformation to apply to the new image, or NULL for none */
-	gerbv_image_t *destinationImage /*!< the destination image to copy to */
+void gerbv_image_copy_image(
+    gerbv_image_t*               sourceImage,     /*!< the source image */
+    gerbv_user_transformation_t* transform,       /*!< the transformation to apply to the new image, or NULL for none */
+    gerbv_image_t*               destinationImage /*!< the destination image to copy to */
 );
 
 //! Duplicate an existing image and return the new copy
 //! \return the newly created image
-gerbv_image_t *
-gerbv_image_duplicate_image (gerbv_image_t *sourceImage, /*!< the source image */
-	gerbv_user_transformation_t *transform /*!< the transformation to apply to the new image, or NULL for none */
+gerbv_image_t* gerbv_image_duplicate_image(
+    gerbv_image_t*               sourceImage, /*!< the source image */
+    gerbv_user_transformation_t* transform    /*!< the transformation to apply to the new image, or NULL for none */
 );
 
 //! Delete a net in an existing image
-void
-gerbv_image_delete_net (gerbv_net_t *currentNet /*!< the net to delete */
+void gerbv_image_delete_net(gerbv_net_t* currentNet /*!< the net to delete */
 );
 
-gboolean
-gerbv_image_reduce_area_of_selected_objects (GArray *selectionArray, gdouble areaReduction, gint paneRows,
-		gint paneColumns, gdouble paneSeparation);
+gboolean gerbv_image_reduce_area_of_selected_objects(
+    GArray* selectionArray, gdouble areaReduction, gint paneRows, gint paneColumns, gdouble paneSeparation
+);
 
-gboolean
-gerbv_image_move_selected_objects (GArray *selectionArray, gdouble translationX,
-		gdouble translationY);
+gboolean gerbv_image_move_selected_objects(GArray* selectionArray, gdouble translationX, gdouble translationY);
 
 //! Return the next net entry which corresponds to a unique visible object
-gerbv_net_t *
-gerbv_image_return_next_renderable_object (gerbv_net_t *oldNet);
+gerbv_net_t* gerbv_image_return_next_renderable_object(gerbv_net_t* oldNet);
 
 //! Create a new project structure and initialize some important variables
-gerbv_project_t *
-gerbv_create_project (void);
+gerbv_project_t* gerbv_create_project(void);
 
 //! Free a project and all related variables
-void
-gerbv_destroy_project (gerbv_project_t *gerbvProject /*!< the project to destroy */
+void gerbv_destroy_project(gerbv_project_t* gerbvProject /*!< the project to destroy */
 );
 
 //! Open a file, parse the contents, and add a new layer to an existing project
-void 
-gerbv_open_layer_from_filename (
-	gerbv_project_t *gerbvProject, /*!< the existing project to add the new layer to */
-	gchar const* filename /*!< the full pathname of the file to be parsed */
+void gerbv_open_layer_from_filename(
+    gerbv_project_t* gerbvProject, /*!< the existing project to add the new layer to */
+    const gchar*     filename      /*!< the full pathname of the file to be parsed */
 );
 
 //! Open a file, parse the contents, and add a new layer to an existing project while setting the color of the layer
-void 
-gerbv_open_layer_from_filename_with_color(gerbv_project_t *gerbvProject, /*!< the existing project to add the new layer to */
-	gchar const* filename, /*!< the full pathname of the file to be parsed */
-	guint16 red, /*!< the value for the red color component */
-	guint16 green, /*!< the value for the green color component */
-	guint16 blue, /*!< the value for the blue color component */
-	guint16 alpha /*!< the value for the alpha color component */
+void gerbv_open_layer_from_filename_with_color(
+    gerbv_project_t* gerbvProject, /*!< the existing project to add the new layer to */
+    const gchar*     filename,     /*!< the full pathname of the file to be parsed */
+    guint16          red,          /*!< the value for the red color component */
+    guint16          green,        /*!< the value for the green color component */
+    guint16          blue,         /*!< the value for the blue color component */
+    guint16          alpha         /*!< the value for the alpha color component */
 );
 
 //! Free a fileinfo structure
-void
-gerbv_destroy_fileinfo (gerbv_fileinfo_t *fileInfo /*!< the fileinfo to free */
+void gerbv_destroy_fileinfo(gerbv_fileinfo_t* fileInfo /*!< the fileinfo to free */
 );
 
-gboolean 
-gerbv_save_layer_from_index(gerbv_project_t *gerbvProject, gint index, gchar *filename);
+gboolean gerbv_save_layer_from_index(gerbv_project_t* gerbvProject, gint index, gchar* filename);
 
-int
-gerbv_revert_file(gerbv_project_t *gerbvProject, int idx);
+int gerbv_revert_file(gerbv_project_t* gerbvProject, int idx);
 
-void 
-gerbv_revert_all_files(gerbv_project_t *gerbvProject);
+void gerbv_revert_all_files(gerbv_project_t* gerbvProject);
 
-void 
-gerbv_unload_layer(gerbv_project_t *gerbvProject, int index);
+void gerbv_unload_layer(gerbv_project_t* gerbvProject, int index);
 
-void 
-gerbv_unload_all_layers (gerbv_project_t *gerbvProject);
+void gerbv_unload_all_layers(gerbv_project_t* gerbvProject);
 
-void 
-gerbv_change_layer_order(gerbv_project_t *gerbvProject, gint oldPosition, gint newPosition);
+void gerbv_change_layer_order(gerbv_project_t* gerbvProject, gint oldPosition, gint newPosition);
 
-gint
-gerbv_add_parsed_image_to_project (gerbv_project_t *gerbvProject, gerbv_image_t *parsed_image,
-			gchar const* filename, gchar const* baseName, int idx, int reload);
-int
-gerbv_open_image(gerbv_project_t *gerbvProject, gchar const* filename, int idx, int reload,
-		gerbv_HID_Attribute *fattr, int n_fattr, gboolean forceLoadFile);
-		
-void
-gerbv_render_get_boundingbox(gerbv_project_t *gerbvProject, gerbv_render_size_t *boundingbox);
+gint gerbv_add_parsed_image_to_project(
+    gerbv_project_t* gerbvProject, gerbv_image_t* parsed_image, const gchar* filename, const gchar* baseName, int idx,
+    int reload
+);
+int gerbv_open_image(
+    gerbv_project_t* gerbvProject, const gchar* filename, int idx, int reload, gerbv_HID_Attribute* fattr, int n_fattr,
+    gboolean forceLoadFile
+);
+
+void gerbv_render_get_boundingbox(gerbv_project_t* gerbvProject, gerbv_render_size_t* boundingbox);
 
 //! Calculate the zoom and translations to fit the rendered scene inside the given scene size
-void
-gerbv_render_zoom_to_fit_display (gerbv_project_t *gerbvProject, /*!< the project to use for calculating */
-		gerbv_render_info_t *renderInfo /*!< the scene render pointer (updates the values in this parameter) */
+void gerbv_render_zoom_to_fit_display(
+    gerbv_project_t*     gerbvProject, /*!< the project to use for calculating */
+    gerbv_render_info_t* renderInfo    /*!< the scene render pointer (updates the values in this parameter) */
 );
 
-void
-gerbv_render_translate_to_fit_display (gerbv_project_t *gerbvProject, gerbv_render_info_t *renderInfo);
+void gerbv_render_translate_to_fit_display(gerbv_project_t* gerbvProject, gerbv_render_info_t* renderInfo);
 
-void
-gerbv_render_to_pixmap_using_gdk (gerbv_project_t *gerbvProject, GdkPixmap *pixmap,
-		gerbv_render_info_t *renderInfo, gerbv_selection_info_t *selectionInfo,
-		GdkColor *selectionColor);
+void gerbv_render_to_pixmap_using_gdk(
+    gerbv_project_t* gerbvProject, GdkPixmap* pixmap, gerbv_render_info_t* renderInfo,
+    gerbv_selection_info_t* selectionInfo, GdkColor* selectionColor
+);
 
 #ifndef RENDER_USING_GDK
-void
-gerbv_render_all_layers_to_cairo_target_for_vector_output (gerbv_project_t *gerbvProject,
-		cairo_t *cr, gerbv_render_info_t *renderInfo);
+void gerbv_render_all_layers_to_cairo_target_for_vector_output(
+    gerbv_project_t* gerbvProject, cairo_t* cr, gerbv_render_info_t* renderInfo
+);
 
 void
-gerbv_render_all_layers_to_cairo_target (gerbv_project_t *gerbvProject, cairo_t *cr,
-			gerbv_render_info_t *renderInfo);
+gerbv_render_all_layers_to_cairo_target(gerbv_project_t* gerbvProject, cairo_t* cr, gerbv_render_info_t* renderInfo);
 
 //! Render a layer to a cairo context
-void
-gerbv_render_layer_to_cairo_target (cairo_t *cr, /*!< the cairo context */
-		gerbv_fileinfo_t *fileInfo, /*!< the layer fileinfo pointer */
-		gerbv_render_info_t *renderInfo /*!< the scene render info */
+void gerbv_render_layer_to_cairo_target(
+    cairo_t*             cr,        /*!< the cairo context */
+    gerbv_fileinfo_t*    fileInfo,  /*!< the layer fileinfo pointer */
+    gerbv_render_info_t* renderInfo /*!< the scene render info */
 );
-						
-void
-gerbv_render_cairo_set_scale_and_translation(cairo_t *cr, gerbv_render_info_t *renderInfo);
 
-void
-gerbv_render_layer_to_cairo_target_without_transforming(cairo_t *cr, gerbv_fileinfo_t *fileInfo, gerbv_render_info_t *renderInfo, gboolean pixelOutput );
-#endif
+void gerbv_render_cairo_set_scale_and_translation(cairo_t* cr, gerbv_render_info_t* renderInfo);
 
-double
-gerbv_get_tool_diameter(int toolNumber
+void gerbv_render_layer_to_cairo_target_without_transforming(
+    cairo_t* cr, gerbv_fileinfo_t* fileInfo, gerbv_render_info_t* renderInfo, gboolean pixelOutput
 );
+#endif
 
-int
-gerbv_process_tools_file(const char *toolFileName
-);
+double gerbv_get_tool_diameter(int toolNumber);
+
+int gerbv_process_tools_file(const char* toolFileName);
 
 //! Render a project to a PNG file, autoscaling the layers to fit inside the specified image dimensions
-void
-gerbv_export_png_file_from_project_autoscaled (
-		gerbv_project_t *gerbvProject, /*!< the project to render */
-		int widthInPixels, /*!< the width of the rendered picture (in pixels) */
-		int heightInPixels, /*!< the height of the rendered picture (in pixels) */
-		gchar const* filename  /*!< the filename for the exported PNG file */
+void gerbv_export_png_file_from_project_autoscaled(
+    gerbv_project_t* gerbvProject,   /*!< the project to render */
+    int              widthInPixels,  /*!< the width of the rendered picture (in pixels) */
+    int              heightInPixels, /*!< the height of the rendered picture (in pixels) */
+    const gchar*     filename        /*!< the filename for the exported PNG file */
 );
 
 //! Render a project to a PNG file using user-specified render info
-void
-gerbv_export_png_file_from_project (
-		gerbv_project_t *gerbvProject, /*!< the project to render */
-		gerbv_render_info_t *renderInfo, /*!< the render settings for the rendered image */
-		gchar const* filename /*!< the filename for the exported PNG file */
+void gerbv_export_png_file_from_project(
+    gerbv_project_t*     gerbvProject, /*!< the project to render */
+    gerbv_render_info_t* renderInfo,   /*!< the render settings for the rendered image */
+    const gchar*         filename      /*!< the filename for the exported PNG file */
 );
 
 //! Render a project to a PDF file, autoscaling the layers to fit inside the specified image dimensions
-void
-gerbv_export_pdf_file_from_project_autoscaled (
-		gerbv_project_t *gerbvProject, /*!< the project to render */
-		gchar const* filename  /*!< the filename for the exported PDF file */
+void gerbv_export_pdf_file_from_project_autoscaled(
+    gerbv_project_t* gerbvProject, /*!< the project to render */
+    const gchar*     filename      /*!< the filename for the exported PDF file */
 );
 
 //! Render a project to a PDF file using user-specified render info
-void
-gerbv_export_pdf_file_from_project (
-		gerbv_project_t *gerbvProject, /*!< the project to render */
-		gerbv_render_info_t *renderInfo, /*!< the render settings for the rendered image */
-		gchar const* filename /*!< the filename for the exported PDF file */
+void gerbv_export_pdf_file_from_project(
+    gerbv_project_t*     gerbvProject, /*!< the project to render */
+    gerbv_render_info_t* renderInfo,   /*!< the render settings for the rendered image */
+    const gchar*         filename      /*!< the filename for the exported PDF file */
 );
 
 //! Render a project to a Postscript file, autoscaling the layers to fit inside the specified image dimensions
-void
-gerbv_export_postscript_file_from_project_autoscaled (
-		gerbv_project_t *gerbvProject, /*!< the project to render */
-		gchar const* filename  /*!< the filename for the exported Postscript file */
+void gerbv_export_postscript_file_from_project_autoscaled(
+    gerbv_project_t* gerbvProject, /*!< the project to render */
+    const gchar*     filename      /*!< the filename for the exported Postscript file */
 );
 
 //! Render a project to a Postscript file using user-specified render info
-void
-gerbv_export_postscript_file_from_project (
-		gerbv_project_t *gerbvProject, /*!< the project to render */
-		gerbv_render_info_t *renderInfo, /*!< the render settings for the rendered image */
-		gchar const* filename /*!< the filename for the exported Postscript file */
+void gerbv_export_postscript_file_from_project(
+    gerbv_project_t*     gerbvProject, /*!< the project to render */
+    gerbv_render_info_t* renderInfo,   /*!< the render settings for the rendered image */
+    const gchar*         filename      /*!< the filename for the exported Postscript file */
 );
 
 //! Render a project to a SVG file, autoscaling the layers to fit inside the specified image dimensions
-void
-gerbv_export_svg_file_from_project_autoscaled (
-		gerbv_project_t *gerbvProject, /*!< the project to render */
-		gchar const* filename  /*!< the filename for the exported   file */
+void gerbv_export_svg_file_from_project_autoscaled(
+    gerbv_project_t* gerbvProject, /*!< the project to render */
+    const gchar*     filename      /*!< the filename for the exported   file */
 );
 
 //! Render a project to a   file using user-specified render info
-void
-gerbv_export_svg_file_from_project (
-		gerbv_project_t *gerbvProject, /*!< the project to render */
-		gerbv_render_info_t *renderInfo, /*!< the render settings for the rendered image */
-		gchar const* filename /*!< the filename for the exported   file */
+void gerbv_export_svg_file_from_project(
+    gerbv_project_t*     gerbvProject, /*!< the project to render */
+    gerbv_render_info_t* renderInfo,   /*!< the render settings for the rendered image */
+    const gchar*         filename      /*!< the filename for the exported   file */
 );
 
 //! Export an image to a new file in DXF format
 //! \return TRUE if successful, or FALSE if not
-gboolean
-gerbv_export_dxf_file_from_image (const gchar *filename, /*!< the filename for the new file */
-		gerbv_image_t *image, /*!< the image to export */
-		gerbv_user_transformation_t *transform /*!< the transformation to apply before exporting */
+gboolean gerbv_export_dxf_file_from_image(
+    const gchar*                 filename, /*!< the filename for the new file */
+    gerbv_image_t*               image,    /*!< the image to export */
+    gerbv_user_transformation_t* transform /*!< the transformation to apply before exporting */
 );
 
 //! Parse a RS274X file and return the parsed image
 //! \return the new gerbv_image_t, or NULL if not successful
-gerbv_image_t *
-gerbv_create_rs274x_image_from_filename (const gchar *filename /*!< the filename of the file to be parsed*/
+gerbv_image_t*
+gerbv_create_rs274x_image_from_filename(const gchar* filename /*!< the filename of the file to be parsed*/
 );
 
 //! Export an image to a new file in RS274X format
 //! \return TRUE if successful, or FALSE if not
-gboolean
-gerbv_export_rs274x_file_from_image (const gchar *filename, /*!< the filename for the new file */
-		gerbv_image_t *image, /*!< the image to export */
-		gerbv_user_transformation_t *transform /*!< the transformation to apply before exporting */
+gboolean gerbv_export_rs274x_file_from_image(
+    const gchar*                 filename, /*!< the filename for the new file */
+    gerbv_image_t*               image,    /*!< the image to export */
+    gerbv_user_transformation_t* transform /*!< the transformation to apply before exporting */
 );
 
 //! Export an image to a new file in Excellon drill format
 //! \return TRUE if successful, or FALSE if not
-gboolean
-gerbv_export_drill_file_from_image (const gchar *filename, /*!< the filename for the new file */
-		gerbv_image_t *image, /*!< the image to export */
-		gerbv_user_transformation_t *transform /*!< the transformation to apply before exporting */
+gboolean gerbv_export_drill_file_from_image(
+    const gchar*                 filename, /*!< the filename for the new file */
+    gerbv_image_t*               image,    /*!< the image to export */
+    gerbv_user_transformation_t* transform /*!< the transformation to apply before exporting */
 );
 
 //! Export an image to a new file in ISEL NCP drill format
 //! \return TRUE if successful, or FALSE if not
-gboolean
-gerbv_export_isel_drill_file_from_image (const gchar *filename, /*!< the filename for the new file */
-		gerbv_image_t *image, /*!< the image to export */
-		gerbv_user_transformation_t *transform /*!< the transformation to apply before exporting */
+gboolean gerbv_export_isel_drill_file_from_image(
+    const gchar*                 filename, /*!< the filename for the new file */
+    gerbv_image_t*               image,    /*!< the image to export */
+    gerbv_user_transformation_t* transform /*!< the transformation to apply before exporting */
 );
 
 //! Export an image to a new file in gEDA PCB format
 //! \return TRUE if successful, or FALSE if not
-gboolean
-gerbv_export_geda_pcb_file_from_image (const gchar *filename, /*!< the filename for the new file */
-		gerbv_image_t *image, /*!< the image to export */
-		gerbv_user_transformation_t *transform /*!< the transformation to apply before exporting */
+gboolean gerbv_export_geda_pcb_file_from_image(
+    const gchar*                 filename, /*!< the filename for the new file */
+    gerbv_image_t*               image,    /*!< the image to export */
+    gerbv_user_transformation_t* transform /*!< the transformation to apply before exporting */
 );
 
 //! Draw a line on the specified image
-void
-gerbv_image_create_line_object (gerbv_image_t *image, /*!< the image to draw to */
-		gdouble startX, /*!< the starting X coordinate */
-		gdouble startY, /*!< the starting Y coordinate */
-		gdouble endX, /*!< the ending X coordinate */
-		gdouble endY, /*!< the ending Y coordinate */
-		gdouble lineWidth, /*!< the width of the line to draw */
-		gerbv_aperture_type_t apertureType  /*!< the type of aperture to use (e.g. CIRCLE) */
+void gerbv_image_create_line_object(
+    gerbv_image_t*        image,       /*!< the image to draw to */
+    gdouble               startX,      /*!< the starting X coordinate */
+    gdouble               startY,      /*!< the starting Y coordinate */
+    gdouble               endX,        /*!< the ending X coordinate */
+    gdouble               endY,        /*!< the ending Y coordinate */
+    gdouble               lineWidth,   /*!< the width of the line to draw */
+    gerbv_aperture_type_t apertureType /*!< the type of aperture to use (e.g. CIRCLE) */
 );
 
 //! Draw an arc on the specified image
-void
-gerbv_image_create_arc_object (gerbv_image_t *image, /*!< the image to draw to */
-		gdouble centerX, /*!< the center X coordinate */
-		gdouble centerY, /*!< the center Y coordinate */
-		gdouble radius, /*!< the arc radius */
-		gdouble startAngle, /*!< the start angle (in CCW degrees) */
-		gdouble endAngle, /*!< the start angle (in CCW degrees) */
-		gdouble lineWidth, /*!< the width of the line to draw */
-		gerbv_aperture_type_t apertureType  /*!< the type of aperture to use (e.g. CIRCLE) */
+void gerbv_image_create_arc_object(
+    gerbv_image_t*        image,       /*!< the image to draw to */
+    gdouble               centerX,     /*!< the center X coordinate */
+    gdouble               centerY,     /*!< the center Y coordinate */
+    gdouble               radius,      /*!< the arc radius */
+    gdouble               startAngle,  /*!< the start angle (in CCW degrees) */
+    gdouble               endAngle,    /*!< the start angle (in CCW degrees) */
+    gdouble               lineWidth,   /*!< the width of the line to draw */
+    gerbv_aperture_type_t apertureType /*!< the type of aperture to use (e.g. CIRCLE) */
 );
-		
-//! Draw a filled rectangle on the specified image	
-void
-gerbv_image_create_rectangle_object (gerbv_image_t *image, /*!< the image to draw to */
-		gdouble coordinateX, /*!< the X coordinate of the lower left corner */
-		gdouble coordinateY, /*!< the Y coordinate of the lower left corner */
-		gdouble width, /*!< the width of the drawn rectangle */
-		gdouble height /*!< the height of the drawn rectangle */
+
+//! Draw a filled rectangle on the specified image
+void gerbv_image_create_rectangle_object(
+    gerbv_image_t* image,       /*!< the image to draw to */
+    gdouble        coordinateX, /*!< the X coordinate of the lower left corner */
+    gdouble        coordinateY, /*!< the Y coordinate of the lower left corner */
+    gdouble        width,       /*!< the width of the drawn rectangle */
+    gdouble        height       /*!< the height of the drawn rectangle */
 );
 
 //! Create any missing apertures in the specified image
-void
-gerbv_image_create_dummy_apertures (gerbv_image_t *parsed_image /*!< the image to repair */
+void gerbv_image_create_dummy_apertures(gerbv_image_t* parsed_image /*!< the image to repair */
 );
-		
+
 /*! Create new struct for holding drill stats */
-gerbv_drill_stats_t *
-gerbv_drill_stats_new(void);
+gerbv_drill_stats_t* gerbv_drill_stats_new(void);
 
 /*! Free the memory for a drill stats struct */
-void
-gerbv_drill_stats_destroy(gerbv_drill_stats_t *);
+void gerbv_drill_stats_destroy(gerbv_drill_stats_t*);
 
 /*! Add stats gathered from specified layer to accumulatedd drill stats
  *  compiled from all layers */
-void
-gerbv_drill_stats_add_layer(gerbv_drill_stats_t *accum_stats,
-		gerbv_drill_stats_t *input_stats,
-		int this_layer
-);
+void gerbv_drill_stats_add_layer(gerbv_drill_stats_t* accum_stats, gerbv_drill_stats_t* input_stats, int this_layer);
 
 /*! Create new struct for holding Gerber stats */
-gerbv_stats_t *
-gerbv_stats_new(void);
+gerbv_stats_t* gerbv_stats_new(void);
 
 /*! Free the memory for a stats struct */
-void
-gerbv_stats_destroy(gerbv_stats_t *);
+void gerbv_stats_destroy(gerbv_stats_t*);
 
 /*! Add stats gathered from specified layer to accumulated Gerber stats
  *  compiled from all layers */
-void
-gerbv_stats_add_layer(gerbv_stats_t *accum_stats, 
-		gerbv_stats_t *input_stats,
-		int this_layer
-);
+void gerbv_stats_add_layer(gerbv_stats_t* accum_stats, gerbv_stats_t* input_stats, int this_layer);
 
-void
-gerbv_attribute_destroy_HID_attribute (gerbv_HID_Attribute *attributeList, int n_attr);
+void gerbv_attribute_destroy_HID_attribute(gerbv_HID_Attribute* attributeList, int n_attr);
 
-gerbv_HID_Attribute *
-gerbv_attribute_dup (gerbv_HID_Attribute *, int);
+gerbv_HID_Attribute* gerbv_attribute_dup(gerbv_HID_Attribute*, int);
 
 /*! Return found fileinfo for image, or NULL */
-gerbv_fileinfo_t *
-gerbv_get_fileinfo_for_image(const gerbv_image_t *image,
-				const gerbv_project_t *project);
+gerbv_fileinfo_t* gerbv_get_fileinfo_for_image(const gerbv_image_t* image, const gerbv_project_t* project);
 
 /*! Transform coordinate x and y for image in project */
-int
-gerbv_transform_coord_for_image(double *x, double *y,
-		const gerbv_image_t *image, const gerbv_project_t *project);
+int gerbv_transform_coord_for_image(double* x, double* y, const gerbv_image_t* image, const gerbv_project_t* project);
 
 /*! See if 'path' ends with the filename extension 'ext' */
-gboolean
-gerbv_endswith(const char *path, const char *ext);
+gboolean gerbv_endswith(const char* path, const char* ext);
 
 /*! Transform coordinate x and y */
-void
-gerbv_transform_coord(double *x, double *y,
-		const gerbv_user_transformation_t *trans);
+void gerbv_transform_coord(double* x, double* y, const gerbv_user_transformation_t* trans);
 
 /*! Rotate coordinate x and y buy angle in radians */
-void
-gerbv_rotate_coord(double *x, double *y, double rad);
+void gerbv_rotate_coord(double* x, double* y, double rad);
 
 #undef MIN
 #undef MAX
-#define MIN(x,y) ({ \
-		typeof(x) _x = (x);     \
-		typeof(y) _y = (y);     \
-		(void) (&_x == &_y);    \
-		_x < _y ? _x : _y; })
-#define MAX(x,y) ({ \
-		typeof(x) _x = (x);     \
-		typeof(y) _y = (y);     \
-		(void) (&_x == &_y);    \
-		_x > _y ? _x : _y; })
+#define MIN(x, y)           \
+    ({                      \
+        typeof(x) _x = (x); \
+        typeof(y) _y = (y); \
+        (void)(&_x == &_y); \
+        _x < _y ? _x : _y;  \
+    })
+#define MAX(x, y)           \
+    ({                      \
+        typeof(x) _x = (x); \
+        typeof(y) _y = (y); \
+        (void)(&_x == &_y); \
+        _x > _y ? _x : _y;  \
+    })
 
 #if defined(__cplusplus)
 }
diff --git a/src/gerbv_icon.h b/src/gerbv_icon.h
index 9b09bef..847835d 100644
--- a/src/gerbv_icon.h
+++ b/src/gerbv_icon.h
@@ -9,460 +9,371 @@
 
 #ifdef USE_NEW_ICON
 /* This is the new icon */
-static char *gerbv_icon_xpm[] = {
-/* columns rows colors chars-per-pixel */
-"48 48 104 2",
-"   c #000000",
-".  c #050709",
-"X  c #070808",
-"o  c #090A0A",
-"O  c #0E0F10",
-"+  c #121313",
-"@  c #151618",
-"#  c #13181C",
-"$  c #191B1C",
-"%  c #151C23",
-"&  c #191C20",
-"*  c #1E2124",
-"=  c #19232E",
-"-  c #1F2C3A",
-";  c #232425",
-":  c #222628",
-">  c #24292B",
-",  c #2A2B2C",
-"<  c #292F31",
-"1  c #22303F",
-"2  c #2D3335",
-"3  c #343434",
-"4  c #3B3B3B",
-"5  c #273544",
-"6  c #293746",
-"7  c #2D3B4A",
-"8  c #323940",
-"9  c #333E4B",
-"0  c #434343",
-"q  c #4B4B4B",
-"w  c #495057",
-"e  c #49525B",
-"r  c #535353",
-"t  c #50575E",
-"y  c #5A5A5A",
-"u  c #4D5966",
-"i  c #515F6E",
-"p  c #56626F",
-"a  c #596067",
-"s  c #5C6671",
-"d  c #5D6B7A",
-"f  c #636363",
-"g  c #61686F",
-"h  c #6B6B6B",
-"j  c #646B72",
-"k  c #616F7E",
-"l  c #62707F",
-"z  c #737373",
-"x  c #7D7D7D",
-"c  c #657382",
-"v  c #697786",
-"b  c #6D7986",
-"n  c #6D7B8A",
-"m  c #717F8E",
-"M  c #74808E",
-"N  c #748392",
-"B  c #798593",
-"V  c #7E8C9B",
-"C  c #848484",
-"Z  c #8A8A8A",
-"A  c #81909F",
-"S  c #949494",
-"D  c #9A9A9A",
-"F  c #8392A1",
-"G  c #8896A5",
-"H  c #8D9BAA",
-"J  c #919DAB",
-"K  c #92A0AE",
-"L  c #94A2B1",
-"P  c #99A6B5",
-"I  c #9AA8B7",
-"U  c #9CAABA",
-"Y  c #A3A3A3",
-"T  c gray67",
-"R  c #A0AEBD",
-"E  c #A2B0BF",
-"W  c #B3B3B3",
-"Q  c gray74",
-"!  c #A4B3C2",
-"~  c #A8B6C5",
-"^  c #AAB8C7",
-"/  c #ADBBCA",
-"(  c #B1BFCE",
-")  c #B3C0CF",
-"_  c #B4C2D1",
-"`  c #B8C6D5",
-"'  c #BAC8D7",
-"]  c #BCCAD9",
-"[  c #C2C2C2",
-"{  c #CBCBCB",
-"}  c #C1CFDE",
-"|  c #D3D3D3",
-" . c #DBDBDB",
-".. c #C4D3E2",
-"X. c #C8D6E5",
-"o. c #CCDAEA",
-"O. c #D0DEED",
-"+. c #D2E0EF",
-"@. c #D2E1F0",
-"#. c #E3E3E3",
-"$. c #ECECEC",
-"%. c #F3F3F3",
-"&. c #FEFEFE",
-"*. c None",
-/* pixels */
-"*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
-"*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
-"*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
-"*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
-"*.*.*.*.*.*.*.*.*.r q q q 0 0 *.*.*.*.0 q q q *.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
-"*.*.*.*.*.*.*.*.0 f &.#.[ C q q q 0 0 q #. .f q 0 *.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
-"*.*.*.*.*.*.*.*.0 Y &.&.&.&.&.%.{ D y r C Y  .| y q 0 *.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
-"*.*.*.*.*.*.*.*.r | &.&.[ T %.&.&.&.$.%. .T z q z C r q 0 *.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
-"*.*.*.*.*.*.*.*.q %.&.&.S ; X , f D  .&.&.&.$.%.#.Q C q q 0 0 4 *.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
-"*.*.*.*.*.*.*.q y &.&.&.D { $.D y $ S &.&.&.#.Q [ %.&.&.$.[ C r q 0 4 4 *.*.*.*.*.*.*.*.*.*.*.*.",
-"*.*.*.*.*.*.*.0 S &.&.T X X o , C Q +  .&.0 z %. .T W $.&.&.&.%.#.{ D y 0 0 4 4 *.*.*.*.*.*.*.*.",
-"*.*.q 0 0 0 q 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 4 0 4 0 Z  .%.&. .Y 0 4 *.*.*.*.*.*.*.",
-"*.*.q &.&.&.&.%.&.&.&.$.$.$.$.$.$.$.&.$.%.&.%.$.&.%.$.&.&.&.&.&.%.0 &.| { $.&.0 4 *.*.*.*.*.*.*.",
-"*.*.0 &.&.&.&. .&.&.&.| | | | | | | &. .#.$.$.| #.%. . .&.&.$.$.%.4 &.&.&. . .0 *.*.*.*.*.*.*.*.",
-"*.*.q &.&.&.D C C C C Z Q | { T Q | &.T | $.$. .$.$.Q | %.&.%. .%.4 $.&.&.&.| r q 4 *.*.*.*.*.*.",
-"*.*.0 &.&.&.$.%.&.&.$.[ Z Q | Q Z [ $.[ Z | $.| $.$.C | %.&.&. .&.4 W &.&.&.D W  .h 0 0 *.*.*.*.",
-"*.*.0 &.&.&.Z C C C C Q ( Z Q | Q Z {  .| S {  .$.%.C | &.&.&.| &.4 Y %.&.&.y  .&.&.| y 0 0 *.*.",
-"*.*.0 &.&.&.C C C C C C Q Q Z | | { Z #.$.| Z  .$.&.C #.&.&.$. .&.4 [ | &.%.q $.&.&.&.&.{ r 0 0 ",
-"*.*.0 &.&.%.C C C C C C C | C { |  .C  .#.$.C #.%.&.C $.&.&. .$.&.4  .Q &. .h q z &.&.&.&.&.W 0 ",
-"*.*.0 &.&.%.C C C C C C C | C | |  .C #. .| C  .$.$.C %.&.&.| %.&.4 Q { &.T x o #.&.&.&.&.&.$.0 ",
-"*.*.0 &.&.#.C C C C C C C { C | | { f x q q 0 T | | C  .$.$.| &.&.4 T &.&.h 4 f &.&.&.&.&.&.C 4 ",
-"*.*.0 &.&.#.C C C C C C C | C Q 0       $ @       0 z #. . .| %.&.4 | &.&.0 + %.&.&.&.&.&.$.0 4 ",
-"*.*.0 &.%.#.C C C C C C C | r O o i s ) ..( m J j X X Y $. . .| &.4 &.&. .0 z &.&.&.&.&.&.z 4 *.",
-"*.*.0 &.$.$.C C C C C C C 4   * b V A V A V A V V b *   r |  .| %.3 &.&.W > &.&.&.&.&.&. .0 4 *.",
-"*.*.0 &.#.&.x r 0 3 3 , ;   2 _ X...V ..X.] V X...( V w   C #. .%.4 | &.h h &.&.&.&.&.&.f 4 *.*.",
-"*.*.4 &. .&.X             # 1 v ] H n ~ X.~ V / +.! V ! * o { | &.3 Q $.4 $.&.&.&.&.&. .0 *.*.*.",
-"*.*.0 &.[ &.              u 1 c / n 1 N ..L n ~ @.^ V ! b o 0 [ &.4 &.| 4 { &.&.&.&.&.r 4 *.*.*.",
-"*.*.0 &.| &.            # c 1 v K n 1 m ( V 5 V @.U d I i j   Q &.3 { T 0 h &.&.&.&.{ 0 *.*.*.*.",
-"*.*.4 %.$.&.            = H v U K ~ V E K ~ K ] ( o.K o.1 K   T &.4 | z 4 C &.&.&.&.r 4 *.*.*.*.",
-"*.*.0 %.&.&.            - K I L K ' ] U K ` +.E K ] +.] 1 '   C &.3 $.0 + #.&.&.&.[ 4 *.*.*.*.*.",
-"*.*.0 %.&.&.          . 1 K L U ~ ] ] K L o.O.K K } +.P 1 ` + r &.4 $.4 f &.&.&.&.q 4 *.*.*.*.*.",
-"*.*.4 %.&.%.          . 1 E V H L R N K ' o.H H I X.G H 1 ( + r &.3 { , $.&.&.&.W 4 *.*.*.*.*.*.",
-"*.*.4 &.&.$.            - M 1 c o.m 1 k L c 1 k ' V 5 d 1 H   C &.3 Z y &.&.&.&.0 3 *.*.*.*.*.*.",
-"*.*.4 &.&.&.            = d 5 n ] m 1 k o.v 1 d L d 5 c 1 M   Y &.3 q { &.&.&.T 4 *.*.*.*.*.*.*.",
-"*.*.4 &.&.&.            # N - V +.F 1 n +.F 1 k ' B - i 5 ; . y #.3 4 &.&.&.%.4 4 *.*.*.*.*.*.*.",
-"*.*.4 %.$.%.              p 5 o.O.o.1 X.+.] 1 ! / ' c 5 9 X : $ o + y &.&.&.D 4 *.*.*.*.*.*.*.*.",
-"*.*.4 &.| [               & 5 - 1 1 1 1 1 1 1 1 5 - 6 i . @ 2 2 2 # X 4 [ %.4 4 *.*.*.*.*.*.*.*.",
-"*.*.4 &.&.&.o         X h   % o.@.@.1 @.+.+.7 E O.' ! e   X $ < 2 2 2 * o ; ; *.*.*.*.*.*.*.*.*.",
-"*.*.4 &.&.&.&.&.&.&.&.$.S     < P } 1 @.@.@.^ 9 ! _ <   y { f o $ , 2 2 2 * X     *.*.*.*.*.*.*.",
-"*.*.4 &.&.&.f           o T Z o X t e L _ ..' B %           x $.x X @ : 2 2 < ; .       *.*.*.*.",
-"*.*.4 &.&.&.&.&.&.&.&.&.&.&.&. .3       + @       0 | &.&.%.%.&.%.2 x + O : 2 2 2 : o     *.*.*.",
-"*.*.4 &.&.&.&.&.&.&.&.&.&.&.&.&.&.$.Y h 4 4 f Y  . .{ Q [  .#.$.%.3 &.z + . o * 2 2 2 : X   *.*.",
-"*.*.4 &.&.&.&.&.&.&.&.&.&.&.&.&.&.&.&.&.&.&.&.&.%.&.&.&.&.%.%.%.$.4  .4 3       X ; 2 2 @   *.*.",
-"*.*.0 4 4 4 4 3 4 4 3 4 4 3 4 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 Z f 3 *.*.*.*.    . @     *.*.",
-"*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.3 4 q { &.&.&. .4 *.*.*.*.*.*.*.      *.*.*.",
-"*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.3 3 r | &.r 3 *.*.*.*.*.*.*.*.*.*.*.*.*.",
-"*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.3 4 3 4 *.*.*.*.*.*.*.*.*.*.*.*.*.*.",
-"*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.2 *.*.*.*.*.*.*.*.*.*.*.*.*.*.*."
+static char* gerbv_icon_xpm[] = {
+    /* columns rows colors chars-per-pixel */
+    "48 48 104 2", "   c #000000", ".  c #050709", "X  c #070808", "o  c #090A0A", "O  c #0E0F10", "+  c #121313",
+    "@  c #151618", "#  c #13181C", "$  c #191B1C", "%  c #151C23", "&  c #191C20", "*  c #1E2124", "=  c #19232E",
+    "-  c #1F2C3A", ";  c #232425", ":  c #222628", ">  c #24292B", ",  c #2A2B2C", "<  c #292F31", "1  c #22303F",
+    "2  c #2D3335", "3  c #343434", "4  c #3B3B3B", "5  c #273544", "6  c #293746", "7  c #2D3B4A", "8  c #323940",
+    "9  c #333E4B", "0  c #434343", "q  c #4B4B4B", "w  c #495057", "e  c #49525B", "r  c #535353", "t  c #50575E",
+    "y  c #5A5A5A", "u  c #4D5966", "i  c #515F6E", "p  c #56626F", "a  c #596067", "s  c #5C6671", "d  c #5D6B7A",
+    "f  c #636363", "g  c #61686F", "h  c #6B6B6B", "j  c #646B72", "k  c #616F7E", "l  c #62707F", "z  c #737373",
+    "x  c #7D7D7D", "c  c #657382", "v  c #697786", "b  c #6D7986", "n  c #6D7B8A", "m  c #717F8E", "M  c #74808E",
+    "N  c #748392", "B  c #798593", "V  c #7E8C9B", "C  c #848484", "Z  c #8A8A8A", "A  c #81909F", "S  c #949494",
+    "D  c #9A9A9A", "F  c #8392A1", "G  c #8896A5", "H  c #8D9BAA", "J  c #919DAB", "K  c #92A0AE", "L  c #94A2B1",
+    "P  c #99A6B5", "I  c #9AA8B7", "U  c #9CAABA", "Y  c #A3A3A3", "T  c gray67", "R  c #A0AEBD", "E  c #A2B0BF",
+    "W  c #B3B3B3", "Q  c gray74", "!  c #A4B3C2", "~  c #A8B6C5", "^  c #AAB8C7", "/  c #ADBBCA", "(  c #B1BFCE",
+    ")  c #B3C0CF", "_  c #B4C2D1", "`  c #B8C6D5", "'  c #BAC8D7", "]  c #BCCAD9", "[  c #C2C2C2", "{  c #CBCBCB",
+    "}  c #C1CFDE", "|  c #D3D3D3", " . c #DBDBDB", ".. c #C4D3E2", "X. c #C8D6E5", "o. c #CCDAEA", "O. c #D0DEED",
+    "+. c #D2E0EF", "@. c #D2E1F0", "#. c #E3E3E3", "$. c #ECECEC", "%. c #F3F3F3", "&. c #FEFEFE", "*. c None",
+    /* pixels */
+    "*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
+    "*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
+    "*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
+    "*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
+    "*.*.*.*.*.*.*.*.*.r q q q 0 0 *.*.*.*.0 q q q *.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
+    "*.*.*.*.*.*.*.*.0 f &.#.[ C q q q 0 0 q #. .f q 0 *.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
+    "*.*.*.*.*.*.*.*.0 Y &.&.&.&.&.%.{ D y r C Y  .| y q 0 *.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
+    "*.*.*.*.*.*.*.*.r | &.&.[ T %.&.&.&.$.%. .T z q z C r q 0 *.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
+    "*.*.*.*.*.*.*.*.q %.&.&.S ; X , f D  .&.&.&.$.%.#.Q C q q 0 0 4 *.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.",
+    "*.*.*.*.*.*.*.q y &.&.&.D { $.D y $ S &.&.&.#.Q [ %.&.&.$.[ C r q 0 4 4 *.*.*.*.*.*.*.*.*.*.*.*.",
+    "*.*.*.*.*.*.*.0 S &.&.T X X o , C Q +  .&.0 z %. .T W $.&.&.&.%.#.{ D y 0 0 4 4 *.*.*.*.*.*.*.*.",
+    "*.*.q 0 0 0 q 0 0 0 0 0 0 0 0 0 0 0 4 0 0 0 0 0 0 0 0 0 0 4 0 4 0 Z  .%.&. .Y 0 4 *.*.*.*.*.*.*.",
+    "*.*.q &.&.&.&.%.&.&.&.$.$.$.$.$.$.$.&.$.%.&.%.$.&.%.$.&.&.&.&.&.%.0 &.| { $.&.0 4 *.*.*.*.*.*.*.",
+    "*.*.0 &.&.&.&. .&.&.&.| | | | | | | &. .#.$.$.| #.%. . .&.&.$.$.%.4 &.&.&. . .0 *.*.*.*.*.*.*.*.",
+    "*.*.q &.&.&.D C C C C Z Q | { T Q | &.T | $.$. .$.$.Q | %.&.%. .%.4 $.&.&.&.| r q 4 *.*.*.*.*.*.",
+    "*.*.0 &.&.&.$.%.&.&.$.[ Z Q | Q Z [ $.[ Z | $.| $.$.C | %.&.&. .&.4 W &.&.&.D W  .h 0 0 *.*.*.*.",
+    "*.*.0 &.&.&.Z C C C C Q ( Z Q | Q Z {  .| S {  .$.%.C | &.&.&.| &.4 Y %.&.&.y  .&.&.| y 0 0 *.*.",
+    "*.*.0 &.&.&.C C C C C C Q Q Z | | { Z #.$.| Z  .$.&.C #.&.&.$. .&.4 [ | &.%.q $.&.&.&.&.{ r 0 0 ",
+    "*.*.0 &.&.%.C C C C C C C | C { |  .C  .#.$.C #.%.&.C $.&.&. .$.&.4  .Q &. .h q z &.&.&.&.&.W 0 ",
+    "*.*.0 &.&.%.C C C C C C C | C | |  .C #. .| C  .$.$.C %.&.&.| %.&.4 Q { &.T x o #.&.&.&.&.&.$.0 ",
+    "*.*.0 &.&.#.C C C C C C C { C | | { f x q q 0 T | | C  .$.$.| &.&.4 T &.&.h 4 f &.&.&.&.&.&.C 4 ",
+    "*.*.0 &.&.#.C C C C C C C | C Q 0       $ @       0 z #. . .| %.&.4 | &.&.0 + %.&.&.&.&.&.$.0 4 ",
+    "*.*.0 &.%.#.C C C C C C C | r O o i s ) ..( m J j X X Y $. . .| &.4 &.&. .0 z &.&.&.&.&.&.z 4 *.",
+    "*.*.0 &.$.$.C C C C C C C 4   * b V A V A V A V V b *   r |  .| %.3 &.&.W > &.&.&.&.&.&. .0 4 *.",
+    "*.*.0 &.#.&.x r 0 3 3 , ;   2 _ X...V ..X.] V X...( V w   C #. .%.4 | &.h h &.&.&.&.&.&.f 4 *.*.",
+    "*.*.4 &. .&.X             # 1 v ] H n ~ X.~ V / +.! V ! * o { | &.3 Q $.4 $.&.&.&.&.&. .0 *.*.*.",
+    "*.*.0 &.[ &.              u 1 c / n 1 N ..L n ~ @.^ V ! b o 0 [ &.4 &.| 4 { &.&.&.&.&.r 4 *.*.*.",
+    "*.*.0 &.| &.            # c 1 v K n 1 m ( V 5 V @.U d I i j   Q &.3 { T 0 h &.&.&.&.{ 0 *.*.*.*.",
+    "*.*.4 %.$.&.            = H v U K ~ V E K ~ K ] ( o.K o.1 K   T &.4 | z 4 C &.&.&.&.r 4 *.*.*.*.",
+    "*.*.0 %.&.&.            - K I L K ' ] U K ` +.E K ] +.] 1 '   C &.3 $.0 + #.&.&.&.[ 4 *.*.*.*.*.",
+    "*.*.0 %.&.&.          . 1 K L U ~ ] ] K L o.O.K K } +.P 1 ` + r &.4 $.4 f &.&.&.&.q 4 *.*.*.*.*.",
+    "*.*.4 %.&.%.          . 1 E V H L R N K ' o.H H I X.G H 1 ( + r &.3 { , $.&.&.&.W 4 *.*.*.*.*.*.",
+    "*.*.4 &.&.$.            - M 1 c o.m 1 k L c 1 k ' V 5 d 1 H   C &.3 Z y &.&.&.&.0 3 *.*.*.*.*.*.",
+    "*.*.4 &.&.&.            = d 5 n ] m 1 k o.v 1 d L d 5 c 1 M   Y &.3 q { &.&.&.T 4 *.*.*.*.*.*.*.",
+    "*.*.4 &.&.&.            # N - V +.F 1 n +.F 1 k ' B - i 5 ; . y #.3 4 &.&.&.%.4 4 *.*.*.*.*.*.*.",
+    "*.*.4 %.$.%.              p 5 o.O.o.1 X.+.] 1 ! / ' c 5 9 X : $ o + y &.&.&.D 4 *.*.*.*.*.*.*.*.",
+    "*.*.4 &.| [               & 5 - 1 1 1 1 1 1 1 1 5 - 6 i . @ 2 2 2 # X 4 [ %.4 4 *.*.*.*.*.*.*.*.",
+    "*.*.4 &.&.&.o         X h   % o.@.@.1 @.+.+.7 E O.' ! e   X $ < 2 2 2 * o ; ; *.*.*.*.*.*.*.*.*.",
+    "*.*.4 &.&.&.&.&.&.&.&.$.S     < P } 1 @.@.@.^ 9 ! _ <   y { f o $ , 2 2 2 * X     *.*.*.*.*.*.*.",
+    "*.*.4 &.&.&.f           o T Z o X t e L _ ..' B %           x $.x X @ : 2 2 < ; .       *.*.*.*.",
+    "*.*.4 &.&.&.&.&.&.&.&.&.&.&.&. .3       + @       0 | &.&.%.%.&.%.2 x + O : 2 2 2 : o     *.*.*.",
+    "*.*.4 &.&.&.&.&.&.&.&.&.&.&.&.&.&.$.Y h 4 4 f Y  . .{ Q [  .#.$.%.3 &.z + . o * 2 2 2 : X   *.*.",
+    "*.*.4 &.&.&.&.&.&.&.&.&.&.&.&.&.&.&.&.&.&.&.&.&.%.&.&.&.&.%.%.%.$.4  .4 3       X ; 2 2 @   *.*.",
+    "*.*.0 4 4 4 4 3 4 4 3 4 4 3 4 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 Z f 3 *.*.*.*.    . @     *.*.",
+    "*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.3 4 q { &.&.&. .4 *.*.*.*.*.*.*.      *.*.*.",
+    "*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.3 3 r | &.r 3 *.*.*.*.*.*.*.*.*.*.*.*.*.",
+    "*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.3 4 3 4 *.*.*.*.*.*.*.*.*.*.*.*.*.*.",
+    "*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.2 *.*.*.*.*.*.*.*.*.*.*.*.*.*.*."
 };
 
-#else 
+#else
 
 /* This is the old icon.  To get it back, just rename it. */
-static char * gerbv_icon_xpm[] = {
-"48 48 244 2",
-"  	c None",
-". 	c #1F8888",
-"+ 	c #000000",
-"@ 	c #2CC2C2",
-"# 	c #37F2F2",
-"$ 	c #000200",
-"% 	c #010401",
-"& 	c #39FEFE",
-"* 	c #040D03",
-"= 	c #071505",
-"- 	c #081806",
-"; 	c #3AFFFF",
-"> 	c #030902",
-", 	c #061505",
-"' 	c #0B2308",
-") 	c #0F300B",
-"! 	c #12380D",
-"~ 	c #1D8383",
-"{ 	c #2BC0C0",
-"] 	c #2AB9B9",
-"^ 	c #155E5E",
-"/ 	c #051717",
-"( 	c #040F03",
-"_ 	c #0C2709",
-": 	c #174811",
-"< 	c #236C1A",
-"[ 	c #2C8721",
-"} 	c #309424",
-"| 	c #020802",
-"1 	c #081A06",
-"2 	c #12370D",
-"3 	c #206318",
-"4 	c #2D8C22",
-"5 	c #35A328",
-"6 	c #37AA29",
-"7 	c #39AF2B",
-"8 	c #38AD2A",
-"9 	c #339D26",
-"0 	c #1D5A16",
-"a 	c #051204",
-"b 	c #0A1F07",
-"c 	c #154310",
-"d 	c #26741C",
-"e 	c #329B26",
-"f 	c #38AC2A",
-"g 	c #1D5916",
-"h 	c #0A2008",
-"i 	c #174611",
-"j 	c #27781D",
-"k 	c #339F27",
-"l 	c #051104",
-"m 	c #091E07",
-"n 	c #143F0F",
-"o 	c #236D1A",
-"p 	c #309624",
-"q 	c #37A929",
-"r 	c #38AE2A",
-"s 	c #020601",
-"t 	c #1C5715",
-"u 	c #297F1F",
-"v 	c #329925",
-"w 	c #35A428",
-"x 	c #030A02",
-"y 	c #133A0E",
-"z 	c #1D5B16",
-"A 	c #26761D",
-"B 	c #2B8520",
-"C 	c #39FCFC",
-"D 	c #061405",
-"E 	c #0D2809",
-"F 	c #15400F",
-"G 	c #1C5615",
-"H 	c #1F6117",
-"I 	c #35EAEA",
-"J 	c #061204",
-"K 	c #133D0F",
-"L 	c #1A5114",
-"M 	c #2ECBCB",
-"N 	c #081B06",
-"O 	c #10320C",
-"P 	c #1B5314",
-"Q 	c #236E1B",
-"R 	c #287B1E",
-"S 	c #37F4F4",
-"T 	c #29B6B6",
-"U 	c #135656",
-"V 	c #0E2B0A",
-"W 	c #194F13",
-"X 	c #2F9123",
-"Y 	c #000202",
-"Z 	c #133B0E",
-"` 	c #226919",
-" .	c #36A628",
-"..	c #000101",
-"+.	c #0A1E07",
-"@.	c #164410",
-"#.	c #216819",
-"$.	c #2F9023",
-"%.	c #37AB2A",
-"&.	c #329C26",
-"*.	c #184912",
-"=.	c #2F9224",
-"-.	c #2E8E23",
-";.	c #010501",
-">.	c #040E03",
-",.	c #0D2A0A",
-"'.	c #12390E",
-").	c #154210",
-"!.	c #1C5815",
-"~.	c #000100",
-"{.	c #030B05",
-"].	c #020701",
-"^.	c #051004",
-"/.	c #050F03",
-"(.	c #010505",
-"_.	c #DD1313",
-":.	c #EA1414",
-"<.	c #E41313",
-"[.	c #DF1313",
-"}.	c #B80F0F",
-"|.	c #460606",
-"1.	c #9F0D0D",
-"2.	c #FF1616",
-"3.	c #F81515",
-"4.	c #E21313",
-"5.	c #DE1313",
-"6.	c #A10E0E",
-"7.	c #B10F0F",
-"8.	c #F91515",
-"9.	c #B51010",
-"0.	c #B91010",
-"a.	c #F01414",
-"b.	c #F11515",
-"c.	c #E11313",
-"d.	c #EE1414",
-"e.	c #C81111",
-"f.	c #F31515",
-"g.	c #ED1414",
-"h.	c #D11212",
-"i.	c #B11010",
-"j.	c #3D0B0B",
-"k.	c #D21313",
-"l.	c #D91313",
-"m.	c #A70F0F",
-"n.	c #E91414",
-"o.	c #F71515",
-"p.	c #F61515",
-"q.	c #A91010",
-"r.	c #090909",
-"s.	c #B81010",
-"t.	c #DA1313",
-"u.	c #DB1313",
-"v.	c #9F0F0F",
-"w.	c #EF1515",
-"x.	c #820D0D",
-"y.	c #9F1010",
-"z.	c #0A0A0A",
-"A.	c #C11212",
-"B.	c #E51414",
-"C.	c #B41010",
-"D.	c #840F0F",
-"E.	c #F51515",
-"F.	c #810D0D",
-"G.	c #950F0F",
-"H.	c #E71414",
-"I.	c #D61313",
-"J.	c #901010",
-"K.	c #C81313",
-"L.	c #7B1111",
-"M.	c #DE1414",
-"N.	c #A01010",
-"O.	c #EC1414",
-"P.	c #F11414",
-"Q.	c #991010",
-"R.	c #E41414",
-"S.	c #931010",
-"T.	c #DD1414",
-"U.	c #C41212",
-"V.	c #0B0B0B",
-"W.	c #8A1010",
-"X.	c #0E0E0E",
-"Y.	c #7A1111",
-"Z.	c #450C0C",
-"`.	c #490C0C",
-" +	c #880E0E",
-".+	c #400C0C",
-"++	c #E31414",
-"@+	c #E11414",
-"#+	c #821111",
-"$+	c #7F1111",
-"%+	c #801111",
-"&+	c #831111",
-"*+	c #851111",
-"=+	c #3E0E0E",
-"-+	c #D71414",
-";+	c #0C0C0C",
-">+	c #8E1010",
-",+	c #791111",
-"'+	c #BD1313",
-")+	c #BF1313",
-"!+	c #D31414",
-"~+	c #6C0F0F",
-"{+	c #AB1111",
-"]+	c #EE1515",
-"^+	c #941212",
-"/+	c #0F0F0F",
-"(+	c #0D0D0D",
-"_+	c #611010",
-":+	c #3D0E0E",
-"<+	c #D51414",
-"[+	c #881111",
-"}+	c #370E0E",
-"|+	c #B31212",
-"1+	c #A51111",
-"2+	c #E01414",
-"3+	c #A51212",
-"4+	c #861111",
-"5+	c #380E0E",
-"6+	c #891111",
-"7+	c #D61414",
-"8+	c #8B1111",
-"9+	c #AC1010",
-"0+	c #390D0D",
-"a+	c #D51313",
-"b+	c #840E0E",
-"c+	c #AF1212",
-"d+	c #871010",
-"e+	c #3A0D0D",
-"f+	c #5C1010",
-"g+	c #B01313",
-"h+	c #C81414",
-"i+	c #C91414",
-"j+	c #CC1414",
-"k+	c #400E0E",
-"l+	c #D81414",
-"m+	c #6F0F0F",
-"n+	c #E21414",
-"o+	c #AF1111",
-"p+	c #A11111",
-"q+	c #CB1313",
-"r+	c #B51212",
-"s+	c #610F0F",
-"t+	c #9A1010",
-"u+	c #A41111",
-"                                                                                                ",
-"                                                                                                ",
-"                                                                                                ",
-"                                                                                                ",
-"                                                                      .                         ",
-"            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @ + + + + +               ",
-"            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # + + + + + +             ",
-"            + + + + + + + + + + + + + + $ % % % % $ + + + + + + + + + & + + + + + +             ",
-"            + + + + + + + + + + + + $ % * = - - = * % $ + + + + + + + ; + + + + + +             ",
-"            + + + + + + + + + + + $ > , ' ) ! ! ) ' , > $ + + + + + + ; + + + + + + +           ",
-"          ~ { # & ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; & # ] ^ /           ",
-"          + + + + + + + + + + + $ ( _ : < [ } } [ < : _ ( $ + + + + + ; + + + + + + +           ",
-"          + + + + + + + + + + + | 1 2 3 4 5 6 6 5 4 3 2 1 | + + + + 7 ; 7 7 8 9 0 a + +         ",
-"          + + + + + + + + + + + > b c d e f 7 7 7 7 7 7 7 7 7 7 7 7 7 ; 7 7 8 9 g a + +         ",
-"          + + + + + + + + + + + > h i j k f 7 7 7 7 7 7 7 7 7 7 7 7 7 ; 7 7 8 9 g l + +         ",
-"          + + + + + + + + + + + > m n o p q r 7 7 7 7 7 7 7 7 7 7 7 7 ; + + + + + + + +         ",
-"          + + + + + + + + + + + s = ) t u v w w v u t ) = s + + + + + ; + + + + + + + +         ",
-"          + + + + + + + + + + + + x b y z A B B A z y b x + + + + + + C + + + + + + + +         ",
-"          + + # + ; + ; + ; + + + % D E F G H H G F E D % + + + + + + I + + + + + + + +         ",
-"          + + + + + + + + + + + + % J _ K L z z L K _ J % + + + + + + M + + + + + + + +         ",
-"          + + # + ; + ; + ; + + + x N O P Q R R Q P O N x + + + + + + ] S ; & # T U + +         ",
-"          + + + + + + + + + + + % l V W A X 9 9 X A W V l % + + Y + + + + + + + + + + +         ",
-"          + + + + + + ; + ; + + | N Z ` X  .f f  .X ` Z N | + + ..+ + + + + + + + + + +         ",
-"          + + + + + + + + + + + | +.@.A 9 f 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 + + + + + +         ",
-"          + + + + + + ; + ; + + | +.@.A 9 f 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 + + + + +         ",
-"          + + + + + + + + + + + | N Z #.$. .%.%.r r 8 8 8 8 8 8 8 8 8 8 8 8 f &.+ + + +         ",
-"            + + + + + # + # + + % l _ *.< B =.=.B < *._ l % + + + + + + 9 9 &.-.+ + + +         ",
-"            + + + + + + + + + + + ;.>.1 ,.'.).).'.,.1 >.;.+ + + + + + + !.!.!.L + + +           ",
-"              + + + + + + + + + + + ~.$ % s {.].s % $ ~.+ + + + + + + + + ^.^./.+ + +           ",
-"                + + + + + + + + + + + + + (...+ + + + + + + + + + + + + + + + + + + +           ",
-"                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +             ",
-"                      + + + + + + + + + + + + + + + + + + + + + + + + + + + +                   ",
-"            _.:.<.[.}.|.                                1.2.2.                                  ",
-"          2.2.3.4.5.2.6.                                7.2.2.                                  ",
-"        8.2.9.                                          0.2.2.                                  ",
-"      a.2.b.                c.d.d.e.      <.f.    d.g.h.i.2.2.j.k.l.m.    a.n.        o.        ",
-"      p.2.q.  r.          2.b.s.t.2.u.    d.2.8.2.2.2.c.v.2.2.w.2.2.2.x.  2.2.5.      3.        ",
-"      f.2.y.z.z.  A.B.C.2.o.D.    2.E.F.  B.2.2.t.G.H.I.J.2.2.K.L.M.2.B.  N.2.O.    b.c.        ",
-"      P.2.Q.z.z.  R.2.R.2.2.2.2.2.2.2.S.  T.2.U.V.V.V.V.W.2.2.X.X.Y.2.2.V.z.2.2.Z.`.2. +        ",
-"      5.2.2..+z.  ++2.M.2.@+#+$+%+&+*+=+V.-+2.W.;+;+V.z.>+2.2.X.X.,+2.2.;+V.k.2.'+)+f.          ",
-"        w.2.!+~+  M.2.{+2.]+^+/+X.(+_+:+;+<+2.[+;+V.z.  Q.2.2.}+(+K.2.|+;+V.1+2.2.2+3+V.        ",
-"          2.2.2.2.2.2.4+5+2.2.2.2.2.2.6+(+7+2.8+;+z.    9+2.2.2.2.2.2.0+;+z.r.a+2.2.;+;+        ",
-"          b+c+!+k.k.d+e+(+f+g+h+i+j+4+k+  |+l+m+V.        n+o+p+q+r+s+V.V.r.  t+I.u+V.z.        ",
-"                V.V.V.V.;+;+;+;+;+V.V.V.                      z.V.V.V.z.            z.          ",
-"                                                                                                ",
-"                                                                                                ",
-"                                                                                                ",
-"                                                                                                "};
+static char* gerbv_icon_xpm[] = {
+    "48 48 244 2",
+    "  	c None",
+    ". 	c #1F8888",
+    "+ 	c #000000",
+    "@ 	c #2CC2C2",
+    "# 	c #37F2F2",
+    "$ 	c #000200",
+    "% 	c #010401",
+    "& 	c #39FEFE",
+    "* 	c #040D03",
+    "= 	c #071505",
+    "- 	c #081806",
+    "; 	c #3AFFFF",
+    "> 	c #030902",
+    ", 	c #061505",
+    "' 	c #0B2308",
+    ") 	c #0F300B",
+    "! 	c #12380D",
+    "~ 	c #1D8383",
+    "{ 	c #2BC0C0",
+    "] 	c #2AB9B9",
+    "^ 	c #155E5E",
+    "/ 	c #051717",
+    "( 	c #040F03",
+    "_ 	c #0C2709",
+    ": 	c #174811",
+    "< 	c #236C1A",
+    "[ 	c #2C8721",
+    "} 	c #309424",
+    "| 	c #020802",
+    "1 	c #081A06",
+    "2 	c #12370D",
+    "3 	c #206318",
+    "4 	c #2D8C22",
+    "5 	c #35A328",
+    "6 	c #37AA29",
+    "7 	c #39AF2B",
+    "8 	c #38AD2A",
+    "9 	c #339D26",
+    "0 	c #1D5A16",
+    "a 	c #051204",
+    "b 	c #0A1F07",
+    "c 	c #154310",
+    "d 	c #26741C",
+    "e 	c #329B26",
+    "f 	c #38AC2A",
+    "g 	c #1D5916",
+    "h 	c #0A2008",
+    "i 	c #174611",
+    "j 	c #27781D",
+    "k 	c #339F27",
+    "l 	c #051104",
+    "m 	c #091E07",
+    "n 	c #143F0F",
+    "o 	c #236D1A",
+    "p 	c #309624",
+    "q 	c #37A929",
+    "r 	c #38AE2A",
+    "s 	c #020601",
+    "t 	c #1C5715",
+    "u 	c #297F1F",
+    "v 	c #329925",
+    "w 	c #35A428",
+    "x 	c #030A02",
+    "y 	c #133A0E",
+    "z 	c #1D5B16",
+    "A 	c #26761D",
+    "B 	c #2B8520",
+    "C 	c #39FCFC",
+    "D 	c #061405",
+    "E 	c #0D2809",
+    "F 	c #15400F",
+    "G 	c #1C5615",
+    "H 	c #1F6117",
+    "I 	c #35EAEA",
+    "J 	c #061204",
+    "K 	c #133D0F",
+    "L 	c #1A5114",
+    "M 	c #2ECBCB",
+    "N 	c #081B06",
+    "O 	c #10320C",
+    "P 	c #1B5314",
+    "Q 	c #236E1B",
+    "R 	c #287B1E",
+    "S 	c #37F4F4",
+    "T 	c #29B6B6",
+    "U 	c #135656",
+    "V 	c #0E2B0A",
+    "W 	c #194F13",
+    "X 	c #2F9123",
+    "Y 	c #000202",
+    "Z 	c #133B0E",
+    "` 	c #226919",
+    " .	c #36A628",
+    "..	c #000101",
+    "+.	c #0A1E07",
+    "@.	c #164410",
+    "#.	c #216819",
+    "$.	c #2F9023",
+    "%.	c #37AB2A",
+    "&.	c #329C26",
+    "*.	c #184912",
+    "=.	c #2F9224",
+    "-.	c #2E8E23",
+    ";.	c #010501",
+    ">.	c #040E03",
+    ",.	c #0D2A0A",
+    "'.	c #12390E",
+    ").	c #154210",
+    "!.	c #1C5815",
+    "~.	c #000100",
+    "{.	c #030B05",
+    "].	c #020701",
+    "^.	c #051004",
+    "/.	c #050F03",
+    "(.	c #010505",
+    "_.	c #DD1313",
+    ":.	c #EA1414",
+    "<.	c #E41313",
+    "[.	c #DF1313",
+    "}.	c #B80F0F",
+    "|.	c #460606",
+    "1.	c #9F0D0D",
+    "2.	c #FF1616",
+    "3.	c #F81515",
+    "4.	c #E21313",
+    "5.	c #DE1313",
+    "6.	c #A10E0E",
+    "7.	c #B10F0F",
+    "8.	c #F91515",
+    "9.	c #B51010",
+    "0.	c #B91010",
+    "a.	c #F01414",
+    "b.	c #F11515",
+    "c.	c #E11313",
+    "d.	c #EE1414",
+    "e.	c #C81111",
+    "f.	c #F31515",
+    "g.	c #ED1414",
+    "h.	c #D11212",
+    "i.	c #B11010",
+    "j.	c #3D0B0B",
+    "k.	c #D21313",
+    "l.	c #D91313",
+    "m.	c #A70F0F",
+    "n.	c #E91414",
+    "o.	c #F71515",
+    "p.	c #F61515",
+    "q.	c #A91010",
+    "r.	c #090909",
+    "s.	c #B81010",
+    "t.	c #DA1313",
+    "u.	c #DB1313",
+    "v.	c #9F0F0F",
+    "w.	c #EF1515",
+    "x.	c #820D0D",
+    "y.	c #9F1010",
+    "z.	c #0A0A0A",
+    "A.	c #C11212",
+    "B.	c #E51414",
+    "C.	c #B41010",
+    "D.	c #840F0F",
+    "E.	c #F51515",
+    "F.	c #810D0D",
+    "G.	c #950F0F",
+    "H.	c #E71414",
+    "I.	c #D61313",
+    "J.	c #901010",
+    "K.	c #C81313",
+    "L.	c #7B1111",
+    "M.	c #DE1414",
+    "N.	c #A01010",
+    "O.	c #EC1414",
+    "P.	c #F11414",
+    "Q.	c #991010",
+    "R.	c #E41414",
+    "S.	c #931010",
+    "T.	c #DD1414",
+    "U.	c #C41212",
+    "V.	c #0B0B0B",
+    "W.	c #8A1010",
+    "X.	c #0E0E0E",
+    "Y.	c #7A1111",
+    "Z.	c #450C0C",
+    "`.	c #490C0C",
+    " +	c #880E0E",
+    ".+	c #400C0C",
+    "++	c #E31414",
+    "@+	c #E11414",
+    "#+	c #821111",
+    "$+	c #7F1111",
+    "%+	c #801111",
+    "&+	c #831111",
+    "*+	c #851111",
+    "=+	c #3E0E0E",
+    "-+	c #D71414",
+    ";+	c #0C0C0C",
+    ">+	c #8E1010",
+    ",+	c #791111",
+    "'+	c #BD1313",
+    ")+	c #BF1313",
+    "!+	c #D31414",
+    "~+	c #6C0F0F",
+    "{+	c #AB1111",
+    "]+	c #EE1515",
+    "^+	c #941212",
+    "/+	c #0F0F0F",
+    "(+	c #0D0D0D",
+    "_+	c #611010",
+    ":+	c #3D0E0E",
+    "<+	c #D51414",
+    "[+	c #881111",
+    "}+	c #370E0E",
+    "|+	c #B31212",
+    "1+	c #A51111",
+    "2+	c #E01414",
+    "3+	c #A51212",
+    "4+	c #861111",
+    "5+	c #380E0E",
+    "6+	c #891111",
+    "7+	c #D61414",
+    "8+	c #8B1111",
+    "9+	c #AC1010",
+    "0+	c #390D0D",
+    "a+	c #D51313",
+    "b+	c #840E0E",
+    "c+	c #AF1212",
+    "d+	c #871010",
+    "e+	c #3A0D0D",
+    "f+	c #5C1010",
+    "g+	c #B01313",
+    "h+	c #C81414",
+    "i+	c #C91414",
+    "j+	c #CC1414",
+    "k+	c #400E0E",
+    "l+	c #D81414",
+    "m+	c #6F0F0F",
+    "n+	c #E21414",
+    "o+	c #AF1111",
+    "p+	c #A11111",
+    "q+	c #CB1313",
+    "r+	c #B51212",
+    "s+	c #610F0F",
+    "t+	c #9A1010",
+    "u+	c #A41111",
+    "                                                                                                ",
+    "                                                                                                ",
+    "                                                                                                ",
+    "                                                                                                ",
+    "                                                                      .                         ",
+    "            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @ + + + + +               ",
+    "            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # + + + + + +             ",
+    "            + + + + + + + + + + + + + + $ % % % % $ + + + + + + + + + & + + + + + +             ",
+    "            + + + + + + + + + + + + $ % * = - - = * % $ + + + + + + + ; + + + + + +             ",
+    "            + + + + + + + + + + + $ > , ' ) ! ! ) ' , > $ + + + + + + ; + + + + + + +           ",
+    "          ~ { # & ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; & # ] ^ /           ",
+    "          + + + + + + + + + + + $ ( _ : < [ } } [ < : _ ( $ + + + + + ; + + + + + + +           ",
+    "          + + + + + + + + + + + | 1 2 3 4 5 6 6 5 4 3 2 1 | + + + + 7 ; 7 7 8 9 0 a + +         ",
+    "          + + + + + + + + + + + > b c d e f 7 7 7 7 7 7 7 7 7 7 7 7 7 ; 7 7 8 9 g a + +         ",
+    "          + + + + + + + + + + + > h i j k f 7 7 7 7 7 7 7 7 7 7 7 7 7 ; 7 7 8 9 g l + +         ",
+    "          + + + + + + + + + + + > m n o p q r 7 7 7 7 7 7 7 7 7 7 7 7 ; + + + + + + + +         ",
+    "          + + + + + + + + + + + s = ) t u v w w v u t ) = s + + + + + ; + + + + + + + +         ",
+    "          + + + + + + + + + + + + x b y z A B B A z y b x + + + + + + C + + + + + + + +         ",
+    "          + + # + ; + ; + ; + + + % D E F G H H G F E D % + + + + + + I + + + + + + + +         ",
+    "          + + + + + + + + + + + + % J _ K L z z L K _ J % + + + + + + M + + + + + + + +         ",
+    "          + + # + ; + ; + ; + + + x N O P Q R R Q P O N x + + + + + + ] S ; & # T U + +         ",
+    "          + + + + + + + + + + + % l V W A X 9 9 X A W V l % + + Y + + + + + + + + + + +         ",
+    "          + + + + + + ; + ; + + | N Z ` X  .f f  .X ` Z N | + + ..+ + + + + + + + + + +         ",
+    "          + + + + + + + + + + + | +.@.A 9 f 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 + + + + + +         ",
+    "          + + + + + + ; + ; + + | +.@.A 9 f 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 7 8 + + + + +         ",
+    "          + + + + + + + + + + + | N Z #.$. .%.%.r r 8 8 8 8 8 8 8 8 8 8 8 8 f &.+ + + +         ",
+    "            + + + + + # + # + + % l _ *.< B =.=.B < *._ l % + + + + + + 9 9 &.-.+ + + +         ",
+    "            + + + + + + + + + + + ;.>.1 ,.'.).).'.,.1 >.;.+ + + + + + + !.!.!.L + + +           ",
+    "              + + + + + + + + + + + ~.$ % s {.].s % $ ~.+ + + + + + + + + ^.^./.+ + +           ",
+    "                + + + + + + + + + + + + + (...+ + + + + + + + + + + + + + + + + + + +           ",
+    "                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +             ",
+    "                      + + + + + + + + + + + + + + + + + + + + + + + + + + + +                   ",
+    "            _.:.<.[.}.|.                                1.2.2.                                  ",
+    "          2.2.3.4.5.2.6.                                7.2.2.                                  ",
+    "        8.2.9.                                          0.2.2.                                  ",
+    "      a.2.b.                c.d.d.e.      <.f.    d.g.h.i.2.2.j.k.l.m.    a.n.        o.        ",
+    "      p.2.q.  r.          2.b.s.t.2.u.    d.2.8.2.2.2.c.v.2.2.w.2.2.2.x.  2.2.5.      3.        ",
+    "      f.2.y.z.z.  A.B.C.2.o.D.    2.E.F.  B.2.2.t.G.H.I.J.2.2.K.L.M.2.B.  N.2.O.    b.c.        ",
+    "      P.2.Q.z.z.  R.2.R.2.2.2.2.2.2.2.S.  T.2.U.V.V.V.V.W.2.2.X.X.Y.2.2.V.z.2.2.Z.`.2. +        ",
+    "      5.2.2..+z.  ++2.M.2.@+#+$+%+&+*+=+V.-+2.W.;+;+V.z.>+2.2.X.X.,+2.2.;+V.k.2.'+)+f.          ",
+    "        w.2.!+~+  M.2.{+2.]+^+/+X.(+_+:+;+<+2.[+;+V.z.  Q.2.2.}+(+K.2.|+;+V.1+2.2.2+3+V.        ",
+    "          2.2.2.2.2.2.4+5+2.2.2.2.2.2.6+(+7+2.8+;+z.    9+2.2.2.2.2.2.0+;+z.r.a+2.2.;+;+        ",
+    "          b+c+!+k.k.d+e+(+f+g+h+i+j+4+k+  |+l+m+V.        n+o+p+q+r+s+V.V.r.  t+I.u+V.z.        ",
+    "                V.V.V.V.;+;+;+;+;+V.V.V.                      z.V.V.V.z.            z.          ",
+    "                                                                                                ",
+    "                                                                                                ",
+    "                                                                                                ",
+    "                                                                                                "
+};
 
 #endif
diff --git a/src/gettext.h b/src/gettext.h
index e76b592..f71e855 100644
--- a/src/gettext.h
+++ b/src/gettext.h
@@ -23,19 +23,17 @@
 #if ENABLE_NLS
 
 /* Get declarations of GNU message catalog functions.  */
-# include <libintl.h>
+#include <libintl.h>
 
 /* You can set the DEFAULT_TEXT_DOMAIN macro to specify the domain used by
    the gettext() and ngettext() macros.  This is an alternative to calling
    textdomain(), and is useful for libraries.  */
-# ifdef DEFAULT_TEXT_DOMAIN
-#  undef gettext
-#  define gettext(Msgid) \
-     dgettext (DEFAULT_TEXT_DOMAIN, Msgid)
-#  undef ngettext
-#  define ngettext(Msgid1, Msgid2, N) \
-     dngettext (DEFAULT_TEXT_DOMAIN, Msgid1, Msgid2, N)
-# endif
+#ifdef DEFAULT_TEXT_DOMAIN
+#undef gettext
+#define gettext(Msgid) dgettext(DEFAULT_TEXT_DOMAIN, Msgid)
+#undef ngettext
+#define ngettext(Msgid1, Msgid2, N) dngettext(DEFAULT_TEXT_DOMAIN, Msgid1, Msgid2, N)
+#endif
 
 #else
 
@@ -46,17 +44,17 @@
    and also including <libintl.h> would fail on SunOS 4, whereas <locale.h>
    is OK.  */
 #if defined(__sun)
-# include <locale.h>
+#include <locale.h>
 #endif
 
 /* Many header files from the libstdc++ coming with g++ 3.3 or newer include
    <libintl.h>, which chokes if dcgettext is defined as a macro.  So include
    it now, to make later inclusions of <libintl.h> a NOP.  */
 #if defined(__cplusplus) && defined(__GNUG__) && (__GNUC__ >= 3)
-# include <cstdlib>
-# if (__GLIBC__ >= 2) || _GLIBCXX_HAVE_LIBINTL_H
-#  include <libintl.h>
-# endif
+#include <cstdlib>
+#if (__GLIBC__ >= 2) || _GLIBCXX_HAVE_LIBINTL_H
+#include <libintl.h>
+#endif
 #endif
 
 /* Disabled NLS.
@@ -64,32 +62,25 @@
    for invalid uses of the value returned from these functions.
    On pre-ANSI systems without 'const', the config.h file is supposed to
    contain "#define const".  */
-# undef gettext
-# define gettext(Msgid) ((const char *) (Msgid))
-# undef dgettext
-# define dgettext(Domainname, Msgid) ((void) (Domainname), gettext (Msgid))
-# undef dcgettext
-# define dcgettext(Domainname, Msgid, Category) \
-    ((void) (Category), dgettext (Domainname, Msgid))
-# undef ngettext
-# define ngettext(Msgid1, Msgid2, N) \
-    ((N) == 1 \
-     ? ((void) (Msgid2), (const char *) (Msgid1)) \
-     : ((void) (Msgid1), (const char *) (Msgid2)))
-# undef dngettext
-# define dngettext(Domainname, Msgid1, Msgid2, N) \
-    ((void) (Domainname), ngettext (Msgid1, Msgid2, N))
-# undef dcngettext
-# define dcngettext(Domainname, Msgid1, Msgid2, N, Category) \
-    ((void) (Category), dngettext(Domainname, Msgid1, Msgid2, N))
-# undef textdomain
-# define textdomain(Domainname) ((const char *) (Domainname))
-# undef bindtextdomain
-# define bindtextdomain(Domainname, Dirname) \
-    ((void) (Domainname), (const char *) (Dirname))
-# undef bind_textdomain_codeset
-# define bind_textdomain_codeset(Domainname, Codeset) \
-    ((void) (Domainname), (const char *) (Codeset))
+#undef gettext
+#define gettext(Msgid) ((const char*)(Msgid))
+#undef dgettext
+#define dgettext(Domainname, Msgid) ((void)(Domainname), gettext(Msgid))
+#undef dcgettext
+#define dcgettext(Domainname, Msgid, Category) ((void)(Category), dgettext(Domainname, Msgid))
+#undef ngettext
+#define ngettext(Msgid1, Msgid2, N) \
+    ((N) == 1 ? ((void)(Msgid2), (const char*)(Msgid1)) : ((void)(Msgid1), (const char*)(Msgid2)))
+#undef dngettext
+#define dngettext(Domainname, Msgid1, Msgid2, N) ((void)(Domainname), ngettext(Msgid1, Msgid2, N))
+#undef dcngettext
+#define dcngettext(Domainname, Msgid1, Msgid2, N, Category) ((void)(Category), dngettext(Domainname, Msgid1, Msgid2, N))
+#undef textdomain
+#define textdomain(Domainname) ((const char*)(Domainname))
+#undef bindtextdomain
+#define bindtextdomain(Domainname, Dirname) ((void)(Domainname), (const char*)(Dirname))
+#undef bind_textdomain_codeset
+#define bind_textdomain_codeset(Domainname, Codeset) ((void)(Domainname), (const char*)(Codeset))
 
 #endif
 
@@ -110,27 +101,26 @@
    short and rarely need to change.
    The letter 'p' stands for 'particular' or 'special'.  */
 #ifdef DEFAULT_TEXT_DOMAIN
-# define pgettext(Msgctxt, Msgid) \
-   pgettext_aux (DEFAULT_TEXT_DOMAIN, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, LC_MESSAGES)
+#define pgettext(Msgctxt, Msgid) \
+    pgettext_aux(DEFAULT_TEXT_DOMAIN, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, LC_MESSAGES)
 #else
-# define pgettext(Msgctxt, Msgid) \
-   pgettext_aux (NULL, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, LC_MESSAGES)
+#define pgettext(Msgctxt, Msgid) pgettext_aux(NULL, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, LC_MESSAGES)
 #endif
 #define dpgettext(Domainname, Msgctxt, Msgid) \
-  pgettext_aux (Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, LC_MESSAGES)
+    pgettext_aux(Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, LC_MESSAGES)
 #define dcpgettext(Domainname, Msgctxt, Msgid, Category) \
-  pgettext_aux (Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, Category)
+    pgettext_aux(Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, Category)
 #ifdef DEFAULT_TEXT_DOMAIN
-# define npgettext(Msgctxt, Msgid, MsgidPlural, N) \
-   npgettext_aux (DEFAULT_TEXT_DOMAIN, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, LC_MESSAGES)
+#define npgettext(Msgctxt, Msgid, MsgidPlural, N) \
+    npgettext_aux(DEFAULT_TEXT_DOMAIN, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, LC_MESSAGES)
 #else
-# define npgettext(Msgctxt, Msgid, MsgidPlural, N) \
-   npgettext_aux (NULL, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, LC_MESSAGES)
+#define npgettext(Msgctxt, Msgid, MsgidPlural, N) \
+    npgettext_aux(NULL, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, LC_MESSAGES)
 #endif
 #define dnpgettext(Domainname, Msgctxt, Msgid, MsgidPlural, N) \
-  npgettext_aux (Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, LC_MESSAGES)
+    npgettext_aux(Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, LC_MESSAGES)
 #define dcnpgettext(Domainname, Msgctxt, Msgid, MsgidPlural, N, Category) \
-  npgettext_aux (Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, Category)
+    npgettext_aux(Domainname, Msgctxt GETTEXT_CONTEXT_GLUE Msgid, Msgid, MsgidPlural, N, Category)
 
 #ifdef __GNUC__
 __inline
@@ -139,16 +129,13 @@ __inline
 inline
 #endif
 #endif
-static const char *
-pgettext_aux (const char *domain,
-              const char *msg_ctxt_id, const char *msgid,
-              int category)
-{
-  const char *translation = dcgettext (domain, msg_ctxt_id, category);
-  if (translation == msg_ctxt_id)
-    return msgid;
-  else
-    return translation;
+    static const char*
+    pgettext_aux(const char* domain, const char* msg_ctxt_id, const char* msgid, int category) {
+    const char* translation = dcgettext(domain, msg_ctxt_id, category);
+    if (translation == msg_ctxt_id)
+        return msgid;
+    else
+        return translation;
 }
 
 #ifdef __GNUC__
@@ -158,18 +145,16 @@ __inline
 inline
 #endif
 #endif
-static const char *
-npgettext_aux (const char *domain,
-               const char *msg_ctxt_id, const char *msgid,
-               const char *msgid_plural, unsigned long int n,
-               int category)
-{
-  const char *translation =
-    dcngettext (domain, msg_ctxt_id, msgid_plural, n, category);
-  if (translation == msg_ctxt_id || translation == msgid_plural)
-    return (n == 1 ? msgid : msgid_plural);
-  else
-    return translation;
+    static const char*
+    npgettext_aux(
+        const char* domain, const char* msg_ctxt_id, const char* msgid, const char* msgid_plural, unsigned long int n,
+        int category
+    ) {
+    const char* translation = dcngettext(domain, msg_ctxt_id, msgid_plural, n, category);
+    if (translation == msg_ctxt_id || translation == msgid_plural)
+        return (n == 1 ? msgid : msgid_plural);
+    else
+        return translation;
 }
 
 /* The same thing extended for non-constant arguments.  Here MSGCTXT and MSGID
@@ -179,17 +164,14 @@ npgettext_aux (const char *domain,
 #include <string.h>
 
 #define _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS \
-  (((__GNUC__ >= 3 || __GNUG__ >= 2) && !__STRICT_ANSI__) \
-   /* || __STDC_VERSION__ >= 199901L */ )
+    (((__GNUC__ >= 3 || __GNUG__ >= 2) && !__STRICT_ANSI__) /* || __STDC_VERSION__ >= 199901L */)
 
 #if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
 #include <stdlib.h>
 #endif
 
-#define pgettext_expr(Msgctxt, Msgid) \
-  dcpgettext_expr (NULL, Msgctxt, Msgid, LC_MESSAGES)
-#define dpgettext_expr(Domainname, Msgctxt, Msgid) \
-  dcpgettext_expr (Domainname, Msgctxt, Msgid, LC_MESSAGES)
+#define pgettext_expr(Msgctxt, Msgid)              dcpgettext_expr(NULL, Msgctxt, Msgid, LC_MESSAGES)
+#define dpgettext_expr(Domainname, Msgctxt, Msgid) dcpgettext_expr(Domainname, Msgctxt, Msgid, LC_MESSAGES)
 
 #ifdef __GNUC__
 __inline
@@ -198,43 +180,37 @@ __inline
 inline
 #endif
 #endif
-static const char *
-dcpgettext_expr (const char *domain,
-                 const char *msgctxt, const char *msgid,
-                 int category)
-{
-  size_t msgctxt_len = strlen (msgctxt) + 1;
-  size_t msgid_len = strlen (msgid) + 1;
-  const char *translation;
+    static const char*
+    dcpgettext_expr(const char* domain, const char* msgctxt, const char* msgid, int category) {
+    size_t      msgctxt_len = strlen(msgctxt) + 1;
+    size_t      msgid_len   = strlen(msgid) + 1;
+    const char* translation;
 #if _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
-  char msg_ctxt_id[msgctxt_len + msgid_len];
+    char msg_ctxt_id[msgctxt_len + msgid_len];
 #else
-  char buf[1024];
-  char *msg_ctxt_id =
-    (msgctxt_len + msgid_len <= sizeof (buf)
-     ? buf
-     : (char *) malloc (msgctxt_len + msgid_len));
-  if (msg_ctxt_id != NULL)
+    char  buf[1024];
+    char* msg_ctxt_id = (msgctxt_len + msgid_len <= sizeof(buf) ? buf : (char*)malloc(msgctxt_len + msgid_len));
+    if (msg_ctxt_id != NULL)
 #endif
     {
-      memcpy (msg_ctxt_id, msgctxt, msgctxt_len - 1);
-      msg_ctxt_id[msgctxt_len - 1] = '\004';
-      memcpy (msg_ctxt_id + msgctxt_len, msgid, msgid_len);
-      translation = dcgettext (domain, msg_ctxt_id, category);
+        memcpy(msg_ctxt_id, msgctxt, msgctxt_len - 1);
+        msg_ctxt_id[msgctxt_len - 1] = '\004';
+        memcpy(msg_ctxt_id + msgctxt_len, msgid, msgid_len);
+        translation = dcgettext(domain, msg_ctxt_id, category);
 #if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
-      if (msg_ctxt_id != buf)
-        free (msg_ctxt_id);
+        if (msg_ctxt_id != buf)
+            free(msg_ctxt_id);
 #endif
-      if (translation != msg_ctxt_id)
-        return translation;
+        if (translation != msg_ctxt_id)
+            return translation;
     }
-  return msgid;
+    return msgid;
 }
 
 #define npgettext_expr(Msgctxt, Msgid, MsgidPlural, N) \
-  dcnpgettext_expr (NULL, Msgctxt, Msgid, MsgidPlural, N, LC_MESSAGES)
+    dcnpgettext_expr(NULL, Msgctxt, Msgid, MsgidPlural, N, LC_MESSAGES)
 #define dnpgettext_expr(Domainname, Msgctxt, Msgid, MsgidPlural, N) \
-  dcnpgettext_expr (Domainname, Msgctxt, Msgid, MsgidPlural, N, LC_MESSAGES)
+    dcnpgettext_expr(Domainname, Msgctxt, Msgid, MsgidPlural, N, LC_MESSAGES)
 
 #ifdef __GNUC__
 __inline
@@ -243,38 +219,34 @@ __inline
 inline
 #endif
 #endif
-static const char *
-dcnpgettext_expr (const char *domain,
-                  const char *msgctxt, const char *msgid,
-                  const char *msgid_plural, unsigned long int n,
-                  int category)
-{
-  size_t msgctxt_len = strlen (msgctxt) + 1;
-  size_t msgid_len = strlen (msgid) + 1;
-  const char *translation;
+    static const char*
+    dcnpgettext_expr(
+        const char* domain, const char* msgctxt, const char* msgid, const char* msgid_plural, unsigned long int n,
+        int category
+    ) {
+    size_t      msgctxt_len = strlen(msgctxt) + 1;
+    size_t      msgid_len   = strlen(msgid) + 1;
+    const char* translation;
 #if _LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
-  char msg_ctxt_id[msgctxt_len + msgid_len];
+    char msg_ctxt_id[msgctxt_len + msgid_len];
 #else
-  char buf[1024];
-  char *msg_ctxt_id =
-    (msgctxt_len + msgid_len <= sizeof (buf)
-     ? buf
-     : (char *) malloc (msgctxt_len + msgid_len));
-  if (msg_ctxt_id != NULL)
+    char  buf[1024];
+    char* msg_ctxt_id = (msgctxt_len + msgid_len <= sizeof(buf) ? buf : (char*)malloc(msgctxt_len + msgid_len));
+    if (msg_ctxt_id != NULL)
 #endif
     {
-      memcpy (msg_ctxt_id, msgctxt, msgctxt_len - 1);
-      msg_ctxt_id[msgctxt_len - 1] = '\004';
-      memcpy (msg_ctxt_id + msgctxt_len, msgid, msgid_len);
-      translation = dcngettext (domain, msg_ctxt_id, msgid_plural, n, category);
+        memcpy(msg_ctxt_id, msgctxt, msgctxt_len - 1);
+        msg_ctxt_id[msgctxt_len - 1] = '\004';
+        memcpy(msg_ctxt_id + msgctxt_len, msgid, msgid_len);
+        translation = dcngettext(domain, msg_ctxt_id, msgid_plural, n, category);
 #if !_LIBGETTEXT_HAVE_VARIABLE_SIZE_ARRAYS
-      if (msg_ctxt_id != buf)
-        free (msg_ctxt_id);
+        if (msg_ctxt_id != buf)
+            free(msg_ctxt_id);
 #endif
-      if (!(translation == msg_ctxt_id || translation == msgid_plural))
-        return translation;
+        if (!(translation == msg_ctxt_id || translation == msgid_plural))
+            return translation;
     }
-  return (n == 1 ? msgid : msgid_plural);
+    return (n == 1 ? msgid : msgid_plural);
 }
 
 #endif /* _LIBGETTEXT_H */
diff --git a/src/icons.h b/src/icons.h
index cf6f560..a550abc 100644
--- a/src/icons.h
+++ b/src/icons.h
@@ -1,118 +1,123 @@
 #include <gdk-pixbuf/gdk-pixbuf.h>
 
 typedef struct icon {
-  GdkColorspace colorspace;
-  gboolean has_alpha;
-  int bits_per_sample;
-  int width;
-  int height;
-  int rowstride;
-  const guchar *data;
+    GdkColorspace colorspace;
+    gboolean      has_alpha;
+    int           bits_per_sample;
+    int           width;
+    int           height;
+    int           rowstride;
+    const guchar* data;
 } icon;
 
-static const guchar lzoom_data[] =
-{ ""
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0IIIN444\243---\335))"
-  ")\373&&&\373&&&\335&&&\243555N\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0]]]2...\300000\377sss\377\241\241\241\377\264\264\264\377\262\262"
-  "\262\377\235\235\235\377ggg\377\40\40\40\377\34\34\34\3007772\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0@@@N'''\373aaa\377\264\264\264\377\312\312\312\377\317\317"
-  "\317\377\320\320\320\377\316\316\316\377\311\311\311\377\301\301\301"
-  "\377\247\247\247\377LLL\377\23\23\23\373###N\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\0\0\0\377OOO2\"\"\"\373uu"
-  "u\377\312\312\312\377\323\323\323\377\333\333\333\377\347\347\347\377"
-  "\357\357\357\377\363\363\363\377\361\361\361\377\345\345\345\377\322"
-  "\322\322\377\274\274\274\377^^^\377\20\20\20\373$$$2\0\0\0\0\0\0\0\377"
-  "\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\0\0\0\377!!!\300888\377"
-  "\314\314\314\377\205\205\205\377\345\345\345\377\227\227\227\377\372"
-  "\372\372\377\233\233\233\377\372\372\372\377\231\231\231\377\365\365"
-  "\365\377\224\224\224\377\341\341\341\377xxx\377CCC\377\6\6\6\377\0\0"
-  "\0\0\0\0\0\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0""000N\37\37"
-  "\37\377\271\271\271\377\326\326\326\377\347\347\347\377\371\371\371\377"
-  "\373\373\373\377\375\375\375\377\375\375\375\377\374\374\374\377\373"
-  "\373\373\377\370\370\370\377\362\362\362\377\354\354\354\377\344\344"
-  "\344\377\253\253\253\377\16\16\16\377\22\22\22N\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\21\21\21\377mmm\377\322\322\322\377\341\341"
-  "\341\377\365\365\365\377\372\372\372\377\375\375\375\377\376\376\376"
-  "\377\376\376\376\377\375\375\375\377\374\374\374\377\371\371\371\377"
-  "\365\365\365\377\356\356\356\377\346\346\346\377\333\333\333\377WWW\377"
-  "\11\11\11\243\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\24\24"
-  "\24\335\250\250\250\377\330\330\330\377\356\356\356\377\366\366\366\377"
-  "\371\371\371\377\374\374\374\377\376\376\376\377\376\376\376\377\375"
-  "\375\375\377\373\373\373\377\370\370\370\377\364\364\364\377\356\356"
-  "\356\377\346\346\346\377\334\334\334\377\233\233\233\377\6\6\6\335\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\20\20\20\377\305\305\305"
-  "\377\337\337\337\377\357\357\357\377\365\365\365\377\370\370\370\377"
-  "\373\373\373\377\375\375\375\377\375\375\375\377\374\374\374\377\372"
-  "\372\372\377\367\367\367\377\362\362\362\377\355\355\355\377\345\345"
-  "\345\377\333\333\333\377\277\277\277\377\6\6\6\373\0\0\0\377\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\16\16\16\373\306\306\306\377\343\343"
-  "\343\377\354\354\354\377\362\362\362\377\365\365\365\377\370\370\370"
-  "\377\372\372\372\377\372\372\372\377\372\372\372\377\367\367\367\377"
-  "\364\364\364\377\360\360\360\377\352\352\352\377\340\340\340\377\327"
-  "\327\327\377\272\272\272\377\5\5\5\373\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\11\11\11\377\245\245\245\377\341\341\341\377\347\347"
-  "\347\377\355\355\355\377\361\361\361\377\364\364\364\377\366\366\366"
-  "\377\366\366\366\377\365\365\365\377\363\363\363\377\357\357\357\377"
-  "\354\354\354\377\344\344\344\377\333\333\333\377\321\321\321\377\223"
-  "\223\223\377\2\2\2\335\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\12\12\12\243___\377\331\331\331\377\341\341\341\377\346\346\346"
-  "\377\353\353\353\377\356\356\356\377\357\357\357\377\357\357\357\377"
-  "\356\356\356\377\355\355\355\377\351\351\351\377\344\344\344\377\333"
-  "\333\333\377\324\324\324\377\312\312\312\377LLL\377\0\0\0\243\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\3\3\3\377\12\12\12\377\264\264"
-  "\264\377\330\330\330\377\334\334\334\377\342\342\342\377\345\345\345"
-  "\377\346\346\346\377\346\346\346\377\347\347\347\377\343\343\343\377"
-  "\337\337\337\377\332\332\332\377\324\324\324\377\313\313\313\377\241"
-  "\241\241\377\2\2\2\377\0\0\0N\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\37\6\6\6\300;;;\377\314\314\314\377\322\322\322\377"
-  "\324\324\324\377\332\332\332\377\333\333\333\377\332\332\332\377\333"
-  "\333\333\377\330\330\330\377\325\325\325\377\320\320\320\377\310\310"
-  "\310\377\275\275\275\377...\377\0\0\0\300\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\5\5\5""2\5\5\5\373QQQ\377\302"
-  "\302\302\377\307\307\307\377\313\313\313\377\314\314\314\377\315\315"
-  "\315\377\313\313\313\377\313\313\313\377\310\310\310\377\302\302\302"
-  "\377\270\270\270\377EEE\377\0\0\0\373\0\0\0K\0\0\0\0\0\0\0\377\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\37\3\3\3N\3\3\3\373"
-  "111\377\231\231\231\377\273\273\273\377\275\275\275\377\274\274\274\377"
-  "\274\274\274\377\274\274\274\377\266\266\266\377\220\220\220\377+++\377"
-  "\0\0\0\373\0\0\0\361\0\0\0\362\0\0\0g\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\377\0\0\0\0\0\0\0\37\0\0\0""2\1\1\1\300\3\3\3"
-  "\377AAA\377zzz\377\232\232\232\377\232\232\232\377www\377<<<\377\0\0"
-  "\0\377\0\0\0\300\0\0\0""2\0\0\0\337\0\0\0\360\0\0\0\363\0\0\0\377\0\0"
-  "\0L\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\37\0\0\0N\0\0\0\243\0\0\0\335\0\0\0\373\0\0\0\373\0\0\0\335\0\0"
-  "\0\243\0\0\0N\0\0\0:\0\0\0\37\0\0\0\37\40\40\40\363\40\40\40\364\0\0"
-  "\0\366\0\0\0\361\0\0\0:\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\37\0\0\0\37\0\0\0\37\0\0\0\37\0\0"
-  "\0\37\0\0\0\37\0\0\0\37\0\0\0\0\0\0\0\0\0\0\0\37\0\0\0\354hhh\373\0\0"
-  "\0\377\0\0\0\362\0\0\0\366\0\0\0\37\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\37\0\0\0\363yyy\375"
-  ":::\374\0\0\0\363\0\0\0\364\0\0\0\37\0\0\0\377\0\0\0\377\0\0\0\0\0\0"
-  "\0\377\0\0\0\0\0\0\0\377\0\0\0\0\0\0\0\377\0\0\0\0\0\0\0\377\0\0\0\0"
-  "\0\0\0\377\0\0\0\0\0\0\0\377\0\0\0\0\0\0\0\377\0\0\0\0\0\0\0\377\0\0"
-  "\0\37\0\0\0\377\0\0\0\377\37\37\37\373\0\0\0\364\0\0\0\37\0\0\0\377\0"
-  "\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\37\0\0\0\377\0\0\0\377\0\0\0\375\0\0\0\77\0\0\0\37\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\37\0\0\0\37\0\0\0\37\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"};
+static const guchar lzoom_data[] = {
+    ""
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0IIIN444\243---\335))"
+    ")\373&&&\373&&&\335&&&\243555N\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0]]]2...\300000\377sss\377\241\241\241\377\264\264\264\377\262\262"
+    "\262\377\235\235\235\377ggg\377\40\40\40\377\34\34\34\3007772\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0@@@N'''\373aaa\377\264\264\264\377\312\312\312\377\317\317"
+    "\317\377\320\320\320\377\316\316\316\377\311\311\311\377\301\301\301"
+    "\377\247\247\247\377LLL\377\23\23\23\373###N\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\0\0\0\377OOO2\"\"\"\373uu"
+    "u\377\312\312\312\377\323\323\323\377\333\333\333\377\347\347\347\377"
+    "\357\357\357\377\363\363\363\377\361\361\361\377\345\345\345\377\322"
+    "\322\322\377\274\274\274\377^^^\377\20\20\20\373$$$2\0\0\0\0\0\0\0\377"
+    "\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\0\0\0\377!!!\300888\377"
+    "\314\314\314\377\205\205\205\377\345\345\345\377\227\227\227\377\372"
+    "\372\372\377\233\233\233\377\372\372\372\377\231\231\231\377\365\365"
+    "\365\377\224\224\224\377\341\341\341\377xxx\377CCC\377\6\6\6\377\0\0"
+    "\0\0\0\0\0\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "000N\37\37"
+    "\37\377\271\271\271\377\326\326\326\377\347\347\347\377\371\371\371\377"
+    "\373\373\373\377\375\375\375\377\375\375\375\377\374\374\374\377\373"
+    "\373\373\377\370\370\370\377\362\362\362\377\354\354\354\377\344\344"
+    "\344\377\253\253\253\377\16\16\16\377\22\22\22N\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\21\21\21\377mmm\377\322\322\322\377\341\341"
+    "\341\377\365\365\365\377\372\372\372\377\375\375\375\377\376\376\376"
+    "\377\376\376\376\377\375\375\375\377\374\374\374\377\371\371\371\377"
+    "\365\365\365\377\356\356\356\377\346\346\346\377\333\333\333\377WWW\377"
+    "\11\11\11\243\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\24\24"
+    "\24\335\250\250\250\377\330\330\330\377\356\356\356\377\366\366\366\377"
+    "\371\371\371\377\374\374\374\377\376\376\376\377\376\376\376\377\375"
+    "\375\375\377\373\373\373\377\370\370\370\377\364\364\364\377\356\356"
+    "\356\377\346\346\346\377\334\334\334\377\233\233\233\377\6\6\6\335\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\20\20\20\377\305\305\305"
+    "\377\337\337\337\377\357\357\357\377\365\365\365\377\370\370\370\377"
+    "\373\373\373\377\375\375\375\377\375\375\375\377\374\374\374\377\372"
+    "\372\372\377\367\367\367\377\362\362\362\377\355\355\355\377\345\345"
+    "\345\377\333\333\333\377\277\277\277\377\6\6\6\373\0\0\0\377\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\16\16\16\373\306\306\306\377\343\343"
+    "\343\377\354\354\354\377\362\362\362\377\365\365\365\377\370\370\370"
+    "\377\372\372\372\377\372\372\372\377\372\372\372\377\367\367\367\377"
+    "\364\364\364\377\360\360\360\377\352\352\352\377\340\340\340\377\327"
+    "\327\327\377\272\272\272\377\5\5\5\373\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\11\11\11\377\245\245\245\377\341\341\341\377\347\347"
+    "\347\377\355\355\355\377\361\361\361\377\364\364\364\377\366\366\366"
+    "\377\366\366\366\377\365\365\365\377\363\363\363\377\357\357\357\377"
+    "\354\354\354\377\344\344\344\377\333\333\333\377\321\321\321\377\223"
+    "\223\223\377\2\2\2\335\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\12\12\12\243___\377\331\331\331\377\341\341\341\377\346\346\346"
+    "\377\353\353\353\377\356\356\356\377\357\357\357\377\357\357\357\377"
+    "\356\356\356\377\355\355\355\377\351\351\351\377\344\344\344\377\333"
+    "\333\333\377\324\324\324\377\312\312\312\377LLL\377\0\0\0\243\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\3\3\3\377\12\12\12\377\264\264"
+    "\264\377\330\330\330\377\334\334\334\377\342\342\342\377\345\345\345"
+    "\377\346\346\346\377\346\346\346\377\347\347\347\377\343\343\343\377"
+    "\337\337\337\377\332\332\332\377\324\324\324\377\313\313\313\377\241"
+    "\241\241\377\2\2\2\377\0\0\0N\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\37\6\6\6\300;;;\377\314\314\314\377\322\322\322\377"
+    "\324\324\324\377\332\332\332\377\333\333\333\377\332\332\332\377\333"
+    "\333\333\377\330\330\330\377\325\325\325\377\320\320\320\377\310\310"
+    "\310\377\275\275\275\377...\377\0\0\0\300\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\5\5\5"
+    "2\5\5\5\373QQQ\377\302"
+    "\302\302\377\307\307\307\377\313\313\313\377\314\314\314\377\315\315"
+    "\315\377\313\313\313\377\313\313\313\377\310\310\310\377\302\302\302"
+    "\377\270\270\270\377EEE\377\0\0\0\373\0\0\0K\0\0\0\0\0\0\0\377\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\37\3\3\3N\3\3\3\373"
+    "111\377\231\231\231\377\273\273\273\377\275\275\275\377\274\274\274\377"
+    "\274\274\274\377\274\274\274\377\266\266\266\377\220\220\220\377+++\377"
+    "\0\0\0\373\0\0\0\361\0\0\0\362\0\0\0g\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\377\0\0\0\0\0\0\0\37\0\0\0"
+    "2\1\1\1\300\3\3\3"
+    "\377AAA\377zzz\377\232\232\232\377\232\232\232\377www\377<<<\377\0\0"
+    "\0\377\0\0\0\300\0\0\0"
+    "2\0\0\0\337\0\0\0\360\0\0\0\363\0\0\0\377\0\0"
+    "\0L\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\37\0\0\0N\0\0\0\243\0\0\0\335\0\0\0\373\0\0\0\373\0\0\0\335\0\0"
+    "\0\243\0\0\0N\0\0\0:\0\0\0\37\0\0\0\37\40\40\40\363\40\40\40\364\0\0"
+    "\0\366\0\0\0\361\0\0\0:\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\37\0\0\0\37\0\0\0\37\0\0\0\37\0\0"
+    "\0\37\0\0\0\37\0\0\0\37\0\0\0\0\0\0\0\0\0\0\0\37\0\0\0\354hhh\373\0\0"
+    "\0\377\0\0\0\362\0\0\0\366\0\0\0\37\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\37\0\0\0\363yyy\375"
+    ":::\374\0\0\0\363\0\0\0\364\0\0\0\37\0\0\0\377\0\0\0\377\0\0\0\0\0\0"
+    "\0\377\0\0\0\0\0\0\0\377\0\0\0\0\0\0\0\377\0\0\0\0\0\0\0\377\0\0\0\0"
+    "\0\0\0\377\0\0\0\0\0\0\0\377\0\0\0\0\0\0\0\377\0\0\0\0\0\0\0\377\0\0"
+    "\0\37\0\0\0\377\0\0\0\377\37\37\37\373\0\0\0\364\0\0\0\37\0\0\0\377\0"
+    "\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\37\0\0\0\377\0\0\0\377\0\0\0\375\0\0\0\77\0\0\0\37\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\37\0\0\0\37\0\0\0\37\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+};
 
 static const icon lzoom = {
-  .colorspace = GDK_COLORSPACE_RGB,
-  .has_alpha = 1,
-  .bits_per_sample = 8,
-  .width = 24,
-  .height = 24,
-  .rowstride = 96,
-  .data = lzoom_data,
+    .colorspace      = GDK_COLORSPACE_RGB,
+    .has_alpha       = 1,
+    .bits_per_sample = 8,
+    .width           = 24,
+    .height          = 24,
+    .rowstride       = 96,
+    .data            = lzoom_data,
 };
 
 /* -------------------  Measure tool icon  ------------------- */
@@ -122,334 +127,342 @@ static const icon lzoom = {
    ver. 1.8.0-1~bpo70+.  This theme has been made by Rowen_Stipe based on
    Faenza and Faience icon themes by ~Tiheum. */
 
-static const guchar ruler_data[] =
-{ ""
-  "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0"
-  "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0"
-  "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0"
-  "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0"
-  "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0"
-  "\377\377\377\0\377\377\377\0\0\0\0\7\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0"
-  "\15\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0\15\0\0"
-  "\0\15\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0\7\377\377\377\0\377\377"
-  "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\311\277e`\356\343\205"
-  "\337\363\350\215\377\363\351\217\377\363\351\222\377\363\351\225\377\364"
-  "\352\227\377\364\352\231\377\364\353\233\377\364\353\235\377\365\354\237"
-  "\377\365\354\240\377\365\354\241\377\365\355\244\377\365\355\246\377\366"
-  "\355\250\377\366\356\252\377\366\356\254\377\362\352\243\346\322\312~"
-  "k\377\377\377\0\377\377\377\0\377\377\377\0\0\0\0\11\352\335z\340\355"
-  "\337_\377\357\342k\377\361\344z\377\360\344{\377\361\345\201\377\361\346"
-  "\201\377\361\347\205\377\362\347\205\377\362\350\212\377\362\350\212\377"
-  "\363\351\217\377\363\350\217\377\363\351\224\377\364\351\223\377\364\352"
-  "\230\377\364\352\227\377\364\353\231\377\364\353\236\377\360\346\236\350"
-  "\0\0\0\11\377\377\377\0\377\377\377\0\0\0\0\20\360\344{\377\352\333L\377"
-  "\357\343u\377\214|\"\377\361\345\200\377\214|$\377\361\346\205\377\214"
-  "|%\377\362\347\212\377\214}'\377\362\350\216\377\215}(\377\363\351\223"
-  "\377\215})\377\364\352\227\377\215~*\377\363\352\231\377\215}*\377\363"
-  "\352\231\377\365\355\244\377\0\0\0\20\377\377\377\0\377\377\377\0\0\0"
-  "\0\21\357\342u\377\353\331L\377\360\343v\377\206u\34\377\361\345\202\377"
-  "\206u\35\377\362\347\207\377\206v\36\377\362\350\214\377\206v\40\377\362"
-  "\350\220\377\206v\40\377\363\351\225\377\206v\"\377\363\352\231\377\206"
-  "v\"\377\364\352\232\377\206v\"\377\364\351\231\377\364\353\240\377\0\0"
-  "\0\21\377\377\377\0\377\377\377\0\0\0\0\22\356\340m\377\352\330I\377\357"
-  "\342u\377~m\26\377\361\345\201\377~m\27\377\361\345\206\377\177m\30\377"
-  "\361\346\213\377\177n\31\377\362\347\217\377\177n\32\377\363\351\224\377"
-  "\177n\32\377\363\351\230\377\177n\33\377\363\351\232\377\177n\33\377\363"
-  "\351\226\377\363\352\232\377\0\0\0\22\377\377\377\0\377\377\377\0\0\0"
-  "\0\24\355\337e\377\351\327E\377\356\341s\377xf\17\377\360\344~\377xg\20"
-  "\377\361\345\204\377xg\21\377\361\346\210\377xg\21\377\361\346\215\377"
-  "xg\22\377\362\350\221\377xg\22\377\363\351\225\377xg\23\377\362\351\230"
-  "\377xg\23\377\362\351\224\377\362\350\225\377\0\0\0\24\377\377\377\0\377"
-  "\377\377\0\0\0\0\25\352\334]\377\346\326@\377\355\340o\377p_\11\377\356"
-  "\343{\377p_\11\377\357\344\201\377p_\12\377\357\345\205\377p_\12\377\360"
-  "\346\211\377p_\12\377\361\346\215\377p_\13\377\361\350\222\377p_\13\377"
-  "\362\350\225\377p_\13\377\361\350\221\377\360\346\216\377\0\0\0\25\377"
-  "\377\377\0\377\377\377\0\0\0\0\26\351\332T\377\345\324:\377\355\337k\377"
-  "jW\3\377\356\341x\377jW\3\377\356\343}\377jW\3\377\357\344\201\377jW\3"
-  "\377\357\345\206\377jW\3\377\360\346\212\377jW\3\377\361\347\217\377j"
-  "W\3\377\361\350\221\377jW\3\377\361\346\215\377\357\345\207\377\0\0\0"
-  "\26\377\377\377\0\377\377\377\0\0\0\0\27\346\327J\377\344\3226\377\353"
-  "\335h\377fT\0\377\355\341t\377\355\341x\377\355\341w\377\356\341}\377"
-  "\356\342{\377\357\343\201\377\357\342\200\377\357\344\205\377\357\345"
-  "\207\377fT\0\377\360\346\214\377\360\345\215\377\360\346\215\377\360\345"
-  "\215\377\357\343\201\377\356\342\200\377\0\0\0\27\377\377\377\0\377\377"
-  "\377\0\0\0\0\30\345\325@\377\343\3201\377\352\335d\377fT\0\377\354\340"
-  "q\377\350\330Q\377\350\331T\377\351\332W\377\351\332Z\377\351\332\\\377"
-  "\352\333`\377\352\334b\377\357\344\205\377fT\0\377\357\345\211\377\353"
-  "\337n\377\354\337o\377\353\337l\377\353\336i\377\355\340y\377\0\0\0\30"
-  "\377\377\377\0\377\377\377\0\0\0\0\32\344\3228\377\343\320-\377\352\334"
-  "a\377fT\0\377\354\336n\377\347\327N\377\350\330Q\377\350\331T\377\351"
-  "\331W\377\351\332X\377\351\331V\377\350\330R\377\354\337q\377fT\0\377"
-  "\354\336o\377\347\326H\377\346\325C\377\345\3229\377\343\3200\377\345"
-  "\324A\377\0\0\0\32\377\377\377\0\377\377\377\0\0\0\0\33\343\3200\377\342"
-  "\316)\377\351\332]\377fT\0\377\353\335k\377\346\325I\377\346\325H\377"
-  "\345\324D\377\345\324@\377\345\323<\377\345\323<\377\345\323<\377\351"
-  "\331W\377\352\334c\377\351\331W\377\344\323;\377\344\3229\377\343\320"
-  "0\377\342\316'\377\343\3200\377\0\0\0\33\377\377\377\0\377\377\377\0\0"
-  "\0\0\34\341\315(\377\341\314#\377\351\331Z\377fT\0\377\351\333c\377\344"
-  "\321:\377\344\321:\377\344\321:\377\344\321:\377\344\321:\377\344\321"
-  ":\377\344\321:\377\344\321:\377\344\321:\377\344\321:\377\344\3219\377"
-  "\343\3206\377\342\316.\377\341\314#\377\341\315(\377\0\0\0\34\377\377"
-  "\377\0\377\377\377\0\0\0\0\35\337\313\37\377\337\313\37\377\346\327U\377"
-  "fT\0\377\350\331]\377\342\3206\377\342\3206\377\342\3206\377\342\3206"
-  "\377\342\3206\377\342\3206\377\342\3206\377\342\3206\377\342\3206\377"
-  "\342\3206\377\342\3205\377\342\3172\377\340\315*\377\337\313\37\377\337"
-  "\313\37\377\0\0\0\35\377\377\377\0\377\377\377\0\0\0\0\36\335\311\27\377"
-  "\336\312\34\377\343\323E\377\347\330Y\377\345\326O\377\341\3174\377\341"
-  "\3174\377\341\3174\377\341\3174\377\341\3174\377\341\3174\377\341\317"
-  "4\377\341\3174\377\341\3174\377\341\3174\377\341\3173\377\341\3160\377"
-  "\337\314'\377\336\312\34\377\335\311\27\377\0\0\0\36\377\377\377\0\377"
-  "\377\377\0\0\0\0\40\333\307\20\377\335\311\30\377\336\313#\377\340\315"
-  "+\377\340\316/\377\340\3160\377\340\3160\377\340\3160\377\340\3160\377"
-  "\340\3160\377\340\3160\377\340\3160\377\340\3160\377\340\3160\377\340"
-  "\3160\377\340\316/\377\340\315+\377\336\313#\377\335\311\30\377\333\307"
-  "\20\377\0\0\0\40\377\377\377\0\377\377\377\0\0\0\0!\332\305\15\377\333"
-  "\306\23\377\335\310\34\377\336\312%\377\337\313)\377\337\314+\377\337"
-  "\314+\377\337\314+\377\337\314+\377\337\314+\377\337\314+\377\337\314"
-  "+\377\337\314+\377\337\314+\377\337\314+\377\337\313)\377\336\312%\377"
-  "\335\310\34\377\333\306\23\377\332\305\15\377\0\0\0!\377\377\377\0\377"
-  "\377\377\0\0\0\0\"\332\303\12\377\333\304\16\377\334\306\25\377\335\307"
-  "\32\377\335\310\36\377\336\311\40\377\336\311\40\377\336\311\40\377\336"
-  "\311\40\377\336\311\40\377\336\311\40\377\336\311\40\377\336\311\40\377"
-  "\336\311\40\377\336\311\40\377\335\310\36\377\335\307\32\377\334\306\25"
-  "\377\333\304\16\377\332\303\12\377\0\0\0\"\377\377\377\0\377\377\377\0"
-  "\0\0\0\40\272\247\10\353\331\303\12\377\332\303\13\377\332\304\16\377"
-  "\333\305\20\377\333\305\21\377\333\305\22\377\333\305\22\377\333\305\22"
-  "\377\333\305\22\377\333\305\22\377\333\305\22\377\333\305\22\377\333\305"
-  "\22\377\333\305\21\377\333\305\20\377\332\304\16\377\332\303\13\377\331"
-  "\303\12\377\272\247\10\353\0\0\0\40\377\377\377\0\377\377\377\0\0\0\0"
-  "\10QH\2\242\274\251\20\355\334\307\35\377\334\311\"\377\335\312%\377\337"
-  "\313)\377\337\313,\377\337\314/\377\340\3153\377\340\3166\377\340\316"
-  "6\377\340\3153\377\337\314/\377\337\313,\377\337\313)\377\335\312%\377"
-  "\334\311\"\377\334\307\35\377\274\251\20\355QH\2\242\0\0\0\10\377\377"
-  "\377\0\377\377\377\0\377\377\377\0\0\0\0+\0\0\0{\0\0\0\243\0\0\0\245\0"
-  "\0\0\245\0\0\0\245\0\0\0\245\0\0\0\245\0\0\0\245\0\0\0\245\0\0\0\245\0"
-  "\0\0\245\0\0\0\245\0\0\0\245\0\0\0\245\0\0\0\245\0\0\0\245\0\0\0\243\0"
-  "\0\0{\0\0\0+\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0"};
+static const guchar ruler_data[] = {
+    ""
+    "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0"
+    "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0"
+    "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0"
+    "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0"
+    "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0"
+    "\377\377\377\0\377\377\377\0\0\0\0\7\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0"
+    "\15\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0\15\0\0"
+    "\0\15\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0\15\0\0\0\7\377\377\377\0\377\377"
+    "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\311\277e`\356\343\205"
+    "\337\363\350\215\377\363\351\217\377\363\351\222\377\363\351\225\377\364"
+    "\352\227\377\364\352\231\377\364\353\233\377\364\353\235\377\365\354\237"
+    "\377\365\354\240\377\365\354\241\377\365\355\244\377\365\355\246\377\366"
+    "\355\250\377\366\356\252\377\366\356\254\377\362\352\243\346\322\312~"
+    "k\377\377\377\0\377\377\377\0\377\377\377\0\0\0\0\11\352\335z\340\355"
+    "\337_\377\357\342k\377\361\344z\377\360\344{\377\361\345\201\377\361\346"
+    "\201\377\361\347\205\377\362\347\205\377\362\350\212\377\362\350\212\377"
+    "\363\351\217\377\363\350\217\377\363\351\224\377\364\351\223\377\364\352"
+    "\230\377\364\352\227\377\364\353\231\377\364\353\236\377\360\346\236\350"
+    "\0\0\0\11\377\377\377\0\377\377\377\0\0\0\0\20\360\344{\377\352\333L\377"
+    "\357\343u\377\214|\"\377\361\345\200\377\214|$\377\361\346\205\377\214"
+    "|%\377\362\347\212\377\214}'\377\362\350\216\377\215}(\377\363\351\223"
+    "\377\215})\377\364\352\227\377\215~*\377\363\352\231\377\215}*\377\363"
+    "\352\231\377\365\355\244\377\0\0\0\20\377\377\377\0\377\377\377\0\0\0"
+    "\0\21\357\342u\377\353\331L\377\360\343v\377\206u\34\377\361\345\202\377"
+    "\206u\35\377\362\347\207\377\206v\36\377\362\350\214\377\206v\40\377\362"
+    "\350\220\377\206v\40\377\363\351\225\377\206v\"\377\363\352\231\377\206"
+    "v\"\377\364\352\232\377\206v\"\377\364\351\231\377\364\353\240\377\0\0"
+    "\0\21\377\377\377\0\377\377\377\0\0\0\0\22\356\340m\377\352\330I\377\357"
+    "\342u\377~m\26\377\361\345\201\377~m\27\377\361\345\206\377\177m\30\377"
+    "\361\346\213\377\177n\31\377\362\347\217\377\177n\32\377\363\351\224\377"
+    "\177n\32\377\363\351\230\377\177n\33\377\363\351\232\377\177n\33\377\363"
+    "\351\226\377\363\352\232\377\0\0\0\22\377\377\377\0\377\377\377\0\0\0"
+    "\0\24\355\337e\377\351\327E\377\356\341s\377xf\17\377\360\344~\377xg\20"
+    "\377\361\345\204\377xg\21\377\361\346\210\377xg\21\377\361\346\215\377"
+    "xg\22\377\362\350\221\377xg\22\377\363\351\225\377xg\23\377\362\351\230"
+    "\377xg\23\377\362\351\224\377\362\350\225\377\0\0\0\24\377\377\377\0\377"
+    "\377\377\0\0\0\0\25\352\334]\377\346\326@\377\355\340o\377p_\11\377\356"
+    "\343{\377p_\11\377\357\344\201\377p_\12\377\357\345\205\377p_\12\377\360"
+    "\346\211\377p_\12\377\361\346\215\377p_\13\377\361\350\222\377p_\13\377"
+    "\362\350\225\377p_\13\377\361\350\221\377\360\346\216\377\0\0\0\25\377"
+    "\377\377\0\377\377\377\0\0\0\0\26\351\332T\377\345\324:\377\355\337k\377"
+    "jW\3\377\356\341x\377jW\3\377\356\343}\377jW\3\377\357\344\201\377jW\3"
+    "\377\357\345\206\377jW\3\377\360\346\212\377jW\3\377\361\347\217\377j"
+    "W\3\377\361\350\221\377jW\3\377\361\346\215\377\357\345\207\377\0\0\0"
+    "\26\377\377\377\0\377\377\377\0\0\0\0\27\346\327J\377\344\3226\377\353"
+    "\335h\377fT\0\377\355\341t\377\355\341x\377\355\341w\377\356\341}\377"
+    "\356\342{\377\357\343\201\377\357\342\200\377\357\344\205\377\357\345"
+    "\207\377fT\0\377\360\346\214\377\360\345\215\377\360\346\215\377\360\345"
+    "\215\377\357\343\201\377\356\342\200\377\0\0\0\27\377\377\377\0\377\377"
+    "\377\0\0\0\0\30\345\325@\377\343\3201\377\352\335d\377fT\0\377\354\340"
+    "q\377\350\330Q\377\350\331T\377\351\332W\377\351\332Z\377\351\332\\\377"
+    "\352\333`\377\352\334b\377\357\344\205\377fT\0\377\357\345\211\377\353"
+    "\337n\377\354\337o\377\353\337l\377\353\336i\377\355\340y\377\0\0\0\30"
+    "\377\377\377\0\377\377\377\0\0\0\0\32\344\3228\377\343\320-\377\352\334"
+    "a\377fT\0\377\354\336n\377\347\327N\377\350\330Q\377\350\331T\377\351"
+    "\331W\377\351\332X\377\351\331V\377\350\330R\377\354\337q\377fT\0\377"
+    "\354\336o\377\347\326H\377\346\325C\377\345\3229\377\343\3200\377\345"
+    "\324A\377\0\0\0\32\377\377\377\0\377\377\377\0\0\0\0\33\343\3200\377\342"
+    "\316)\377\351\332]\377fT\0\377\353\335k\377\346\325I\377\346\325H\377"
+    "\345\324D\377\345\324@\377\345\323<\377\345\323<\377\345\323<\377\351"
+    "\331W\377\352\334c\377\351\331W\377\344\323;\377\344\3229\377\343\320"
+    "0\377\342\316'\377\343\3200\377\0\0\0\33\377\377\377\0\377\377\377\0\0"
+    "\0\0\34\341\315(\377\341\314#\377\351\331Z\377fT\0\377\351\333c\377\344"
+    "\321:\377\344\321:\377\344\321:\377\344\321:\377\344\321:\377\344\321"
+    ":\377\344\321:\377\344\321:\377\344\321:\377\344\321:\377\344\3219\377"
+    "\343\3206\377\342\316.\377\341\314#\377\341\315(\377\0\0\0\34\377\377"
+    "\377\0\377\377\377\0\0\0\0\35\337\313\37\377\337\313\37\377\346\327U\377"
+    "fT\0\377\350\331]\377\342\3206\377\342\3206\377\342\3206\377\342\3206"
+    "\377\342\3206\377\342\3206\377\342\3206\377\342\3206\377\342\3206\377"
+    "\342\3206\377\342\3205\377\342\3172\377\340\315*\377\337\313\37\377\337"
+    "\313\37\377\0\0\0\35\377\377\377\0\377\377\377\0\0\0\0\36\335\311\27\377"
+    "\336\312\34\377\343\323E\377\347\330Y\377\345\326O\377\341\3174\377\341"
+    "\3174\377\341\3174\377\341\3174\377\341\3174\377\341\3174\377\341\317"
+    "4\377\341\3174\377\341\3174\377\341\3174\377\341\3173\377\341\3160\377"
+    "\337\314'\377\336\312\34\377\335\311\27\377\0\0\0\36\377\377\377\0\377"
+    "\377\377\0\0\0\0\40\333\307\20\377\335\311\30\377\336\313#\377\340\315"
+    "+\377\340\316/\377\340\3160\377\340\3160\377\340\3160\377\340\3160\377"
+    "\340\3160\377\340\3160\377\340\3160\377\340\3160\377\340\3160\377\340"
+    "\3160\377\340\316/\377\340\315+\377\336\313#\377\335\311\30\377\333\307"
+    "\20\377\0\0\0\40\377\377\377\0\377\377\377\0\0\0\0!\332\305\15\377\333"
+    "\306\23\377\335\310\34\377\336\312%\377\337\313)\377\337\314+\377\337"
+    "\314+\377\337\314+\377\337\314+\377\337\314+\377\337\314+\377\337\314"
+    "+\377\337\314+\377\337\314+\377\337\314+\377\337\313)\377\336\312%\377"
+    "\335\310\34\377\333\306\23\377\332\305\15\377\0\0\0!\377\377\377\0\377"
+    "\377\377\0\0\0\0\"\332\303\12\377\333\304\16\377\334\306\25\377\335\307"
+    "\32\377\335\310\36\377\336\311\40\377\336\311\40\377\336\311\40\377\336"
+    "\311\40\377\336\311\40\377\336\311\40\377\336\311\40\377\336\311\40\377"
+    "\336\311\40\377\336\311\40\377\335\310\36\377\335\307\32\377\334\306\25"
+    "\377\333\304\16\377\332\303\12\377\0\0\0\"\377\377\377\0\377\377\377\0"
+    "\0\0\0\40\272\247\10\353\331\303\12\377\332\303\13\377\332\304\16\377"
+    "\333\305\20\377\333\305\21\377\333\305\22\377\333\305\22\377\333\305\22"
+    "\377\333\305\22\377\333\305\22\377\333\305\22\377\333\305\22\377\333\305"
+    "\22\377\333\305\21\377\333\305\20\377\332\304\16\377\332\303\13\377\331"
+    "\303\12\377\272\247\10\353\0\0\0\40\377\377\377\0\377\377\377\0\0\0\0"
+    "\10QH\2\242\274\251\20\355\334\307\35\377\334\311\"\377\335\312%\377\337"
+    "\313)\377\337\313,\377\337\314/\377\340\3153\377\340\3166\377\340\316"
+    "6\377\340\3153\377\337\314/\377\337\313,\377\337\313)\377\335\312%\377"
+    "\334\311\"\377\334\307\35\377\274\251\20\355QH\2\242\0\0\0\10\377\377"
+    "\377\0\377\377\377\0\377\377\377\0\0\0\0+\0\0\0{\0\0\0\243\0\0\0\245\0"
+    "\0\0\245\0\0\0\245\0\0\0\245\0\0\0\245\0\0\0\245\0\0\0\245\0\0\0\245\0"
+    "\0\0\245\0\0\0\245\0\0\0\245\0\0\0\245\0\0\0\245\0\0\0\245\0\0\0\243\0"
+    "\0\0{\0\0\0+\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0"
+};
 
 static const icon ruler = {
-  .colorspace = GDK_COLORSPACE_RGB,
-  .has_alpha = 1,
-  .bits_per_sample = 8,
-  .width = 24,
-  .height = 24,
-  .rowstride = 96,
-  .data = ruler_data,
+    .colorspace      = GDK_COLORSPACE_RGB,
+    .has_alpha       = 1,
+    .bits_per_sample = 8,
+    .width           = 24,
+    .height          = 24,
+    .rowstride       = 96,
+    .data            = ruler_data,
 };
 
-
 /* -------------------  Move tool icon  -------------------------- */
 /* GdkPixbuf RGBA C-Source image dump */
 
-static const guchar move_data[] =
-{ ""
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\40J\207\31\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\40J\207\31\40J\207\377"
-  "\40J\207\31\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\40J\207\31\40J\207\377r\237\317\377\40J\207\377\40"
-  "J\207\31\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\40J\207\31\40J\207\377r\237\317\377L|\265\377r\237\317\377\40J\207\377"
-  "\40J\207\31\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\40J\207"
-  "\377r\237\317\377L|\265\377L|\265\377L|\265\377r\237\317\377\40J\207"
-  "\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\40J\207\377"
-  "\40J\207\377\40J\207\377S\203\272\377\40J\207\377\40J\207\377\40J\207"
-  "\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\40J\207\377Y\210\276\377\40J\207\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\40J\207\31\40J\207\377\40J\207\377\0\0\0\0\0\0\0\0\0\0\0\0\40"
-  "J\207\377b\221\304\377\40J\207\377\0\0\0\0\0\0\0\0\0\0\0\0\40J\207\377"
-  "\40J\207\377\40J\207\31\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\40J\207\31\40J\207\377r\237\317\377\40J\207\377\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\40J\207\377r\237\317\377\40J\207\377\0\0\0\0\0\0\0\0\0\0\0\0\40"
-  "J\207\377r\237\317\377\40J\207\377\40J\207\31\0\0\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\40J\207\31\40J\207\377r\237\317\377L|\265\377\40J\207\377\40"
-  "J\207\377\40J\207\377\40J\207\377\40J\207\377r\237\317\377\40J\207\377"
-  "\40J\207\377\40J\207\377\40J\207\377\40J\207\377L|\265\377r\237\317\377"
-  "\40J\207\377\40J\207\31\0\0\0\0\0\0\0\0\40J\207\31\40J\207\377r\237\317"
-  "\377L|\265\377L|\265\377S\203\272\377Y\210\276\377b\221\304\377r\237"
-  "\317\377r\237\317\377r\237\317\377r\237\317\377r\237\317\377b\221\304"
-  "\377Y\210\276\377S\203\272\377L|\265\377L|\265\377r\237\317\377\40J\207"
-  "\377\40J\207\31\0\0\0\0\0\0\0\0\40J\207\31\40J\207\377r\237\317\377L"
-  "|\265\377\40J\207\377\40J\207\377\40J\207\377\40J\207\377\40J\207\377"
-  "r\237\317\377\40J\207\377\40J\207\377\40J\207\377\40J\207\377\40J\207"
-  "\377L|\265\377r\237\317\377\40J\207\377\40J\207\31\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\40J\207\31\40J\207\377r\237\317\377\40J\207\377\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\40J\207\377r\237\317\377\40J\207\377\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\40J\207\377r\237\317\377\40J\207\377\40J\207\31\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\40J\207\31\40J\207\377\40J\207"
-  "\377\0\0\0\0\0\0\0\1\0\0\0\1\40J\207\377b\221\304\377\40J\207\377\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\40J\207\377\40J\207\377\40J\207\31\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\0\0\0\1\0\0\0\3\0"
-  "\0\0\6\0\0\0\10\0\0\0\11\40J\207\377Y\210\276\377\40J\207\377\0\0\0\12"
-  "\0\0\0\6\0\0\0\5\0\0\0\4\0\0\0\3\0\0\0\2\0\0\0\2\0\0\0\1\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\1\0\0\0\2\0\0\0\5\0\0\0\10\0\0\0\16\0\0\0\26\40J\207"
-  "\377\40J\207\377\40J\207\377S\203\272\377\40J\207\377\40J\207\377\40"
-  "J\207\377\0\0\0\26\0\0\0\20\0\0\0\14\0\0\0\11\0\0\0\6\0\0\0\3\0\0\0\1"
-  "\0\0\0\0\0\0\0\0\0\0\0\3\0\0\0\7\0\0\0\16\0\0\0\25\0\0\0!\0\0\0-\40J"
-  "\207\377r\237\317\377L|\265\377L|\265\377L|\265\377r\237\317\377\40J"
-  "\207\377\0\0\0""1\0\0\0%\0\0\0\32\0\0\0\22\0\0\0\12\0\0\0\5\0\0\0\1\0"
-  "\0\0\0\0\0\0\1\0\0\0\4\0\0\0\13\0\0\0\25\0\0\0\37\0\0\0.\0\0\0:\11\25"
-  "'V\40J\207\377r\237\317\377L|\265\377r\237\317\377\40J\207\377\10\24"
-  "%[\0\0\0\77\0\0\0""0\0\0\0\40\0\0\0\23\0\0\0\14\0\0\0\5\0\0\0\1\0\0\0"
-  "\0\0\0\0\1\0\0\0\3\0\0\0\11\0\0\0\22\0\0\0\35\0\0\0+\0\0\0""6\0\0\0\77"
-  "\10\24%[\40J\207\377r\237\317\377\40J\207\377\10\23#^\0\0\0D\0\0\0""9"
-  "\0\0\0*\0\0\0\31\0\0\0\16\0\0\0\7\0\0\0\3\0\0\0\1\0\0\0\0\0\0\0\0\0\0"
-  "\0\2\0\0\0\4\0\0\0\11\0\0\0\21\0\0\0\32\0\0\0!\0\0\0(\0\0\0""1\12\30"
-  ",L\40J\207\377\12\30+M\0\0\0""4\0\0\0+\0\0\0!\0\0\0\25\0\0\0\14\0\0\0"
-  "\5\0\0\0\2\0\0\0\1\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\0\0\0\2\0"
-  "\0\0\5\0\0\0\11\0\0\0\13\0\0\0\16\0\0\0\21\0\0\0\26\21(I.\0\0\0\25\0"
-  "\0\0\22\0\0\0\15\0\0\0\12\0\0\0\7\0\0\0\3\0\0\0\1\0\0\0\0\0\0\0\0\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\2\0\0\0\2"
-  "\0\0\0\2\0\0\0\2\0\0\0\3\0\0\0\3\0\0\0\2\0\0\0\2\0\0\0\1\0\0\0\1\0\0"
-  "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"};
+static const guchar move_data[] = {
+    ""
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\40J\207\31\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\40J\207\31\40J\207\377"
+    "\40J\207\31\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\40J\207\31\40J\207\377r\237\317\377\40J\207\377\40"
+    "J\207\31\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\40J\207\31\40J\207\377r\237\317\377L|\265\377r\237\317\377\40J\207\377"
+    "\40J\207\31\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\40J\207"
+    "\377r\237\317\377L|\265\377L|\265\377L|\265\377r\237\317\377\40J\207"
+    "\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\40J\207\377"
+    "\40J\207\377\40J\207\377S\203\272\377\40J\207\377\40J\207\377\40J\207"
+    "\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\40J\207\377Y\210\276\377\40J\207\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\40J\207\31\40J\207\377\40J\207\377\0\0\0\0\0\0\0\0\0\0\0\0\40"
+    "J\207\377b\221\304\377\40J\207\377\0\0\0\0\0\0\0\0\0\0\0\0\40J\207\377"
+    "\40J\207\377\40J\207\31\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\40J\207\31\40J\207\377r\237\317\377\40J\207\377\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\40J\207\377r\237\317\377\40J\207\377\0\0\0\0\0\0\0\0\0\0\0\0\40"
+    "J\207\377r\237\317\377\40J\207\377\40J\207\31\0\0\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\40J\207\31\40J\207\377r\237\317\377L|\265\377\40J\207\377\40"
+    "J\207\377\40J\207\377\40J\207\377\40J\207\377r\237\317\377\40J\207\377"
+    "\40J\207\377\40J\207\377\40J\207\377\40J\207\377L|\265\377r\237\317\377"
+    "\40J\207\377\40J\207\31\0\0\0\0\0\0\0\0\40J\207\31\40J\207\377r\237\317"
+    "\377L|\265\377L|\265\377S\203\272\377Y\210\276\377b\221\304\377r\237"
+    "\317\377r\237\317\377r\237\317\377r\237\317\377r\237\317\377b\221\304"
+    "\377Y\210\276\377S\203\272\377L|\265\377L|\265\377r\237\317\377\40J\207"
+    "\377\40J\207\31\0\0\0\0\0\0\0\0\40J\207\31\40J\207\377r\237\317\377L"
+    "|\265\377\40J\207\377\40J\207\377\40J\207\377\40J\207\377\40J\207\377"
+    "r\237\317\377\40J\207\377\40J\207\377\40J\207\377\40J\207\377\40J\207"
+    "\377L|\265\377r\237\317\377\40J\207\377\40J\207\31\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\40J\207\31\40J\207\377r\237\317\377\40J\207\377\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\40J\207\377r\237\317\377\40J\207\377\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\40J\207\377r\237\317\377\40J\207\377\40J\207\31\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\40J\207\31\40J\207\377\40J\207"
+    "\377\0\0\0\0\0\0\0\1\0\0\0\1\40J\207\377b\221\304\377\40J\207\377\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\40J\207\377\40J\207\377\40J\207\31\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\0\0\0\1\0\0\0\3\0"
+    "\0\0\6\0\0\0\10\0\0\0\11\40J\207\377Y\210\276\377\40J\207\377\0\0\0\12"
+    "\0\0\0\6\0\0\0\5\0\0\0\4\0\0\0\3\0\0\0\2\0\0\0\2\0\0\0\1\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\1\0\0\0\2\0\0\0\5\0\0\0\10\0\0\0\16\0\0\0\26\40J\207"
+    "\377\40J\207\377\40J\207\377S\203\272\377\40J\207\377\40J\207\377\40"
+    "J\207\377\0\0\0\26\0\0\0\20\0\0\0\14\0\0\0\11\0\0\0\6\0\0\0\3\0\0\0\1"
+    "\0\0\0\0\0\0\0\0\0\0\0\3\0\0\0\7\0\0\0\16\0\0\0\25\0\0\0!\0\0\0-\40J"
+    "\207\377r\237\317\377L|\265\377L|\265\377L|\265\377r\237\317\377\40J"
+    "\207\377\0\0\0"
+    "1\0\0\0%\0\0\0\32\0\0\0\22\0\0\0\12\0\0\0\5\0\0\0\1\0"
+    "\0\0\0\0\0\0\1\0\0\0\4\0\0\0\13\0\0\0\25\0\0\0\37\0\0\0.\0\0\0:\11\25"
+    "'V\40J\207\377r\237\317\377L|\265\377r\237\317\377\40J\207\377\10\24"
+    "%[\0\0\0\77\0\0\0"
+    "0\0\0\0\40\0\0\0\23\0\0\0\14\0\0\0\5\0\0\0\1\0\0\0"
+    "\0\0\0\0\1\0\0\0\3\0\0\0\11\0\0\0\22\0\0\0\35\0\0\0+\0\0\0"
+    "6\0\0\0\77"
+    "\10\24%[\40J\207\377r\237\317\377\40J\207\377\10\23#^\0\0\0D\0\0\0"
+    "9"
+    "\0\0\0*\0\0\0\31\0\0\0\16\0\0\0\7\0\0\0\3\0\0\0\1\0\0\0\0\0\0\0\0\0\0"
+    "\0\2\0\0\0\4\0\0\0\11\0\0\0\21\0\0\0\32\0\0\0!\0\0\0(\0\0\0"
+    "1\12\30"
+    ",L\40J\207\377\12\30+M\0\0\0"
+    "4\0\0\0+\0\0\0!\0\0\0\25\0\0\0\14\0\0\0"
+    "\5\0\0\0\2\0\0\0\1\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1\0\0\0\2\0"
+    "\0\0\5\0\0\0\11\0\0\0\13\0\0\0\16\0\0\0\21\0\0\0\26\21(I.\0\0\0\25\0"
+    "\0\0\22\0\0\0\15\0\0\0\12\0\0\0\7\0\0\0\3\0\0\0\1\0\0\0\0\0\0\0\0\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\2\0\0\0\2"
+    "\0\0\0\2\0\0\0\2\0\0\0\3\0\0\0\3\0\0\0\2\0\0\0\2\0\0\0\1\0\0\0\1\0\0"
+    "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
+};
 
 static const icon move = {
-  .colorspace = GDK_COLORSPACE_RGB,
-  .has_alpha = 1,
-  .bits_per_sample = 8,
-  .width = 22,
-  .height = 22,
-  .rowstride = 88,
-  .data = move_data,
+    .colorspace      = GDK_COLORSPACE_RGB,
+    .has_alpha       = 1,
+    .bits_per_sample = 8,
+    .width           = 22,
+    .height          = 22,
+    .rowstride       = 88,
+    .data            = move_data,
 };
 
 /* -------------------  Pointer tool icon  -------------------------- */
 /* GdkPixbuf RGBA C-Source image dump */
 
-static const guchar pointer_data[] =
-{ ""
-  "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\363\363\363"
-  "\226\377\377\377(\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\377\364\364"
-  "\364\354\377\377\377\37\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\376sss\374\364\364"
-  "\364\345\377\377\377\27\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\376\376\376\376\1\1\1\377\204\204\204\372\363"
-  "\363\363\333\377\377\377\20\377\377\377\0\377\377\377\0\377\377\377\0"
-  "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\376\376\376\375\2\2\2\377\0\0\0\377\225\225\225\370"
-  "\362\362\362\321\377\377\377\13\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\375\375\375\375\3\3\3\377\0\0\0\377\1\1\1\377\245\245\245\366\362"
-  "\362\362\303\377\377\377\6\377\377\377\0\377\377\377\0\377\377\377\0"
-  "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\375\375\375"
-  "\374\4\4\4\377\0\0\0\377\0\0\0\377\3\3\3\377\264\264\264\365\362\362"
-  "\362\265\377\377\377\3\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\374\374\374\374\5\5\5\377\0\0"
-  "\0\377\0\0\0\377\0\0\0\377\6\6\6\377\302\302\302\364\363\363\363\245"
-  "\377\377\377\1\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\374\374\374\374\6\6\6\377\0\0\0\377\0\0\0\377\0\0\0"
-  "\377\0\0\0\377\13\13\13\377\316\316\316\364\365\365\365\224\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\374\374\374"
-  "\373\7\7\7\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\20\20"
-  "\20\377\331\331\331\364\365\365\365\202\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\373\373\373\373\10\10\10\377\0\0\0\377\0\0\0"
-  "\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\26\26\26\377\343\343\343"
-  "\364\370\370\370o\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\373\373\373"
-  "\372\11\11\11\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0"
-  "\0\0\377\0\0\0\377\36\36\36\377\352\352\352\364\374\374\374^\377\377"
-  "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
-  "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
-  "\377\0\377\377\377\0\372\372\372\372\12\12\12\377\0\0\0\377\0\0\0\377"
-  "\0\0\0\377\0\0\0\377\0\0\0\377\24\24\24\377\31\31\31\377\23\23\23\377"
-  "444\377\362\362\362\366\377\377\377O\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\372\372\372\371"
-  "\13\13\13\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\3\3\3\377\361\361"
-  "\361\372\371\371\371\366\370\370\370\366\372\372\372\371\375\375\375"
-  "\374\362\362\362\305\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
-  "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
-  "\377\0\377\377\377\0\377\377\377\0\372\372\372\370\14\14\14\377\0\0\0"
-  "\377:::\377nnn\370\0\0\0\377\0\0\0\377\224\224\224\370\362\362\362\243"
-  "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\371\371\371\370\15\15\15\377(((\377\360\360\360\366\371\371\371\371"
-  "\20\20\20\377\0\0\0\377\16\16\16\377\356\356\356\365\377\377\3776\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\371\371\371\370"
-  "'''\377\347\347\347\365\374\374\374_\356\356\356\276ZZZ\377\0\0\0\377"
-  "\0\0\0\377ZZZ\376\362\362\362\326\377\377\377\2\377\377\377\0\377\377"
-  "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
-  "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
-  "\377\0\377\377\377\0\371\371\371\367\337\337\337\366\365\365\365}\377"
-  "\377\377\0\377\377\377a\262\262\262\363\0\0\0\377\0\0\0\377\0\0\0\377"
-  "\311\311\311\362\375\375\375g\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\372\372\372\362\362\362\362\234\377\377\377\0\377\377\377\0\377\377"
-  "\377\24\366\366\366\370\7\7\7\377\0\0\0\377\0\0\0\377...\377\367\367"
-  "\367\363\377\377\377\17\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\24\377"
-  "\377\377\2\377\377\377\0\377\377\377\0\377\377\377\0\355\355\355\320"
-  "JJJ\377\11\11\11\377lll\376\351\351\351\364\356\356\356\305\377\377\377"
-  "\6\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
-  "\0\377\377\377\0\377\377\377\0\373\373\373s\324\324\324\372\360\360\360"
-  "\366\356\356\356\270\377\377\3773\377\377\377\0\377\377\377\0\377\377"
-  "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
-  "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
-  "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
-  "\377\0\377\377\377\0\377\377\377\24\366\366\366\207\377\377\377(\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
-  "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0"};
+static const guchar pointer_data[] = {
+    ""
+    "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\363\363\363"
+    "\226\377\377\377(\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\377\364\364"
+    "\364\354\377\377\377\37\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\376sss\374\364\364"
+    "\364\345\377\377\377\27\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\376\376\376\376\1\1\1\377\204\204\204\372\363"
+    "\363\363\333\377\377\377\20\377\377\377\0\377\377\377\0\377\377\377\0"
+    "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\376\376\376\375\2\2\2\377\0\0\0\377\225\225\225\370"
+    "\362\362\362\321\377\377\377\13\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\375\375\375\375\3\3\3\377\0\0\0\377\1\1\1\377\245\245\245\366\362"
+    "\362\362\303\377\377\377\6\377\377\377\0\377\377\377\0\377\377\377\0"
+    "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\375\375\375"
+    "\374\4\4\4\377\0\0\0\377\0\0\0\377\3\3\3\377\264\264\264\365\362\362"
+    "\362\265\377\377\377\3\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\374\374\374\374\5\5\5\377\0\0"
+    "\0\377\0\0\0\377\0\0\0\377\6\6\6\377\302\302\302\364\363\363\363\245"
+    "\377\377\377\1\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\374\374\374\374\6\6\6\377\0\0\0\377\0\0\0\377\0\0\0"
+    "\377\0\0\0\377\13\13\13\377\316\316\316\364\365\365\365\224\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\374\374\374"
+    "\373\7\7\7\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\20\20"
+    "\20\377\331\331\331\364\365\365\365\202\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\373\373\373\373\10\10\10\377\0\0\0\377\0\0\0"
+    "\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\26\26\26\377\343\343\343"
+    "\364\370\370\370o\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\373\373\373"
+    "\372\11\11\11\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0"
+    "\0\0\377\0\0\0\377\36\36\36\377\352\352\352\364\374\374\374^\377\377"
+    "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
+    "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
+    "\377\0\377\377\377\0\372\372\372\372\12\12\12\377\0\0\0\377\0\0\0\377"
+    "\0\0\0\377\0\0\0\377\0\0\0\377\24\24\24\377\31\31\31\377\23\23\23\377"
+    "444\377\362\362\362\366\377\377\377O\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\372\372\372\371"
+    "\13\13\13\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\3\3\3\377\361\361"
+    "\361\372\371\371\371\366\370\370\370\366\372\372\372\371\375\375\375"
+    "\374\362\362\362\305\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
+    "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
+    "\377\0\377\377\377\0\377\377\377\0\372\372\372\370\14\14\14\377\0\0\0"
+    "\377:::\377nnn\370\0\0\0\377\0\0\0\377\224\224\224\370\362\362\362\243"
+    "\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\371\371\371\370\15\15\15\377(((\377\360\360\360\366\371\371\371\371"
+    "\20\20\20\377\0\0\0\377\16\16\16\377\356\356\356\365\377\377\3776\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\371\371\371\370"
+    "'''\377\347\347\347\365\374\374\374_\356\356\356\276ZZZ\377\0\0\0\377"
+    "\0\0\0\377ZZZ\376\362\362\362\326\377\377\377\2\377\377\377\0\377\377"
+    "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
+    "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
+    "\377\0\377\377\377\0\371\371\371\367\337\337\337\366\365\365\365}\377"
+    "\377\377\0\377\377\377a\262\262\262\363\0\0\0\377\0\0\0\377\0\0\0\377"
+    "\311\311\311\362\375\375\375g\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\372\372\372\362\362\362\362\234\377\377\377\0\377\377\377\0\377\377"
+    "\377\24\366\366\366\370\7\7\7\377\0\0\0\377\0\0\0\377...\377\367\367"
+    "\367\363\377\377\377\17\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\24\377"
+    "\377\377\2\377\377\377\0\377\377\377\0\377\377\377\0\355\355\355\320"
+    "JJJ\377\11\11\11\377lll\376\351\351\351\364\356\356\356\305\377\377\377"
+    "\6\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377"
+    "\0\377\377\377\0\377\377\377\0\373\373\373s\324\324\324\372\360\360\360"
+    "\366\356\356\356\270\377\377\3773\377\377\377\0\377\377\377\0\377\377"
+    "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
+    "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
+    "\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377"
+    "\377\0\377\377\377\0\377\377\377\24\366\366\366\207\377\377\377(\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377"
+    "\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0\377\377\377\0"
+};
 
 static const icon pointer = {
-  .colorspace = GDK_COLORSPACE_RGB,
-  .has_alpha = 1,
-  .bits_per_sample = 8,
-  .width = 24,
-  .height = 24,
-  .rowstride = 96,
-  .data = pointer_data,
+    .colorspace      = GDK_COLORSPACE_RGB,
+    .has_alpha       = 1,
+    .bits_per_sample = 8,
+    .width           = 24,
+    .height          = 24,
+    .rowstride       = 96,
+    .data            = pointer_data,
 };
diff --git a/src/interface.c b/src/interface.c
index 8ea1411..8da9caf 100644
--- a/src/interface.c
+++ b/src/interface.c
@@ -51,538 +51,517 @@
 #include "gerbv_icon.h"
 #include "icons.h"
 
-#define dprintf if(DEBUG) printf
+#define dprintf \
+    if (DEBUG)  \
+    printf
 
-static const gchar *gerbv_win_title = N_("Gerbv — gEDA's Gerber Viewer");
+static const gchar* gerbv_win_title = N_("Gerbv — gEDA's Gerber Viewer");
 
 /* Declared in callbacks.c */
-extern const char *gerbv_coords_pattern_mils_str;
+extern const char* gerbv_coords_pattern_mils_str;
 
-	/* ---------------------------------------------- */
-void 
-rename_main_window(char const* filename, GtkWidget *main_win)
-{
-	GString *win_title = g_string_new(NULL);
-	static GtkWidget *win = NULL;
+/* ---------------------------------------------- */
+void
+rename_main_window(const char* filename, GtkWidget* main_win) {
+    GString*          win_title = g_string_new(NULL);
+    static GtkWidget* win       = NULL;
 
-	if (main_win != NULL)
-		win = main_win;
+    if (main_win != NULL)
+        win = main_win;
 
-	g_assert(win != NULL);
+    g_assert(win != NULL);
 
-	if (filename && filename[0] != '\0') {
-		gchar *basename = g_path_get_basename(filename);
-		g_string_printf(win_title, "%s — Gerbv", basename);
-		g_free(basename);
-	} else {
-		g_string_printf(win_title, "%s", _(gerbv_win_title));
-	}
+    if (filename && filename[0] != '\0') {
+        gchar* basename = g_path_get_basename(filename);
+        g_string_printf(win_title, "%s — Gerbv", basename);
+        g_free(basename);
+    } else {
+        g_string_printf(win_title, "%s", _(gerbv_win_title));
+    }
 
-	gtk_window_set_title(GTK_WINDOW(win), win_title->str);
-	g_string_free(win_title, TRUE);
+    gtk_window_set_title(GTK_WINDOW(win), win_title->str);
+    g_string_free(win_title, TRUE);
 }
 
 /* ---------------------------------------------- */
 void
-set_window_icon (GtkWidget * this_window)
-{
-	GdkPixmap *pixmap;
-	GdkBitmap *mask;
+set_window_icon(GtkWidget* this_window) {
+    GdkPixmap* pixmap;
+    GdkBitmap* mask;
 
-	pixmap = gdk_pixmap_create_from_xpm_d (this_window->window, &mask,
-		&this_window->style->bg[GTK_STATE_NORMAL], gerbv_icon_xpm);
-	gdk_window_set_icon (this_window->window, NULL, pixmap, mask);
+    pixmap = gdk_pixmap_create_from_xpm_d(
+        this_window->window, &mask, &this_window->style->bg[GTK_STATE_NORMAL], gerbv_icon_xpm
+    );
+    gdk_window_set_icon(this_window->window, NULL, pixmap, mask);
 
-	return;
+    return;
 }
 
 /* ---------------------------------------------- */
 void
-interface_load_accels (void)
-{	
-	gchar *accel_map_filename = g_build_filename (g_get_home_dir(), GERBV_ACCELS_RELPATH, NULL);
-	if (accel_map_filename) {
-		gtk_accel_map_load (accel_map_filename);
-		g_free (accel_map_filename);
-	}
+interface_load_accels(void) {
+    gchar* accel_map_filename = g_build_filename(g_get_home_dir(), GERBV_ACCELS_RELPATH, NULL);
+    if (accel_map_filename) {
+        gtk_accel_map_load(accel_map_filename);
+        g_free(accel_map_filename);
+    }
 }
 
 /* ---------------------------------------------- */
 void
-interface_save_accels (void)
-{
-	gchar *accel_map_dirname, *accel_map_filename;
+interface_save_accels(void) {
+    gchar *accel_map_dirname, *accel_map_filename;
 
-	accel_map_filename =
-		g_build_filename (g_get_home_dir(), GERBV_ACCELS_RELPATH, NULL);
+    accel_map_filename = g_build_filename(g_get_home_dir(), GERBV_ACCELS_RELPATH, NULL);
 
-	if (!accel_map_filename)
-		return;
+    if (!accel_map_filename)
+        return;
 
-	/* Create directory if it is not present */
-	accel_map_dirname =  g_path_get_dirname (accel_map_filename);
-	g_mkdir_with_parents (accel_map_dirname,
-				S_IRUSR | S_IXUSR | S_IWUSR |
-				S_IRGRP | S_IXGRP |
-				S_IROTH | S_IXOTH);
+    /* Create directory if it is not present */
+    accel_map_dirname = g_path_get_dirname(accel_map_filename);
+    g_mkdir_with_parents(accel_map_dirname, S_IRUSR | S_IXUSR | S_IWUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
 
-	gtk_accel_map_save (accel_map_filename);
+    gtk_accel_map_save(accel_map_filename);
 
-	g_free (accel_map_dirname);
-	g_free (accel_map_filename);
+    g_free(accel_map_dirname);
+    g_free(accel_map_filename);
 }
 
 static void
-request_label_max_size_by_text (GtkWidget *label, const gchar *str)
-{
-	GtkRequisition req;
+request_label_max_size_by_text(GtkWidget* label, const gchar* str) {
+    GtkRequisition req;
 
-	gtk_label_set_text (GTK_LABEL (label), str);
+    gtk_label_set_text(GTK_LABEL(label), str);
 
-	/* Reset previous size request */
-	gtk_widget_set_size_request (label, -1, -1);
-	gtk_widget_size_request (label, &req);
-	gtk_widget_set_size_request (label, req.width, req.height);
-	gtk_label_set_text (GTK_LABEL (label), "");
+    /* Reset previous size request */
+    gtk_widget_set_size_request(label, -1, -1);
+    gtk_widget_size_request(label, &req);
+    gtk_widget_set_size_request(label, req.width, req.height);
+    gtk_label_set_text(GTK_LABEL(label), "");
 }
 
-GdkPixbuf *pixbuf_from_icon(const icon *icon)
-{
-  return gdk_pixbuf_new_from_data(icon->data,
-                                  icon->colorspace,
-                                  icon->has_alpha,
-                                  icon->bits_per_sample,
-                                  icon->width,
-                                  icon->height,
-                                  icon->rowstride,
-                                  NULL, NULL);
+GdkPixbuf*
+pixbuf_from_icon(const icon* icon) {
+    return gdk_pixbuf_new_from_data(
+        icon->data, icon->colorspace, icon->has_alpha, icon->bits_per_sample, icon->width, icon->height,
+        icon->rowstride, NULL, NULL
+    );
 }
 
 /* ---------------------------------------------- */
 void
-interface_create_gui (int req_width, int req_height)
-{
-	GtkStockItem stock;
-
-	GtkWidget *mainWindow;
-	GtkWidget *vbox1;
-	GtkWidget *menubar1;
-
-	GtkWidget *menuitem_file;
-	GtkWidget *menuitem_file_menu;
-	GtkWidget *new_project;
-	GtkWidget *open;
-	GtkWidget *revert;
-	GtkWidget *save;
-	GtkWidget *save_as;
-	GtkWidget *save_layer;
-	GtkWidget *save_as_layer;
-	GtkWidget *menuitem_file_export;
-	GtkWidget *menuitem_file_export_menu;
-	GtkWidget *png, *pdf, *svg, *postscript, *geda_pcb;
-	GtkWidget *rs274x, *drill, *idrill, *rs274xm, *drillm;
+interface_create_gui(int req_width, int req_height) {
+    GtkStockItem stock;
+
+    GtkWidget* mainWindow;
+    GtkWidget* vbox1;
+    GtkWidget* menubar1;
+
+    GtkWidget* menuitem_file;
+    GtkWidget* menuitem_file_menu;
+    GtkWidget* new_project;
+    GtkWidget* open;
+    GtkWidget* revert;
+    GtkWidget* save;
+    GtkWidget* save_as;
+    GtkWidget* save_layer;
+    GtkWidget* save_as_layer;
+    GtkWidget* menuitem_file_export;
+    GtkWidget* menuitem_file_export_menu;
+    GtkWidget *png, *pdf, *svg, *postscript, *geda_pcb;
+    GtkWidget *rs274x, *drill, *idrill, *rs274xm, *drillm;
 #if HAVE_LIBDXFLIB
-	GtkWidget *dxf;
+    GtkWidget* dxf;
 #endif
-	
-#if GTK_CHECK_VERSION(2,10,0)
-	GtkWidget *print;
+
+#if GTK_CHECK_VERSION(2, 10, 0)
+    GtkWidget* print;
 #endif
-	GtkWidget *quit;
-
-	GtkWidget *menuitem_edit;
-	GtkWidget *menuitem_edit_menu;
-	GtkWidget *properties_selected;
-	GtkWidget *delete_selected;
-	GtkWidget *align, *align_layers;
-	GtkWidget *menuitem_view;
-	GtkWidget *menuitem_view_menu;
-	GtkWidget *view_fullscreen;
-	GtkWidget *show_selection_on_invisible;
-	GtkWidget *show_cross_on_drill_holes;
-	GtkWidget *show_toolbar;
-	GtkWidget *show_sidepane;
-	GtkWidget *toggle_layer_visibility_item1;
-	GtkWidget *toggle_layer_visibility_item2;
-	GtkWidget *toggle_layer_visibility_item3;
-	GtkWidget *toggle_layer_visibility_item4;
-	GtkWidget *toggle_layer_visibility_item5;
-	GtkWidget *toggle_layer_visibility_item6;
-	GtkWidget *toggle_layer_visibility_item7;
-	GtkWidget *toggle_layer_visibility_item8;
-	GtkWidget *toggle_layer_visibility_item9;
-	GtkWidget *toggle_layer_visibility_item10;
-	GtkWidget *zoom_in;
-	GtkWidget *zoom_out;
-	GtkWidget *fit_to_window;
-	GtkWidget *backgroundColor;
-	GtkWidget *menuitem_view_render, *menuitem_view_render_menu;
-	GSList *menu_view_render_group;
-	GtkWidget *render_fast, *render_fast_xor, *render_normal, *render_hq;
-	GtkWidget *menuitem_view_unit, *menuitem_view_unit_menu;
-	GSList *menu_view_unit_group;
-	GtkWidget *unit_mil, *unit_mm, *unit_in;
-	GtkWidget *menuitem_layer;
-	GtkWidget *menuitem_layer_menu;
-	GtkWidget *layer_visibility;
-	GtkWidget *layer_visibility_all_on;
-	GtkWidget *layer_visibility_all_off;
-	GtkWidget *layer_invert;
-	GtkWidget *layer_color;
-	GtkWidget *layer_reload;
-	GtkWidget *layer_edit;
-	GtkWidget *layer_format;
-	GtkWidget *layer_up;
-	GtkWidget *layer_down;
-	GtkWidget *layer_remove;
-	GtkWidget *menuitem_analyze;
-	GtkWidget *menuitem_analyze_menu;
-	GtkWidget *analyze_active_gerbers;
-	GtkWidget *analyze_active_drill;
-	GtkWidget *analyze_benchmark;
-	/*GtkWidget *control_gerber_options;*/
-	GtkWidget *menuitem_tools;
-	GtkWidget *menuitem_tools_menu;
-	GtkWidget *toggletoolbutton_pointer;
-	GtkWidget *pointer_tool;
-	GdkPixbuf *pointerpixbuf;
-	GtkWidget *pointerimage;
-	GtkWidget *pan_tool;
-	GtkWidget *zoom_tool;
-	GtkWidget *measure_tool;
-	GtkWidget *menuitem_help;
-	GtkWidget *layer_visibility_menu;
-	GtkWidget *layer_visibility_main_menu;
-	GtkWidget *menuitem_help_menu;
-	/*GtkWidget *online_manual;*/
-	GtkWidget *about;
-	GtkWidget *bugs_menuitem;
-	GtkWidget *image34;
-	GtkWidget *toolbar_hbox;
-	GtkWidget *handlebox;
-	GtkWidget *button_toolbar;
-	/*GtkIconSize tmp_toolbar_icon_size;*/
-	GtkWidget *toolbutton_new;
-	GtkWidget *toolbutton_open;
-	GtkWidget *toolbutton_revert;
-	GtkWidget *toolbutton_save;
-	GtkWidget *separatortoolitem1;
-#if GTK_CHECK_VERSION(2,10,0)
-	GtkWidget *toolbutton_print;
-	GtkWidget *separatortoolitem2;
+    GtkWidget* quit;
+
+    GtkWidget* menuitem_edit;
+    GtkWidget* menuitem_edit_menu;
+    GtkWidget* properties_selected;
+    GtkWidget* delete_selected;
+    GtkWidget *align, *align_layers;
+    GtkWidget* menuitem_view;
+    GtkWidget* menuitem_view_menu;
+    GtkWidget* view_fullscreen;
+    GtkWidget* show_selection_on_invisible;
+    GtkWidget* show_cross_on_drill_holes;
+    GtkWidget* show_toolbar;
+    GtkWidget* show_sidepane;
+    GtkWidget* toggle_layer_visibility_item1;
+    GtkWidget* toggle_layer_visibility_item2;
+    GtkWidget* toggle_layer_visibility_item3;
+    GtkWidget* toggle_layer_visibility_item4;
+    GtkWidget* toggle_layer_visibility_item5;
+    GtkWidget* toggle_layer_visibility_item6;
+    GtkWidget* toggle_layer_visibility_item7;
+    GtkWidget* toggle_layer_visibility_item8;
+    GtkWidget* toggle_layer_visibility_item9;
+    GtkWidget* toggle_layer_visibility_item10;
+    GtkWidget* zoom_in;
+    GtkWidget* zoom_out;
+    GtkWidget* fit_to_window;
+    GtkWidget* backgroundColor;
+    GtkWidget *menuitem_view_render, *menuitem_view_render_menu;
+    GSList*    menu_view_render_group;
+    GtkWidget *render_fast, *render_fast_xor, *render_normal, *render_hq;
+    GtkWidget *menuitem_view_unit, *menuitem_view_unit_menu;
+    GSList*    menu_view_unit_group;
+    GtkWidget *unit_mil, *unit_mm, *unit_in;
+    GtkWidget* menuitem_layer;
+    GtkWidget* menuitem_layer_menu;
+    GtkWidget* layer_visibility;
+    GtkWidget* layer_visibility_all_on;
+    GtkWidget* layer_visibility_all_off;
+    GtkWidget* layer_invert;
+    GtkWidget* layer_color;
+    GtkWidget* layer_reload;
+    GtkWidget* layer_edit;
+    GtkWidget* layer_format;
+    GtkWidget* layer_up;
+    GtkWidget* layer_down;
+    GtkWidget* layer_remove;
+    GtkWidget* menuitem_analyze;
+    GtkWidget* menuitem_analyze_menu;
+    GtkWidget* analyze_active_gerbers;
+    GtkWidget* analyze_active_drill;
+    GtkWidget* analyze_benchmark;
+    /*GtkWidget *control_gerber_options;*/
+    GtkWidget* menuitem_tools;
+    GtkWidget* menuitem_tools_menu;
+    GtkWidget* toggletoolbutton_pointer;
+    GtkWidget* pointer_tool;
+    GdkPixbuf* pointerpixbuf;
+    GtkWidget* pointerimage;
+    GtkWidget* pan_tool;
+    GtkWidget* zoom_tool;
+    GtkWidget* measure_tool;
+    GtkWidget* menuitem_help;
+    GtkWidget* layer_visibility_menu;
+    GtkWidget* layer_visibility_main_menu;
+    GtkWidget* menuitem_help_menu;
+    /*GtkWidget *online_manual;*/
+    GtkWidget* about;
+    GtkWidget* bugs_menuitem;
+    GtkWidget* image34;
+    GtkWidget* toolbar_hbox;
+    GtkWidget* handlebox;
+    GtkWidget* button_toolbar;
+    /*GtkIconSize tmp_toolbar_icon_size;*/
+    GtkWidget* toolbutton_new;
+    GtkWidget* toolbutton_open;
+    GtkWidget* toolbutton_revert;
+    GtkWidget* toolbutton_save;
+    GtkWidget* separatortoolitem1;
+#if GTK_CHECK_VERSION(2, 10, 0)
+    GtkWidget* toolbutton_print;
+    GtkWidget* separatortoolitem2;
 #endif
-	GtkWidget *toolbutton_zoom_in;
-	GtkWidget *toolbutton_zoom_out;
-	GtkWidget *toolbutton_zoom_fit;
-	/* Implement these tool buttons later when we have icons */
-/*	GtkWidget *separatortoolitem3; */
-/*	GtkWidget *toolbutton_analyze; */
-/*	GtkWidget *toolbutton_validate;*/
-/*	GtkWidget *toolbutton_control; */
-	GtkWidget *separatortoolitem4;
-	GtkWidget *toggletoolbutton_pan;
-	GtkWidget *toggletoolbutton_zoom;
-	GtkWidget *toggletoolbutton_measure;
-	GtkWidget *hpaned1;
-	GtkWidget *sidepane_vbox;
-	GtkWidget *sidepane_notebook;
-	GtkWidget *vbox10;
-	GtkWidget *hbox4;
-	GtkWidget *render_combobox;
-	GtkWidget *scrolledwindow1;
-	GtkWidget *hbox1;
-	GtkWidget *button4;
-	GtkWidget *image8;
-	GtkWidget *button5;
-	GtkWidget *image9;
-	GtkWidget *button6;
-	GtkWidget *image10;
-	GtkWidget *button7;
-	GtkWidget *image11;
-	GtkWidget *Layer_label;
-	GtkWidget *vbox11;
-	GtkWidget *messages_scrolledwindow;
-	GtkWidget *message_textview;
-	GtkWidget *clear_messages_button;
-	GtkWidget *Message_label;
-	GtkWidget *vbox2;
-	GtkWidget *main_view_table;
-	GtkWidget *hRuler;
-	GtkWidget *vRuler;
-	GtkWidget *hbox5;
-	GtkWidget *statusbar_label_left;
-	GtkWidget *statusUnitComboBox;
-	GtkWidget *statusbar_label_right;
-	GtkWidget *drawingarea, *hAdjustment, *vAdjustment, *hScrollbar, *vScrollbar;
-	
-	GtkAccelGroup *accel_group;
-	GtkTooltips *tooltips;
-
-	/* Inline icons */
-	GdkPixbuf *zoompixbuf;
-	GtkWidget *zoomimage;
-	GdkPixbuf *measurepixbuf;
-	GtkWidget *measureimage;
-	GdkPixbuf *movepixbuf;
-	GtkWidget *moveimage;
-
-	GtkWidget *tempImage;
-
-	gchar str_coord[MAX_COORDLEN];
-
-	const GtkTargetEntry dragTargetEntries[] = {
-		{ "text/uri-list", 0, 1 },
-	};
-
-	GSettingsSchema *settings_schema = NULL;
-	const gchar *settings_id = "org.geda-user.gerbv";
-	screen.settings = NULL;
-
-	/* Try to find settings schema, GSETTINGS_SCHEMA_DIR env. variable was
-	 * updated with fallback schema directory */
-	GSettingsSchemaSource *settings_source = g_settings_schema_source_get_default();
-	if (NULL != settings_source) {
-		settings_schema = g_settings_schema_source_lookup(
-		    settings_source,
-		    settings_id, TRUE);
-	}
+    GtkWidget* toolbutton_zoom_in;
+    GtkWidget* toolbutton_zoom_out;
+    GtkWidget* toolbutton_zoom_fit;
+    /* Implement these tool buttons later when we have icons */
+    /*	GtkWidget *separatortoolitem3; */
+    /*	GtkWidget *toolbutton_analyze; */
+    /*	GtkWidget *toolbutton_validate;*/
+    /*	GtkWidget *toolbutton_control; */
+    GtkWidget* separatortoolitem4;
+    GtkWidget* toggletoolbutton_pan;
+    GtkWidget* toggletoolbutton_zoom;
+    GtkWidget* toggletoolbutton_measure;
+    GtkWidget* hpaned1;
+    GtkWidget* sidepane_vbox;
+    GtkWidget* sidepane_notebook;
+    GtkWidget* vbox10;
+    GtkWidget* hbox4;
+    GtkWidget* render_combobox;
+    GtkWidget* scrolledwindow1;
+    GtkWidget* hbox1;
+    GtkWidget* button4;
+    GtkWidget* image8;
+    GtkWidget* button5;
+    GtkWidget* image9;
+    GtkWidget* button6;
+    GtkWidget* image10;
+    GtkWidget* button7;
+    GtkWidget* image11;
+    GtkWidget* Layer_label;
+    GtkWidget* vbox11;
+    GtkWidget* messages_scrolledwindow;
+    GtkWidget* message_textview;
+    GtkWidget* clear_messages_button;
+    GtkWidget* Message_label;
+    GtkWidget* vbox2;
+    GtkWidget* main_view_table;
+    GtkWidget* hRuler;
+    GtkWidget* vRuler;
+    GtkWidget* hbox5;
+    GtkWidget* statusbar_label_left;
+    GtkWidget* statusUnitComboBox;
+    GtkWidget* statusbar_label_right;
+    GtkWidget *drawingarea, *hAdjustment, *vAdjustment, *hScrollbar, *vScrollbar;
+
+    GtkAccelGroup* accel_group;
+    GtkTooltips*   tooltips;
+
+    /* Inline icons */
+    GdkPixbuf* zoompixbuf;
+    GtkWidget* zoomimage;
+    GdkPixbuf* measurepixbuf;
+    GtkWidget* measureimage;
+    GdkPixbuf* movepixbuf;
+    GtkWidget* moveimage;
+
+    GtkWidget* tempImage;
+
+    gchar str_coord[MAX_COORDLEN];
+
+    const GtkTargetEntry dragTargetEntries[] = {
+        {"text/uri-list", 0, 1},
+    };
+
+    GSettingsSchema* settings_schema = NULL;
+    const gchar*     settings_id     = "org.geda-user.gerbv";
+    screen.settings                  = NULL;
+
+    /* Try to find settings schema, GSETTINGS_SCHEMA_DIR env. variable was
+     * updated with fallback schema directory */
+    GSettingsSchemaSource* settings_source = g_settings_schema_source_get_default();
+    if (NULL != settings_source) {
+        settings_schema = g_settings_schema_source_lookup(settings_source, settings_id, TRUE);
+    }
 
-	if (NULL != settings_schema) {
-		g_settings_schema_unref(settings_schema);
-		screen.settings = g_settings_new(settings_id);
-	}
+    if (NULL != settings_schema) {
+        g_settings_schema_unref(settings_schema);
+        screen.settings = g_settings_new(settings_id);
+    }
 
-	pointerpixbuf = pixbuf_from_icon(&pointer);
-	movepixbuf = pixbuf_from_icon(&move);
-	zoompixbuf = pixbuf_from_icon(&lzoom);
-	measurepixbuf = pixbuf_from_icon(&ruler);
-
-	tooltips = gtk_tooltips_new();
-	accel_group = gtk_accel_group_new ();
-
-	mainWindow = gtk_window_new (GTK_WINDOW_TOPLEVEL);
-	screen.win.topLevelWindow = mainWindow;
-
-	vbox1 = gtk_vbox_new (FALSE, 0);
-	gtk_container_add (GTK_CONTAINER (mainWindow), vbox1);
-
-	menubar1 = gtk_menu_bar_new ();
-	gtk_box_pack_start (GTK_BOX (vbox1), menubar1, FALSE, FALSE, 0);
-
-	gtk_drag_dest_set (mainWindow, GTK_DEST_DEFAULT_ALL, dragTargetEntries,
-			1, GDK_ACTION_COPY | GDK_ACTION_MOVE | GDK_ACTION_LINK);
-	gtk_signal_connect (GTK_OBJECT(mainWindow), "drag-data-received",
-			GTK_SIGNAL_FUNC(callbacks_file_drop_event), NULL);
-
-	/* --- File menu --- */
-	menuitem_file = gtk_menu_item_new_with_mnemonic (_("_File"));
-	gtk_container_add (GTK_CONTAINER (menubar1), menuitem_file);
-
-	menuitem_file_menu = gtk_menu_new ();
-	gtk_menu_set_accel_group (GTK_MENU(menuitem_file_menu), accel_group);
-	gtk_menu_set_accel_path (GTK_MENU(menuitem_file_menu), ACCEL_FILE);
-	gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem_file), menuitem_file_menu);
-	
-	/* File menu items dealing individual layers. */
-
-	open = gtk_menu_item_new_with_mnemonic (_("_Open"));
-	SET_ACCELS (open, ACCEL_FILE_OPEN_LAYER);
-	gtk_container_add (GTK_CONTAINER (menuitem_file_menu), open);
-	gtk_tooltips_set_tip (tooltips, open,
-			_("Open Gerbv project, Gerber, drill, "
-				"or pick&place files"), NULL);
-
-	save_layer = gtk_menu_item_new_with_mnemonic (_("_Save active layer"));
-	screen.win.curFileMenuItem[0] = save_layer;
-	gtk_tooltips_set_tip (tooltips, save_layer, _("Save the active layer"), NULL);
-	SET_ACCELS (save_layer, ACCEL_FILE_SAVE_LAYER);
-	gtk_container_add (GTK_CONTAINER (menuitem_file_menu), save_layer);
-	
-	save_as_layer = gtk_menu_item_new_with_mnemonic (_("Save active layer _as..."));
-	screen.win.curFileMenuItem[1] = save_as_layer;
-	gtk_tooltips_set_tip (tooltips, save_as_layer, _("Save the active layer to a new file"), NULL);
-	SET_ACCELS (save_as_layer, ACCEL_FILE_SAVE_LAYER_AS);
-	gtk_container_add (GTK_CONTAINER (menuitem_file_menu), save_as_layer);
-
-	revert = gtk_image_menu_item_new_from_stock (GTK_STOCK_REVERT_TO_SAVED, NULL);
-	/* Change stock  label */
-	gtk_menu_item_set_label (GTK_MENU_ITEM (revert), _("_Revert all"));
-	screen.win.curFileMenuItem[2] = revert;
-	SET_ACCELS_FROM_STOCK (revert, GTK_STOCK_REVERT_TO_SAVED, ACCEL_FILE_REVERT);
-	gtk_tooltips_set_tip (tooltips, revert, _("Reload all layers"), NULL);
-	gtk_container_add (GTK_CONTAINER (menuitem_file_menu), revert);
-
-	/* File menu items dealing with exporting different types of files. */
-
-	gtk_container_add (GTK_CONTAINER (menuitem_file_menu),
-			gtk_separator_menu_item_new ());
-
-	menuitem_file_export = gtk_menu_item_new_with_mnemonic (_("_Export"));
-	screen.win.curFileMenuItem[3] = menuitem_file_export;
-	gtk_tooltips_set_tip (tooltips, menuitem_file_export,
-			_("Export to a new format"), NULL);
-	gtk_container_add (GTK_CONTAINER (menuitem_file_menu), menuitem_file_export);
-
-	menuitem_file_export_menu = gtk_menu_new ();
-	gtk_menu_set_accel_group (GTK_MENU(menuitem_file_export_menu), accel_group);
-	gtk_menu_set_accel_path (GTK_MENU(menuitem_file_export_menu), ACCEL_FILE_EXPORT);
-	gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem_file_export), menuitem_file_export_menu);
-
-	png = gtk_menu_item_new_with_mnemonic (_("P_NG..."));
-	gtk_container_add (GTK_CONTAINER (menuitem_file_export_menu), png);
-	gtk_tooltips_set_tip (tooltips, png, _("Export visible layers to a PNG file"), NULL);
-	
-	pdf = gtk_menu_item_new_with_mnemonic (_("P_DF..."));
-	gtk_container_add (GTK_CONTAINER (menuitem_file_export_menu), pdf);
-	gtk_tooltips_set_tip (tooltips, pdf, _("Export visible layers to a PDF file"), NULL);
-
-	svg = gtk_menu_item_new_with_mnemonic (_("_SVG..."));
-	gtk_container_add (GTK_CONTAINER (menuitem_file_export_menu), svg);
-	gtk_tooltips_set_tip (tooltips, svg, _("Export visible layers to a SVG file"), NULL);
-	
-	postscript = gtk_menu_item_new_with_mnemonic (_("_PostScript..."));
-	gtk_container_add (GTK_CONTAINER (menuitem_file_export_menu), postscript);
-	gtk_tooltips_set_tip (tooltips, postscript, _("Export visible layers to a PostScript file"), NULL);
+    pointerpixbuf = pixbuf_from_icon(&pointer);
+    movepixbuf    = pixbuf_from_icon(&move);
+    zoompixbuf    = pixbuf_from_icon(&lzoom);
+    measurepixbuf = pixbuf_from_icon(&ruler);
+
+    tooltips    = gtk_tooltips_new();
+    accel_group = gtk_accel_group_new();
+
+    mainWindow                = gtk_window_new(GTK_WINDOW_TOPLEVEL);
+    screen.win.topLevelWindow = mainWindow;
+
+    vbox1 = gtk_vbox_new(FALSE, 0);
+    gtk_container_add(GTK_CONTAINER(mainWindow), vbox1);
+
+    menubar1 = gtk_menu_bar_new();
+    gtk_box_pack_start(GTK_BOX(vbox1), menubar1, FALSE, FALSE, 0);
+
+    gtk_drag_dest_set(
+        mainWindow, GTK_DEST_DEFAULT_ALL, dragTargetEntries, 1, GDK_ACTION_COPY | GDK_ACTION_MOVE | GDK_ACTION_LINK
+    );
+    gtk_signal_connect(GTK_OBJECT(mainWindow), "drag-data-received", GTK_SIGNAL_FUNC(callbacks_file_drop_event), NULL);
+
+    /* --- File menu --- */
+    menuitem_file = gtk_menu_item_new_with_mnemonic(_("_File"));
+    gtk_container_add(GTK_CONTAINER(menubar1), menuitem_file);
+
+    menuitem_file_menu = gtk_menu_new();
+    gtk_menu_set_accel_group(GTK_MENU(menuitem_file_menu), accel_group);
+    gtk_menu_set_accel_path(GTK_MENU(menuitem_file_menu), ACCEL_FILE);
+    gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem_file), menuitem_file_menu);
+
+    /* File menu items dealing individual layers. */
+
+    open = gtk_menu_item_new_with_mnemonic(_("_Open"));
+    SET_ACCELS(open, ACCEL_FILE_OPEN_LAYER);
+    gtk_container_add(GTK_CONTAINER(menuitem_file_menu), open);
+    gtk_tooltips_set_tip(
+        tooltips, open,
+        _("Open Gerbv project, Gerber, drill, "
+          "or pick&place files"),
+        NULL
+    );
+
+    save_layer                    = gtk_menu_item_new_with_mnemonic(_("_Save active layer"));
+    screen.win.curFileMenuItem[0] = save_layer;
+    gtk_tooltips_set_tip(tooltips, save_layer, _("Save the active layer"), NULL);
+    SET_ACCELS(save_layer, ACCEL_FILE_SAVE_LAYER);
+    gtk_container_add(GTK_CONTAINER(menuitem_file_menu), save_layer);
+
+    save_as_layer                 = gtk_menu_item_new_with_mnemonic(_("Save active layer _as..."));
+    screen.win.curFileMenuItem[1] = save_as_layer;
+    gtk_tooltips_set_tip(tooltips, save_as_layer, _("Save the active layer to a new file"), NULL);
+    SET_ACCELS(save_as_layer, ACCEL_FILE_SAVE_LAYER_AS);
+    gtk_container_add(GTK_CONTAINER(menuitem_file_menu), save_as_layer);
+
+    revert = gtk_image_menu_item_new_from_stock(GTK_STOCK_REVERT_TO_SAVED, NULL);
+    /* Change stock  label */
+    gtk_menu_item_set_label(GTK_MENU_ITEM(revert), _("_Revert all"));
+    screen.win.curFileMenuItem[2] = revert;
+    SET_ACCELS_FROM_STOCK(revert, GTK_STOCK_REVERT_TO_SAVED, ACCEL_FILE_REVERT);
+    gtk_tooltips_set_tip(tooltips, revert, _("Reload all layers"), NULL);
+    gtk_container_add(GTK_CONTAINER(menuitem_file_menu), revert);
+
+    /* File menu items dealing with exporting different types of files. */
+
+    gtk_container_add(GTK_CONTAINER(menuitem_file_menu), gtk_separator_menu_item_new());
+
+    menuitem_file_export          = gtk_menu_item_new_with_mnemonic(_("_Export"));
+    screen.win.curFileMenuItem[3] = menuitem_file_export;
+    gtk_tooltips_set_tip(tooltips, menuitem_file_export, _("Export to a new format"), NULL);
+    gtk_container_add(GTK_CONTAINER(menuitem_file_menu), menuitem_file_export);
+
+    menuitem_file_export_menu = gtk_menu_new();
+    gtk_menu_set_accel_group(GTK_MENU(menuitem_file_export_menu), accel_group);
+    gtk_menu_set_accel_path(GTK_MENU(menuitem_file_export_menu), ACCEL_FILE_EXPORT);
+    gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem_file_export), menuitem_file_export_menu);
+
+    png = gtk_menu_item_new_with_mnemonic(_("P_NG..."));
+    gtk_container_add(GTK_CONTAINER(menuitem_file_export_menu), png);
+    gtk_tooltips_set_tip(tooltips, png, _("Export visible layers to a PNG file"), NULL);
+
+    pdf = gtk_menu_item_new_with_mnemonic(_("P_DF..."));
+    gtk_container_add(GTK_CONTAINER(menuitem_file_export_menu), pdf);
+    gtk_tooltips_set_tip(tooltips, pdf, _("Export visible layers to a PDF file"), NULL);
+
+    svg = gtk_menu_item_new_with_mnemonic(_("_SVG..."));
+    gtk_container_add(GTK_CONTAINER(menuitem_file_export_menu), svg);
+    gtk_tooltips_set_tip(tooltips, svg, _("Export visible layers to a SVG file"), NULL);
+
+    postscript = gtk_menu_item_new_with_mnemonic(_("_PostScript..."));
+    gtk_container_add(GTK_CONTAINER(menuitem_file_export_menu), postscript);
+    gtk_tooltips_set_tip(tooltips, postscript, _("Export visible layers to a PostScript file"), NULL);
 
 #if HAVE_LIBDXFLIB
-	dxf = gtk_menu_item_new_with_mnemonic (_("D_XF..."));
-	gtk_container_add (GTK_CONTAINER (menuitem_file_export_menu), dxf);
-	gtk_tooltips_set_tip (tooltips, dxf,
-			_("Export active layer to a DXF file"), NULL);
+    dxf = gtk_menu_item_new_with_mnemonic(_("D_XF..."));
+    gtk_container_add(GTK_CONTAINER(menuitem_file_export_menu), dxf);
+    gtk_tooltips_set_tip(tooltips, dxf, _("Export active layer to a DXF file"), NULL);
 #endif
 
-	gtk_container_add (GTK_CONTAINER (menuitem_file_export_menu),
-			gtk_separator_menu_item_new ());
-
-	rs274x = gtk_menu_item_new_with_mnemonic (_("RS-274X (_Gerber)..."));
-	gtk_container_add (GTK_CONTAINER (menuitem_file_export_menu), rs274x);
-	gtk_tooltips_set_tip (tooltips, rs274x,
-		_("Export active layer to a RS-274X (Gerber) file"), NULL);
-
-	rs274xm = gtk_menu_item_new_with_mnemonic (_("RS-274X merge (Gerber)..."));
-	gtk_container_add (GTK_CONTAINER (menuitem_file_export_menu), rs274xm);
-	gtk_tooltips_set_tip (tooltips, rs274xm,
-			_("Export merged visible Gerber layers to "
-				"a RS-274X (Gerber) file"), NULL);
-
-	gtk_container_add (GTK_CONTAINER (menuitem_file_export_menu),
-			gtk_separator_menu_item_new ());
-	
-	drill = gtk_menu_item_new_with_mnemonic (_("_Excellon drill..."));
-	gtk_container_add (GTK_CONTAINER (menuitem_file_export_menu), drill);
-	gtk_tooltips_set_tip (tooltips, drill,
-		_("Export active layer to an Excellon drill file"), NULL);
-
-	drillm = gtk_menu_item_new_with_mnemonic (_("Excellon drill merge..."));
-	gtk_container_add (GTK_CONTAINER (menuitem_file_export_menu), drillm);
-	gtk_tooltips_set_tip (tooltips, drillm,
-			_("Export merged visible drill layers to "
-				"an Excellon drill file"), NULL);	
-
-	idrill = gtk_menu_item_new_with_mnemonic (_("_ISEL NCP drill..."));
-	gtk_container_add (GTK_CONTAINER (menuitem_file_export_menu), idrill);
-	gtk_tooltips_set_tip (tooltips, idrill,
-		_("Export active layer to an ISEL Automation NCP drill file"),
-		NULL);
-
-	gtk_container_add (GTK_CONTAINER (menuitem_file_export_menu),
-			gtk_separator_menu_item_new ());
-
-	geda_pcb = gtk_menu_item_new_with_mnemonic (_("gEDA P_CB (beta)..."));
-	gtk_container_add (GTK_CONTAINER (menuitem_file_export_menu), geda_pcb);
-	gtk_tooltips_set_tip (tooltips, geda_pcb,
-			_("Export active layer to a gEDA PCB file"), NULL);
-
-	/* File menu items dealing with a gerbv project. */
-
-	gtk_container_add (GTK_CONTAINER (menuitem_file_menu),
-			gtk_separator_menu_item_new ());
-
-	new_project = gtk_image_menu_item_new_with_mnemonic (_("_New project"));
-	gtk_container_add (GTK_CONTAINER (menuitem_file_menu), new_project);
-	gtk_tooltips_set_tip (tooltips, new_project, _("Close all layers and start a new project"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_NEW, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (new_project), tempImage);
-
-	save = gtk_image_menu_item_new_with_mnemonic (_("Save project"));
-	screen.win.curFileMenuItem[4] = save;
-	gtk_tooltips_set_tip (tooltips, save, _("Save the current project"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_SAVE, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (save), tempImage);
-	gtk_container_add (GTK_CONTAINER (menuitem_file_menu), save);
-
-	save_as = gtk_image_menu_item_new_with_mnemonic (_("Save project as..."));
-	screen.win.curFileMenuItem[5] = save_as;
-	gtk_tooltips_set_tip (tooltips, save_as, _("Save the current project to a new file"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_SAVE_AS, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (save_as), tempImage);
-	gtk_container_add (GTK_CONTAINER (menuitem_file_menu), save_as);
-	
-	/* File menu items dealing with printing and quitting. */
-
-	gtk_container_add (GTK_CONTAINER (menuitem_file_menu),
-			gtk_separator_menu_item_new ());
-
-#if GTK_CHECK_VERSION(2,10,0)
-	if (gtk_stock_lookup(GTK_STOCK_PRINT, &stock)) {
-	    gchar new[] = N_("_Print..."); 
-	    stock.label = _(new);
-	    gtk_stock_add(&stock, 1);
-	}
+    gtk_container_add(GTK_CONTAINER(menuitem_file_export_menu), gtk_separator_menu_item_new());
+
+    rs274x = gtk_menu_item_new_with_mnemonic(_("RS-274X (_Gerber)..."));
+    gtk_container_add(GTK_CONTAINER(menuitem_file_export_menu), rs274x);
+    gtk_tooltips_set_tip(tooltips, rs274x, _("Export active layer to a RS-274X (Gerber) file"), NULL);
+
+    rs274xm = gtk_menu_item_new_with_mnemonic(_("RS-274X merge (Gerber)..."));
+    gtk_container_add(GTK_CONTAINER(menuitem_file_export_menu), rs274xm);
+    gtk_tooltips_set_tip(
+        tooltips, rs274xm,
+        _("Export merged visible Gerber layers to "
+          "a RS-274X (Gerber) file"),
+        NULL
+    );
+
+    gtk_container_add(GTK_CONTAINER(menuitem_file_export_menu), gtk_separator_menu_item_new());
+
+    drill = gtk_menu_item_new_with_mnemonic(_("_Excellon drill..."));
+    gtk_container_add(GTK_CONTAINER(menuitem_file_export_menu), drill);
+    gtk_tooltips_set_tip(tooltips, drill, _("Export active layer to an Excellon drill file"), NULL);
+
+    drillm = gtk_menu_item_new_with_mnemonic(_("Excellon drill merge..."));
+    gtk_container_add(GTK_CONTAINER(menuitem_file_export_menu), drillm);
+    gtk_tooltips_set_tip(
+        tooltips, drillm,
+        _("Export merged visible drill layers to "
+          "an Excellon drill file"),
+        NULL
+    );
+
+    idrill = gtk_menu_item_new_with_mnemonic(_("_ISEL NCP drill..."));
+    gtk_container_add(GTK_CONTAINER(menuitem_file_export_menu), idrill);
+    gtk_tooltips_set_tip(tooltips, idrill, _("Export active layer to an ISEL Automation NCP drill file"), NULL);
+
+    gtk_container_add(GTK_CONTAINER(menuitem_file_export_menu), gtk_separator_menu_item_new());
+
+    geda_pcb = gtk_menu_item_new_with_mnemonic(_("gEDA P_CB (beta)..."));
+    gtk_container_add(GTK_CONTAINER(menuitem_file_export_menu), geda_pcb);
+    gtk_tooltips_set_tip(tooltips, geda_pcb, _("Export active layer to a gEDA PCB file"), NULL);
+
+    /* File menu items dealing with a gerbv project. */
+
+    gtk_container_add(GTK_CONTAINER(menuitem_file_menu), gtk_separator_menu_item_new());
+
+    new_project = gtk_image_menu_item_new_with_mnemonic(_("_New project"));
+    gtk_container_add(GTK_CONTAINER(menuitem_file_menu), new_project);
+    gtk_tooltips_set_tip(tooltips, new_project, _("Close all layers and start a new project"), NULL);
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_NEW, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(new_project), tempImage);
+
+    save                          = gtk_image_menu_item_new_with_mnemonic(_("Save project"));
+    screen.win.curFileMenuItem[4] = save;
+    gtk_tooltips_set_tip(tooltips, save, _("Save the current project"), NULL);
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_SAVE, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(save), tempImage);
+    gtk_container_add(GTK_CONTAINER(menuitem_file_menu), save);
+
+    save_as                       = gtk_image_menu_item_new_with_mnemonic(_("Save project as..."));
+    screen.win.curFileMenuItem[5] = save_as;
+    gtk_tooltips_set_tip(tooltips, save_as, _("Save the current project to a new file"), NULL);
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_SAVE_AS, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(save_as), tempImage);
+    gtk_container_add(GTK_CONTAINER(menuitem_file_menu), save_as);
+
+    /* File menu items dealing with printing and quitting. */
+
+    gtk_container_add(GTK_CONTAINER(menuitem_file_menu), gtk_separator_menu_item_new());
+
+#if GTK_CHECK_VERSION(2, 10, 0)
+    if (gtk_stock_lookup(GTK_STOCK_PRINT, &stock)) {
+        gchar new[] = N_("_Print...");
+        stock.label = _(new);
+        gtk_stock_add(&stock, 1);
+    }
 
-	print = gtk_image_menu_item_new_from_stock (GTK_STOCK_PRINT, NULL);
-	screen.win.curFileMenuItem[6] = print;
-	SET_ACCELS_FROM_STOCK (print, GTK_STOCK_PRINT, ACCEL_FILE_PRINT);
-	gtk_tooltips_set_tip (tooltips, print, _("Print the visible layers"), NULL);
-	gtk_container_add (GTK_CONTAINER (menuitem_file_menu), print);
-	gtk_container_add (GTK_CONTAINER (menuitem_file_menu),
-			gtk_separator_menu_item_new ());
+    print                         = gtk_image_menu_item_new_from_stock(GTK_STOCK_PRINT, NULL);
+    screen.win.curFileMenuItem[6] = print;
+    SET_ACCELS_FROM_STOCK(print, GTK_STOCK_PRINT, ACCEL_FILE_PRINT);
+    gtk_tooltips_set_tip(tooltips, print, _("Print the visible layers"), NULL);
+    gtk_container_add(GTK_CONTAINER(menuitem_file_menu), print);
+    gtk_container_add(GTK_CONTAINER(menuitem_file_menu), gtk_separator_menu_item_new());
 #endif
 
-	quit = gtk_image_menu_item_new_from_stock (GTK_STOCK_QUIT, NULL);
-	SET_ACCELS_FROM_STOCK (quit, GTK_STOCK_QUIT, ACCEL_FILE_QUIT);
-	gtk_tooltips_set_tip (tooltips, quit, _("Quit Gerbv"), NULL);
-	gtk_container_add (GTK_CONTAINER (menuitem_file_menu), quit);
-
-	/* --- Next menu item (Edit) --- */
-	menuitem_edit = gtk_menu_item_new_with_mnemonic (_("_Edit"));
-	screen.win.curEditMenuItem = menuitem_edit;
-	gtk_container_add (GTK_CONTAINER (menubar1), menuitem_edit);
-
-	menuitem_edit_menu = gtk_menu_new ();
-	gtk_menu_set_accel_group (GTK_MENU(menuitem_edit_menu), accel_group);
-	gtk_menu_set_accel_path (GTK_MENU(menuitem_edit_menu), ACCEL_EDIT);
-	gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem_edit), menuitem_edit_menu);
-
-	properties_selected = gtk_image_menu_item_new_with_mnemonic (_("Display _properties of selected object(s)"));
-	SET_ACCELS_FROM_STOCK (properties_selected, GTK_STOCK_PROPERTIES, ACCEL_EDIT_PROPERTIES);
-	gtk_tooltips_set_tip (tooltips, properties_selected, _("Examine the properties of the selected object"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_PROPERTIES, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (properties_selected), tempImage);
-	gtk_container_add (GTK_CONTAINER (menuitem_edit_menu), properties_selected);
-
-	delete_selected = gtk_image_menu_item_new_with_mnemonic (_("_Delete selected object(s)"));
-	SET_ACCELS_FROM_STOCK (delete_selected, GTK_STOCK_REMOVE, ACCEL_EDIT_DELETE);
-	gtk_tooltips_set_tip (tooltips, delete_selected, _("Delete selected objects"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_DELETE, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (delete_selected), tempImage);
-	gtk_container_add (GTK_CONTAINER (menuitem_edit_menu), delete_selected);
-
-	align = gtk_menu_item_new_with_mnemonic (_("_Align layers"));
-	screen.win.curEditAlingMenuItem = align;
-	gtk_tooltips_set_tip (tooltips, align,
-			_("Align two layers by two selected objects"), NULL);
-	gtk_widget_set_sensitive (align, FALSE);
-	gtk_container_add (GTK_CONTAINER (menuitem_edit_menu), align);
-
-	align_layers = gtk_menu_new ();
-	screen.win.curEditAlingItem[0] = gtk_menu_item_new_with_mnemonic ("");
-	screen.win.curEditAlingItem[1] = gtk_menu_item_new_with_mnemonic ("");
-	gtk_menu_item_set_submenu (GTK_MENU_ITEM (align), align_layers);
-	gtk_container_add (GTK_CONTAINER (align_layers),
-			screen.win.curEditAlingItem[0]);
-	gtk_container_add (GTK_CONTAINER (align_layers),
-			screen.win.curEditAlingItem[1]);
+    quit = gtk_image_menu_item_new_from_stock(GTK_STOCK_QUIT, NULL);
+    SET_ACCELS_FROM_STOCK(quit, GTK_STOCK_QUIT, ACCEL_FILE_QUIT);
+    gtk_tooltips_set_tip(tooltips, quit, _("Quit Gerbv"), NULL);
+    gtk_container_add(GTK_CONTAINER(menuitem_file_menu), quit);
+
+    /* --- Next menu item (Edit) --- */
+    menuitem_edit              = gtk_menu_item_new_with_mnemonic(_("_Edit"));
+    screen.win.curEditMenuItem = menuitem_edit;
+    gtk_container_add(GTK_CONTAINER(menubar1), menuitem_edit);
+
+    menuitem_edit_menu = gtk_menu_new();
+    gtk_menu_set_accel_group(GTK_MENU(menuitem_edit_menu), accel_group);
+    gtk_menu_set_accel_path(GTK_MENU(menuitem_edit_menu), ACCEL_EDIT);
+    gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem_edit), menuitem_edit_menu);
+
+    properties_selected = gtk_image_menu_item_new_with_mnemonic(_("Display _properties of selected object(s)"));
+    SET_ACCELS_FROM_STOCK(properties_selected, GTK_STOCK_PROPERTIES, ACCEL_EDIT_PROPERTIES);
+    gtk_tooltips_set_tip(tooltips, properties_selected, _("Examine the properties of the selected object"), NULL);
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_PROPERTIES, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(properties_selected), tempImage);
+    gtk_container_add(GTK_CONTAINER(menuitem_edit_menu), properties_selected);
+
+    delete_selected = gtk_image_menu_item_new_with_mnemonic(_("_Delete selected object(s)"));
+    SET_ACCELS_FROM_STOCK(delete_selected, GTK_STOCK_REMOVE, ACCEL_EDIT_DELETE);
+    gtk_tooltips_set_tip(tooltips, delete_selected, _("Delete selected objects"), NULL);
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_DELETE, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(delete_selected), tempImage);
+    gtk_container_add(GTK_CONTAINER(menuitem_edit_menu), delete_selected);
+
+    align                           = gtk_menu_item_new_with_mnemonic(_("_Align layers"));
+    screen.win.curEditAlingMenuItem = align;
+    gtk_tooltips_set_tip(tooltips, align, _("Align two layers by two selected objects"), NULL);
+    gtk_widget_set_sensitive(align, FALSE);
+    gtk_container_add(GTK_CONTAINER(menuitem_edit_menu), align);
+
+    align_layers                   = gtk_menu_new();
+    screen.win.curEditAlingItem[0] = gtk_menu_item_new_with_mnemonic("");
+    screen.win.curEditAlingItem[1] = gtk_menu_item_new_with_mnemonic("");
+    gtk_menu_item_set_submenu(GTK_MENU_ITEM(align), align_layers);
+    gtk_container_add(GTK_CONTAINER(align_layers), screen.win.curEditAlingItem[0]);
+    gtk_container_add(GTK_CONTAINER(align_layers), screen.win.curEditAlingItem[1]);
 
 #if 0
 	/* Include these after they are coded. */
@@ -605,1958 +584,1828 @@ interface_create_gui (int req_width, int req_height)
 	                  G_CALLBACK (callbacks_reduce_object_area_clicked), NULL);
 #endif
 
-	/* Use the "Edit" menu as right click popup menu for the drawing area */
-	screen.win.drawWindowPopupMenu = menuitem_edit_menu;
-
-	/* --- Next menu item (View) --- */
-	menuitem_view = gtk_menu_item_new_with_mnemonic (_("_View"));
-	gtk_container_add (GTK_CONTAINER (menubar1), menuitem_view);
-
-	menuitem_view_menu = gtk_menu_new ();
-	gtk_menu_set_accel_group (GTK_MENU(menuitem_view_menu), accel_group);
-	gtk_menu_set_accel_path (GTK_MENU(menuitem_view_menu), ACCEL_VIEW);
-	gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem_view), menuitem_view_menu);
-	
-	view_fullscreen = gtk_check_menu_item_new_with_mnemonic (_("Fullscr_een"));
-	gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (view_fullscreen), FALSE);
-	gtk_tooltips_set_tip (tooltips, view_fullscreen, _("Toggle between fullscreen and normal view"), NULL);
-	SET_ACCELS (view_fullscreen, ACCEL_VIEW_FULLSCREEN);
-	gtk_container_add (GTK_CONTAINER (menuitem_view_menu), view_fullscreen);
-
-	show_toolbar = gtk_check_menu_item_new_with_mnemonic (_("Show _Toolbar"));
-	gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (show_toolbar), TRUE);
-	gtk_tooltips_set_tip (tooltips, show_toolbar, _("Toggle visibility of the toolbar"), NULL);
-	SET_ACCELS (show_toolbar, ACCEL_VIEW_TOOLBAR);
-	gtk_container_add (GTK_CONTAINER (menuitem_view_menu), show_toolbar);
-
-	show_sidepane = gtk_check_menu_item_new_with_mnemonic (_("Show _Sidepane"));
-	gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (show_sidepane), TRUE);
-	gtk_tooltips_set_tip (tooltips, show_sidepane, _("Toggle visibility of the sidepane"), NULL);
-	SET_ACCELS (show_sidepane, ACCEL_VIEW_SIDEPANE);
-	gtk_container_add (GTK_CONTAINER (menuitem_view_menu), show_sidepane);
-
-	gtk_container_add (GTK_CONTAINER (menuitem_view_menu),
-			gtk_separator_menu_item_new ());
-	
-	layer_visibility_main_menu = gtk_menu_item_new_with_mnemonic (_("Toggle layer _visibility"));
-	gtk_container_add (GTK_CONTAINER (menuitem_view_menu), layer_visibility_main_menu);
-
-	show_selection_on_invisible = gtk_check_menu_item_new_with_mnemonic (_("Show all se_lection"));
-	gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (show_selection_on_invisible), FALSE);
-	gtk_tooltips_set_tip (tooltips, show_selection_on_invisible, _("Show selected objects on invisible layers"), NULL);
-	SET_ACCELS (show_selection_on_invisible, ACCEL_VIEW_ALL_SELECTION);
-	gtk_container_add (GTK_CONTAINER (menuitem_view_menu), show_selection_on_invisible);
-
-	show_cross_on_drill_holes = gtk_check_menu_item_new_with_mnemonic (_("Show _cross on drill holes"));
-	gtk_tooltips_set_tip (tooltips, show_cross_on_drill_holes,
-			_("Show cross on drill holes"), NULL);
-	SET_ACCELS (show_cross_on_drill_holes, ACCEL_VIEW_CROSS_ON_DRILL_HOLES);
-	gtk_container_add (GTK_CONTAINER (menuitem_view_menu), show_cross_on_drill_holes);
-	if (screen.settings) {
-		g_settings_bind (screen.settings, "cross-on-drill-holes",
-				show_cross_on_drill_holes, "active",
-				G_SETTINGS_BIND_DEFAULT);
-		screenRenderInfo.show_cross_on_drill_holes =
-			gtk_check_menu_item_get_active (GTK_CHECK_MENU_ITEM (
-						show_cross_on_drill_holes));
-	}
+    /* Use the "Edit" menu as right click popup menu for the drawing area */
+    screen.win.drawWindowPopupMenu = menuitem_edit_menu;
+
+    /* --- Next menu item (View) --- */
+    menuitem_view = gtk_menu_item_new_with_mnemonic(_("_View"));
+    gtk_container_add(GTK_CONTAINER(menubar1), menuitem_view);
+
+    menuitem_view_menu = gtk_menu_new();
+    gtk_menu_set_accel_group(GTK_MENU(menuitem_view_menu), accel_group);
+    gtk_menu_set_accel_path(GTK_MENU(menuitem_view_menu), ACCEL_VIEW);
+    gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem_view), menuitem_view_menu);
+
+    view_fullscreen = gtk_check_menu_item_new_with_mnemonic(_("Fullscr_een"));
+    gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(view_fullscreen), FALSE);
+    gtk_tooltips_set_tip(tooltips, view_fullscreen, _("Toggle between fullscreen and normal view"), NULL);
+    SET_ACCELS(view_fullscreen, ACCEL_VIEW_FULLSCREEN);
+    gtk_container_add(GTK_CONTAINER(menuitem_view_menu), view_fullscreen);
+
+    show_toolbar = gtk_check_menu_item_new_with_mnemonic(_("Show _Toolbar"));
+    gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(show_toolbar), TRUE);
+    gtk_tooltips_set_tip(tooltips, show_toolbar, _("Toggle visibility of the toolbar"), NULL);
+    SET_ACCELS(show_toolbar, ACCEL_VIEW_TOOLBAR);
+    gtk_container_add(GTK_CONTAINER(menuitem_view_menu), show_toolbar);
+
+    show_sidepane = gtk_check_menu_item_new_with_mnemonic(_("Show _Sidepane"));
+    gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(show_sidepane), TRUE);
+    gtk_tooltips_set_tip(tooltips, show_sidepane, _("Toggle visibility of the sidepane"), NULL);
+    SET_ACCELS(show_sidepane, ACCEL_VIEW_SIDEPANE);
+    gtk_container_add(GTK_CONTAINER(menuitem_view_menu), show_sidepane);
+
+    gtk_container_add(GTK_CONTAINER(menuitem_view_menu), gtk_separator_menu_item_new());
+
+    layer_visibility_main_menu = gtk_menu_item_new_with_mnemonic(_("Toggle layer _visibility"));
+    gtk_container_add(GTK_CONTAINER(menuitem_view_menu), layer_visibility_main_menu);
+
+    show_selection_on_invisible = gtk_check_menu_item_new_with_mnemonic(_("Show all se_lection"));
+    gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(show_selection_on_invisible), FALSE);
+    gtk_tooltips_set_tip(tooltips, show_selection_on_invisible, _("Show selected objects on invisible layers"), NULL);
+    SET_ACCELS(show_selection_on_invisible, ACCEL_VIEW_ALL_SELECTION);
+    gtk_container_add(GTK_CONTAINER(menuitem_view_menu), show_selection_on_invisible);
+
+    show_cross_on_drill_holes = gtk_check_menu_item_new_with_mnemonic(_("Show _cross on drill holes"));
+    gtk_tooltips_set_tip(tooltips, show_cross_on_drill_holes, _("Show cross on drill holes"), NULL);
+    SET_ACCELS(show_cross_on_drill_holes, ACCEL_VIEW_CROSS_ON_DRILL_HOLES);
+    gtk_container_add(GTK_CONTAINER(menuitem_view_menu), show_cross_on_drill_holes);
+    if (screen.settings) {
+        g_settings_bind(
+            screen.settings, "cross-on-drill-holes", show_cross_on_drill_holes, "active", G_SETTINGS_BIND_DEFAULT
+        );
+        screenRenderInfo.show_cross_on_drill_holes =
+            gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(show_cross_on_drill_holes));
+    }
 
-	layer_visibility_menu = gtk_menu_new ();
-	gtk_menu_set_accel_group (GTK_MENU(layer_visibility_menu), accel_group);
-	gtk_menu_set_accel_path (GTK_MENU(layer_visibility_menu), ACCEL_VIEW_VIS);
-	gtk_menu_item_set_submenu (GTK_MENU_ITEM (layer_visibility_main_menu), layer_visibility_menu);
-	
-	toggle_layer_visibility_item1 = gtk_menu_item_new_with_label (_("Toggle visibility of layer 1"));
-	SET_ACCELS (toggle_layer_visibility_item1, ACCEL_VIEW_VIS_LAYER1);
-	gtk_container_add (GTK_CONTAINER (layer_visibility_menu), toggle_layer_visibility_item1);
-
-	toggle_layer_visibility_item2 = gtk_menu_item_new_with_label (_("Toggle visibility of layer 2"));
-	SET_ACCELS (toggle_layer_visibility_item2, ACCEL_VIEW_VIS_LAYER2);
-	gtk_container_add (GTK_CONTAINER (layer_visibility_menu), toggle_layer_visibility_item2);
-
-	toggle_layer_visibility_item3 = gtk_menu_item_new_with_label (_("Toggle visibility of layer 3"));
-	SET_ACCELS (toggle_layer_visibility_item3, ACCEL_VIEW_VIS_LAYER3);
-	gtk_container_add (GTK_CONTAINER (layer_visibility_menu), toggle_layer_visibility_item3);
-
-	toggle_layer_visibility_item4 = gtk_menu_item_new_with_label (_("Toggle visibility of layer 4"));
-	SET_ACCELS (toggle_layer_visibility_item4, ACCEL_VIEW_VIS_LAYER4);
-	gtk_container_add (GTK_CONTAINER (layer_visibility_menu), toggle_layer_visibility_item4);
-
-	toggle_layer_visibility_item5 = gtk_menu_item_new_with_label (_("Toggle visibility of layer 5"));
-	SET_ACCELS (toggle_layer_visibility_item5, ACCEL_VIEW_VIS_LAYER5);
-	gtk_container_add (GTK_CONTAINER (layer_visibility_menu), toggle_layer_visibility_item5);
-
-	toggle_layer_visibility_item6 = gtk_menu_item_new_with_label (_("Toggle visibility of layer 6"));
-	SET_ACCELS (toggle_layer_visibility_item6, ACCEL_VIEW_VIS_LAYER6);
-	gtk_container_add (GTK_CONTAINER (layer_visibility_menu), toggle_layer_visibility_item6);
-
-	toggle_layer_visibility_item7 = gtk_menu_item_new_with_label (_("Toggle visibility of layer 7"));
-	SET_ACCELS (toggle_layer_visibility_item7, ACCEL_VIEW_VIS_LAYER7);
-	gtk_container_add (GTK_CONTAINER (layer_visibility_menu), toggle_layer_visibility_item7);
-
-	toggle_layer_visibility_item8 = gtk_menu_item_new_with_label (_("Toggle visibility of layer 8"));
-	SET_ACCELS (toggle_layer_visibility_item8, ACCEL_VIEW_VIS_LAYER8);
-	gtk_container_add (GTK_CONTAINER (layer_visibility_menu), toggle_layer_visibility_item8);
-
-	toggle_layer_visibility_item9 = gtk_menu_item_new_with_label (_("Toggle visibility of layer 9"));
-	SET_ACCELS (toggle_layer_visibility_item9, ACCEL_VIEW_VIS_LAYER9);
-	gtk_container_add (GTK_CONTAINER (layer_visibility_menu), toggle_layer_visibility_item9);
-
-	toggle_layer_visibility_item10 = gtk_menu_item_new_with_label (_("Toggle visibility of layer 10"));
-	SET_ACCELS (toggle_layer_visibility_item10, ACCEL_VIEW_VIS_LAYER10);
-	gtk_container_add (GTK_CONTAINER (layer_visibility_menu), toggle_layer_visibility_item10);
-
-	gtk_container_add (GTK_CONTAINER (menuitem_view_menu),
-			gtk_separator_menu_item_new ());
-
-	zoom_in = gtk_image_menu_item_new_from_stock (GTK_STOCK_ZOOM_IN, NULL);
-	SET_ACCELS_FROM_STOCK (zoom_in, GTK_STOCK_ZOOM_IN, ACCEL_VIEW_ZOOM_IN);
-	gtk_tooltips_set_tip (tooltips, zoom_in, _("Zoom in"), NULL);
-	gtk_container_add (GTK_CONTAINER (menuitem_view_menu), zoom_in);
-	                        
-	zoom_out = gtk_image_menu_item_new_from_stock (GTK_STOCK_ZOOM_OUT, NULL);
-	SET_ACCELS_FROM_STOCK (zoom_out, GTK_STOCK_ZOOM_OUT, ACCEL_VIEW_ZOOM_OUT);
-	gtk_tooltips_set_tip (tooltips, zoom_out, _("Zoom out"), NULL);
-	gtk_container_add (GTK_CONTAINER (menuitem_view_menu), zoom_out);
-	                        
-	fit_to_window = gtk_image_menu_item_new_from_stock (GTK_STOCK_ZOOM_FIT, NULL);
-	gtk_tooltips_set_tip (tooltips, fit_to_window, _("Zoom to fit all visible layers in the window"), NULL);
-	SET_ACCELS_FROM_STOCK (fit_to_window, GTK_STOCK_ZOOM_FIT, ACCEL_VIEW_ZOOM_FIT);
-	gtk_container_add (GTK_CONTAINER (menuitem_view_menu), fit_to_window);
-	                        
-	gtk_container_add (GTK_CONTAINER (menuitem_view_menu),
-			gtk_separator_menu_item_new ());
-	
-	backgroundColor = gtk_image_menu_item_new_with_mnemonic (_("Background color"));
-	gtk_tooltips_set_tip (tooltips, backgroundColor, _("Change the background color"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_SELECT_COLOR, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (backgroundColor), tempImage);
-	gtk_container_add (GTK_CONTAINER (menuitem_view_menu), backgroundColor);
-
-	/* Restore saved background color */
-	if (screen.settings
-	&& !screen.background_is_from_cmdline
-	&& !screen.background_is_from_project) {
-		guint clr;
-
-		clr = g_settings_get_uint (screen.settings, "background-color");
-		mainProject->background.blue = (clr & 0xff)*257;
-		clr >>= 8;
-		mainProject->background.green = (clr & 0xff)*257;
-		clr >>= 8;
-		mainProject->background.red = (clr & 0xff)*257;
-	}
+    layer_visibility_menu = gtk_menu_new();
+    gtk_menu_set_accel_group(GTK_MENU(layer_visibility_menu), accel_group);
+    gtk_menu_set_accel_path(GTK_MENU(layer_visibility_menu), ACCEL_VIEW_VIS);
+    gtk_menu_item_set_submenu(GTK_MENU_ITEM(layer_visibility_main_menu), layer_visibility_menu);
+
+    toggle_layer_visibility_item1 = gtk_menu_item_new_with_label(_("Toggle visibility of layer 1"));
+    SET_ACCELS(toggle_layer_visibility_item1, ACCEL_VIEW_VIS_LAYER1);
+    gtk_container_add(GTK_CONTAINER(layer_visibility_menu), toggle_layer_visibility_item1);
+
+    toggle_layer_visibility_item2 = gtk_menu_item_new_with_label(_("Toggle visibility of layer 2"));
+    SET_ACCELS(toggle_layer_visibility_item2, ACCEL_VIEW_VIS_LAYER2);
+    gtk_container_add(GTK_CONTAINER(layer_visibility_menu), toggle_layer_visibility_item2);
+
+    toggle_layer_visibility_item3 = gtk_menu_item_new_with_label(_("Toggle visibility of layer 3"));
+    SET_ACCELS(toggle_layer_visibility_item3, ACCEL_VIEW_VIS_LAYER3);
+    gtk_container_add(GTK_CONTAINER(layer_visibility_menu), toggle_layer_visibility_item3);
+
+    toggle_layer_visibility_item4 = gtk_menu_item_new_with_label(_("Toggle visibility of layer 4"));
+    SET_ACCELS(toggle_layer_visibility_item4, ACCEL_VIEW_VIS_LAYER4);
+    gtk_container_add(GTK_CONTAINER(layer_visibility_menu), toggle_layer_visibility_item4);
+
+    toggle_layer_visibility_item5 = gtk_menu_item_new_with_label(_("Toggle visibility of layer 5"));
+    SET_ACCELS(toggle_layer_visibility_item5, ACCEL_VIEW_VIS_LAYER5);
+    gtk_container_add(GTK_CONTAINER(layer_visibility_menu), toggle_layer_visibility_item5);
+
+    toggle_layer_visibility_item6 = gtk_menu_item_new_with_label(_("Toggle visibility of layer 6"));
+    SET_ACCELS(toggle_layer_visibility_item6, ACCEL_VIEW_VIS_LAYER6);
+    gtk_container_add(GTK_CONTAINER(layer_visibility_menu), toggle_layer_visibility_item6);
+
+    toggle_layer_visibility_item7 = gtk_menu_item_new_with_label(_("Toggle visibility of layer 7"));
+    SET_ACCELS(toggle_layer_visibility_item7, ACCEL_VIEW_VIS_LAYER7);
+    gtk_container_add(GTK_CONTAINER(layer_visibility_menu), toggle_layer_visibility_item7);
+
+    toggle_layer_visibility_item8 = gtk_menu_item_new_with_label(_("Toggle visibility of layer 8"));
+    SET_ACCELS(toggle_layer_visibility_item8, ACCEL_VIEW_VIS_LAYER8);
+    gtk_container_add(GTK_CONTAINER(layer_visibility_menu), toggle_layer_visibility_item8);
+
+    toggle_layer_visibility_item9 = gtk_menu_item_new_with_label(_("Toggle visibility of layer 9"));
+    SET_ACCELS(toggle_layer_visibility_item9, ACCEL_VIEW_VIS_LAYER9);
+    gtk_container_add(GTK_CONTAINER(layer_visibility_menu), toggle_layer_visibility_item9);
+
+    toggle_layer_visibility_item10 = gtk_menu_item_new_with_label(_("Toggle visibility of layer 10"));
+    SET_ACCELS(toggle_layer_visibility_item10, ACCEL_VIEW_VIS_LAYER10);
+    gtk_container_add(GTK_CONTAINER(layer_visibility_menu), toggle_layer_visibility_item10);
+
+    gtk_container_add(GTK_CONTAINER(menuitem_view_menu), gtk_separator_menu_item_new());
+
+    zoom_in = gtk_image_menu_item_new_from_stock(GTK_STOCK_ZOOM_IN, NULL);
+    SET_ACCELS_FROM_STOCK(zoom_in, GTK_STOCK_ZOOM_IN, ACCEL_VIEW_ZOOM_IN);
+    gtk_tooltips_set_tip(tooltips, zoom_in, _("Zoom in"), NULL);
+    gtk_container_add(GTK_CONTAINER(menuitem_view_menu), zoom_in);
+
+    zoom_out = gtk_image_menu_item_new_from_stock(GTK_STOCK_ZOOM_OUT, NULL);
+    SET_ACCELS_FROM_STOCK(zoom_out, GTK_STOCK_ZOOM_OUT, ACCEL_VIEW_ZOOM_OUT);
+    gtk_tooltips_set_tip(tooltips, zoom_out, _("Zoom out"), NULL);
+    gtk_container_add(GTK_CONTAINER(menuitem_view_menu), zoom_out);
+
+    fit_to_window = gtk_image_menu_item_new_from_stock(GTK_STOCK_ZOOM_FIT, NULL);
+    gtk_tooltips_set_tip(tooltips, fit_to_window, _("Zoom to fit all visible layers in the window"), NULL);
+    SET_ACCELS_FROM_STOCK(fit_to_window, GTK_STOCK_ZOOM_FIT, ACCEL_VIEW_ZOOM_FIT);
+    gtk_container_add(GTK_CONTAINER(menuitem_view_menu), fit_to_window);
+
+    gtk_container_add(GTK_CONTAINER(menuitem_view_menu), gtk_separator_menu_item_new());
+
+    backgroundColor = gtk_image_menu_item_new_with_mnemonic(_("Background color"));
+    gtk_tooltips_set_tip(tooltips, backgroundColor, _("Change the background color"), NULL);
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_SELECT_COLOR, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(backgroundColor), tempImage);
+    gtk_container_add(GTK_CONTAINER(menuitem_view_menu), backgroundColor);
+
+    /* Restore saved background color */
+    if (screen.settings && !screen.background_is_from_cmdline && !screen.background_is_from_project) {
+        guint clr;
+
+        clr                          = g_settings_get_uint(screen.settings, "background-color");
+        mainProject->background.blue = (clr & 0xff) * 257;
+        clr >>= 8;
+        mainProject->background.green = (clr & 0xff) * 257;
+        clr >>= 8;
+        mainProject->background.red = (clr & 0xff) * 257;
+    }
 
-	{	// rendering submenu
-		menuitem_view_render = gtk_menu_item_new_with_mnemonic (_("_Rendering"));
-		gtk_container_add (GTK_CONTAINER (menuitem_view_menu), menuitem_view_render);
-		
-		menuitem_view_render_menu = gtk_menu_new ();
-		gtk_menu_set_accel_group (GTK_MENU(menuitem_view_render_menu), accel_group);
-		gtk_menu_set_accel_path (GTK_MENU(menuitem_view_render_menu), ACCEL_VIEW_RENDER);
-		gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem_view_render), menuitem_view_render_menu);
-
-		menu_view_render_group = NULL;
-
-		render_fast = gtk_radio_menu_item_new_with_mnemonic (menu_view_render_group, _("_Fast"));
-		menu_view_render_group = gtk_radio_menu_item_get_group (GTK_RADIO_MENU_ITEM (render_fast));
-		gtk_container_add (GTK_CONTAINER (menuitem_view_render_menu), render_fast);
-
-		render_fast_xor = gtk_radio_menu_item_new_with_mnemonic (menu_view_render_group, _("Fast (_XOR)"));
-		menu_view_render_group = gtk_radio_menu_item_get_group (GTK_RADIO_MENU_ITEM (render_fast_xor));
-		gtk_container_add (GTK_CONTAINER (menuitem_view_render_menu), render_fast_xor);
-
-		render_normal = gtk_radio_menu_item_new_with_mnemonic (menu_view_render_group, _("_Normal"));
-		menu_view_render_group = gtk_radio_menu_item_get_group (GTK_RADIO_MENU_ITEM (render_normal));
-		gtk_container_add (GTK_CONTAINER (menuitem_view_render_menu), render_normal);
-
-		render_hq = gtk_radio_menu_item_new_with_mnemonic (menu_view_render_group, _("High _Quality"));
-		menu_view_render_group = gtk_radio_menu_item_get_group (GTK_RADIO_MENU_ITEM (render_hq));
-		gtk_container_add (GTK_CONTAINER (menuitem_view_render_menu), render_hq);
-
-		screen.win.menu_view_render_group = malloc(4*sizeof(GtkWidget *));
-		if(screen.win.menu_view_render_group == NULL)
-			GERB_FATAL_ERROR("malloc for rendering type synchronization failed in %s()", __FUNCTION__);
-
-		screen.win.menu_view_render_group[GERBV_RENDER_TYPE_GDK] = GTK_CHECK_MENU_ITEM(render_fast);
-		screen.win.menu_view_render_group[GERBV_RENDER_TYPE_GDK_XOR] = GTK_CHECK_MENU_ITEM(render_fast_xor);
-		screen.win.menu_view_render_group[GERBV_RENDER_TYPE_CAIRO_NORMAL] = GTK_CHECK_MENU_ITEM(render_normal);
-		screen.win.menu_view_render_group[GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY] = GTK_CHECK_MENU_ITEM(render_hq);
-	}
+    {  // rendering submenu
+        menuitem_view_render = gtk_menu_item_new_with_mnemonic(_("_Rendering"));
+        gtk_container_add(GTK_CONTAINER(menuitem_view_menu), menuitem_view_render);
 
-	{	// units submenu
-		gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (render_fast), TRUE);
+        menuitem_view_render_menu = gtk_menu_new();
+        gtk_menu_set_accel_group(GTK_MENU(menuitem_view_render_menu), accel_group);
+        gtk_menu_set_accel_path(GTK_MENU(menuitem_view_render_menu), ACCEL_VIEW_RENDER);
+        gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem_view_render), menuitem_view_render_menu);
 
-		menuitem_view_unit = gtk_menu_item_new_with_mnemonic (_("U_nits"));
-		gtk_container_add (GTK_CONTAINER (menuitem_view_menu), menuitem_view_unit);
+        menu_view_render_group = NULL;
 
-		menuitem_view_unit_menu = gtk_menu_new ();
-		gtk_menu_set_accel_group (GTK_MENU(menuitem_view_unit_menu), accel_group);
-		gtk_menu_set_accel_path (GTK_MENU(menuitem_view_unit_menu), ACCEL_VIEW_UNITS);
-		gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem_view_unit), menuitem_view_unit_menu);
+        render_fast            = gtk_radio_menu_item_new_with_mnemonic(menu_view_render_group, _("_Fast"));
+        menu_view_render_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(render_fast));
+        gtk_container_add(GTK_CONTAINER(menuitem_view_render_menu), render_fast);
 
-		menu_view_unit_group = NULL;
+        render_fast_xor        = gtk_radio_menu_item_new_with_mnemonic(menu_view_render_group, _("Fast (_XOR)"));
+        menu_view_render_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(render_fast_xor));
+        gtk_container_add(GTK_CONTAINER(menuitem_view_render_menu), render_fast_xor);
 
-		unit_mil = gtk_radio_menu_item_new_with_mnemonic (menu_view_unit_group, _("mi_l"));
-		menu_view_unit_group = gtk_radio_menu_item_get_group (GTK_RADIO_MENU_ITEM (unit_mil));
-		gtk_container_add (GTK_CONTAINER (menuitem_view_unit_menu), unit_mil);
+        render_normal          = gtk_radio_menu_item_new_with_mnemonic(menu_view_render_group, _("_Normal"));
+        menu_view_render_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(render_normal));
+        gtk_container_add(GTK_CONTAINER(menuitem_view_render_menu), render_normal);
 
-		unit_mm = gtk_radio_menu_item_new_with_mnemonic (menu_view_unit_group, _("_mm"));
-		menu_view_unit_group = gtk_radio_menu_item_get_group (GTK_RADIO_MENU_ITEM (unit_mm));
-		gtk_container_add (GTK_CONTAINER (menuitem_view_unit_menu), unit_mm);
+        render_hq              = gtk_radio_menu_item_new_with_mnemonic(menu_view_render_group, _("High _Quality"));
+        menu_view_render_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(render_hq));
+        gtk_container_add(GTK_CONTAINER(menuitem_view_render_menu), render_hq);
 
-		unit_in = gtk_radio_menu_item_new_with_mnemonic (menu_view_unit_group, _("_in"));
-		menu_view_unit_group = gtk_radio_menu_item_get_group (GTK_RADIO_MENU_ITEM (unit_in));
-		gtk_container_add (GTK_CONTAINER (menuitem_view_unit_menu), unit_in);
-		
-		screen.win.menu_view_unit_group = malloc(3*sizeof(GtkWidget *));
-		if(screen.win.menu_view_unit_group == NULL)
-			GERB_FATAL_ERROR("malloc for display unit synchronization failed in %s()", __FUNCTION__);
+        screen.win.menu_view_render_group = malloc(4 * sizeof(GtkWidget*));
+        if (screen.win.menu_view_render_group == NULL)
+            GERB_FATAL_ERROR("malloc for rendering type synchronization failed in %s()", __FUNCTION__);
 
-		screen.win.menu_view_unit_group[GERBV_MILS] = GTK_CHECK_MENU_ITEM(unit_mil);
-		screen.win.menu_view_unit_group[GERBV_MMS] = GTK_CHECK_MENU_ITEM(unit_mm);
-		screen.win.menu_view_unit_group[GERBV_INS] = GTK_CHECK_MENU_ITEM(unit_in);
-	}
+        screen.win.menu_view_render_group[GERBV_RENDER_TYPE_GDK]                = GTK_CHECK_MENU_ITEM(render_fast);
+        screen.win.menu_view_render_group[GERBV_RENDER_TYPE_GDK_XOR]            = GTK_CHECK_MENU_ITEM(render_fast_xor);
+        screen.win.menu_view_render_group[GERBV_RENDER_TYPE_CAIRO_NORMAL]       = GTK_CHECK_MENU_ITEM(render_normal);
+        screen.win.menu_view_render_group[GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY] = GTK_CHECK_MENU_ITEM(render_hq);
+    }
 
-	/* --- Next menu item (Current Layer) --- */
-	menuitem_layer = gtk_menu_item_new_with_mnemonic (_("_Layer"));
-	gtk_container_add (GTK_CONTAINER (menubar1), menuitem_layer);
-
-	menuitem_layer_menu = gtk_menu_new ();
-	gtk_menu_set_accel_group (GTK_MENU (menuitem_layer_menu), accel_group);
-	gtk_menu_set_accel_path (GTK_MENU (menuitem_layer_menu), ACCEL_LAYER);
-	gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem_layer), menuitem_layer_menu);
-
-	layer_visibility = gtk_menu_item_new_with_mnemonic (_("Toggle _visibility"));
-	gtk_tooltips_set_tip (tooltips, layer_visibility,
-			_("Toggles the visibility of the active layer"), NULL);
-	gtk_container_add (GTK_CONTAINER (menuitem_layer_menu), layer_visibility);
-
-	layer_visibility_all_on = gtk_image_menu_item_new_with_mnemonic (_("All o_n"));
-	SET_ACCELS (layer_visibility_all_on, ACCEL_LAYER_ALL_ON);
-	gtk_tooltips_set_tip (tooltips, layer_visibility_all_on, _("Turn on visibility of all layers"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_YES, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (layer_visibility_all_on), tempImage);
-	gtk_container_add (GTK_CONTAINER (menuitem_layer_menu), layer_visibility_all_on);
-
-	layer_visibility_all_off = gtk_image_menu_item_new_with_mnemonic (_("All _off"));
-	SET_ACCELS (layer_visibility_all_off, ACCEL_LAYER_ALL_OFF);
-	gtk_tooltips_set_tip (tooltips, layer_visibility_all_off, _("Turn off visibility of all layers"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_NO, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (layer_visibility_all_off), tempImage);
-	gtk_container_add (GTK_CONTAINER (menuitem_layer_menu), layer_visibility_all_off);
-
-	layer_invert = gtk_menu_item_new_with_mnemonic (_("_Invert color"));
-	gtk_tooltips_set_tip (tooltips, layer_invert,
-		_("Invert the display polarity of the active layer"), NULL);
-	gtk_container_add (GTK_CONTAINER (menuitem_layer_menu), layer_invert);
-
-	layer_color = gtk_image_menu_item_new_with_mnemonic (_("_Change color"));
-	SET_ACCELS (layer_color, ACCEL_LAYER_COLOR);
-	gtk_tooltips_set_tip (tooltips, layer_color,
-		_("Change the display color of the active layer"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_SELECT_COLOR, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (layer_color), tempImage);
-	gtk_container_add (GTK_CONTAINER (menuitem_layer_menu), layer_color);
-
-	gtk_container_add (GTK_CONTAINER (menuitem_layer_menu),
-			gtk_separator_menu_item_new ());
-
-	layer_reload = gtk_image_menu_item_new_with_mnemonic (_("_Reload layer"));
-	gtk_tooltips_set_tip (tooltips, layer_reload,
-			_("Reload the active layer from disk"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_REVERT_TO_SAVED, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (layer_reload), tempImage);
-	gtk_container_add (GTK_CONTAINER (menuitem_layer_menu), layer_reload);
-
-	layer_edit = gtk_image_menu_item_new_with_mnemonic (_("_Edit layer"));
-	gtk_container_add (GTK_CONTAINER (menuitem_layer_menu), layer_edit);
-	gtk_tooltips_set_tip (tooltips, layer_edit,
-		_("Translate, scale, rotate or mirror the active layer"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_EDIT, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (layer_edit), tempImage);
-
-	layer_format = gtk_image_menu_item_new_with_mnemonic (_("Edit file _format"));
-	gtk_tooltips_set_tip (tooltips, layer_format,
-		_("View and edit the numerical format used to parse "
-			"the active layer"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_PREFERENCES, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (layer_format), tempImage);
-	gtk_container_add (GTK_CONTAINER (menuitem_layer_menu), layer_format);
-
-	gtk_container_add (GTK_CONTAINER (menuitem_layer_menu),
-			gtk_separator_menu_item_new ());
-
-	layer_up = gtk_image_menu_item_new_with_mnemonic (_("Move u_p"));
-	gtk_tooltips_set_tip (tooltips, layer_up,
-		_("Move the active layer one step up"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_GO_UP, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (layer_up), tempImage);
-	SET_ACCELS (layer_up, ACCEL_LAYER_UP);
-	gtk_container_add (GTK_CONTAINER (menuitem_layer_menu), layer_up);
-
-	layer_down = gtk_image_menu_item_new_with_mnemonic (_("Move dow_n"));
-	gtk_tooltips_set_tip (tooltips, layer_down,
-		_("Move the active layer one step down"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_GO_DOWN, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (layer_down), tempImage);
-	SET_ACCELS (layer_down, ACCEL_LAYER_DOWN);
-	gtk_container_add (GTK_CONTAINER (menuitem_layer_menu), layer_down);
-
-	layer_remove = gtk_image_menu_item_new_with_mnemonic (_("_Delete"));
-	gtk_tooltips_set_tip (tooltips, layer_remove,
-		_("Remove the active layer"), NULL);
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_REMOVE, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (layer_remove), tempImage);
-	SET_ACCELS (layer_remove, ACCEL_LAYER_DELETE);
-	gtk_container_add (GTK_CONTAINER (menuitem_layer_menu), layer_remove);
-
-	/* The callbacks need this reference to grey the layer menu out, if there are none loaded. */
-	screen.win.curLayerMenuItem = menuitem_layer;
-
-	/* Use the "Current Layer" menu as right click popup menu for layer tree */
-	screen.win.layerTreePopupMenu = menuitem_layer_menu;
-
-	/* --- Next menu item (Analyze) --- */
-	menuitem_analyze = gtk_menu_item_new_with_mnemonic (_("_Analyze"));
-	screen.win.curAnalyzeMenuItem = menuitem_analyze;
-	gtk_container_add (GTK_CONTAINER (menubar1), menuitem_analyze);
-
-	screen.selectionInfo.selectedNodeArray = selection_new_array ();
-
-	menuitem_analyze_menu = gtk_menu_new ();
-	gtk_menu_set_accel_group (GTK_MENU(menuitem_analyze_menu), accel_group);
-	gtk_menu_set_accel_path (GTK_MENU(menuitem_analyze_menu), ACCEL_ANAL);
-	gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem_analyze), menuitem_analyze_menu);
-
-	analyze_active_gerbers = gtk_menu_item_new_with_mnemonic (
-			_("Analyze visible _Gerber layers"));
-	gtk_tooltips_set_tip (tooltips, analyze_active_gerbers, 
-			_("Examine a detailed analysis of the contents "
-				"of all visible Gerber layers"), NULL);
-	gtk_container_add (GTK_CONTAINER (menuitem_analyze_menu),
-			analyze_active_gerbers);
-
-	analyze_active_drill = gtk_menu_item_new_with_mnemonic (
-			_("Analyze visible _drill layers"));
-	gtk_tooltips_set_tip (tooltips, analyze_active_drill, 
-			_("Examine a detailed analysis of the contents "
-				"of all visible drill layers"), NULL);
-	gtk_container_add (GTK_CONTAINER (menuitem_analyze_menu),
-			analyze_active_drill);
-
-	analyze_benchmark = gtk_menu_item_new_with_mnemonic (_("_Benchmark"));
-	gtk_tooltips_set_tip (tooltips, analyze_benchmark, 
-			_("Benchmark different rendering methods. Will make "
-			"the application unresponsive for 1 minute!"), NULL);
-	gtk_container_add (GTK_CONTAINER (menuitem_analyze_menu),
-			gtk_separator_menu_item_new ());
-	gtk_container_add (GTK_CONTAINER (menuitem_analyze_menu),
-			analyze_benchmark);
-
-	/* Wait and add in for 2.1??
-	control_gerber_options = gtk_menu_item_new_with_mnemonic (_("Control Gerber options..."));
-	gtk_tooltips_set_tip (tooltips, control_gerber_options, _("Set which Gerber features should be displayed"), NULL);
-	gtk_container_add (GTK_CONTAINER (menuitem_analyze_menu), control_gerber_options);
-	*/
-	menuitem_tools = gtk_menu_item_new_with_mnemonic (_("_Tools"));
-	gtk_container_add (GTK_CONTAINER (menubar1), menuitem_tools);
-
-	menuitem_tools_menu = gtk_menu_new ();
-	gtk_menu_set_accel_group (GTK_MENU(menuitem_tools_menu), accel_group);
-	gtk_menu_set_accel_path (GTK_MENU(menuitem_tools_menu), ACCEL_TOOLS);
-	gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem_tools), menuitem_tools_menu);
-	pointer_tool = gtk_image_menu_item_new_with_mnemonic (_("_Pointer Tool"));
-	tempImage = gtk_image_new_from_pixbuf (pointerpixbuf);
-	gtk_image_menu_item_set_image ((GtkImageMenuItem *)pointer_tool, tempImage);
-	SET_ACCELS (pointer_tool, ACCEL_TOOLS_POINTER);
-	gtk_container_add (GTK_CONTAINER (menuitem_tools_menu), pointer_tool);
-	gtk_tooltips_set_tip (tooltips, pointer_tool, _("Select objects on the screen"), NULL);
-	pan_tool = gtk_image_menu_item_new_with_mnemonic (_("Pa_n Tool"));
-	tempImage = gtk_image_new_from_pixbuf (movepixbuf);
-	gtk_image_menu_item_set_image ((GtkImageMenuItem *)pan_tool, tempImage);
-	SET_ACCELS (pan_tool, ACCEL_TOOLS_PAN);
-	gtk_container_add (GTK_CONTAINER (menuitem_tools_menu), pan_tool);
-	gtk_tooltips_set_tip (tooltips, pan_tool, _("Pan by left clicking and dragging"), NULL);
-
-	zoom_tool = gtk_image_menu_item_new_with_mnemonic (_("_Zoom Tool"));
-	tempImage = gtk_image_new_from_pixbuf (zoompixbuf);
-	gtk_image_menu_item_set_image ((GtkImageMenuItem *)zoom_tool, tempImage);
-	SET_ACCELS (zoom_tool, ACCEL_TOOLS_ZOOM);
-	gtk_container_add (GTK_CONTAINER (menuitem_tools_menu), zoom_tool);
-	gtk_tooltips_set_tip (tooltips, zoom_tool, _("Zoom by left clicking or dragging"), NULL);
-
-	measure_tool = gtk_image_menu_item_new_with_mnemonic (_("_Measure Tool"));
-	tempImage = gtk_image_new_from_pixbuf (measurepixbuf);
-	gtk_image_menu_item_set_image ((GtkImageMenuItem *)measure_tool, tempImage);
-	SET_ACCELS (measure_tool, ACCEL_TOOLS_MEASURE);
-	gtk_container_add (GTK_CONTAINER (menuitem_tools_menu), measure_tool);
-	gtk_tooltips_set_tip (tooltips, measure_tool, _("Measure distances on the screen"), NULL);
-
-	menuitem_help = gtk_menu_item_new_with_mnemonic (_("_Help"));
-	gtk_container_add (GTK_CONTAINER (menubar1), menuitem_help);
-
-	menuitem_help_menu = gtk_menu_new ();
-	gtk_menu_set_accel_group (GTK_MENU(menuitem_help_menu), accel_group);
-	gtk_menu_set_accel_path (GTK_MENU(menuitem_help_menu), ACCEL_HELP);
-	gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem_help), menuitem_help_menu);
-
-	/* Not ready for 2.0
-	online_manual = gtk_menu_item_new_with_mnemonic (_("_Online Manual..."));
-	gtk_container_add (GTK_CONTAINER (menuitem_help_menu), online_manual);
-	gtk_tooltips_set_tip (tooltips, online_manual, _("View the online help documentation"), NULL);
-	*/
-
-	about = gtk_image_menu_item_new_with_mnemonic (_("_About Gerbv..."));
-	gtk_container_add (GTK_CONTAINER (menuitem_help_menu), about);
-	gtk_tooltips_set_tip (tooltips, about, _("View information about Gerbv"), NULL);
-	image34 = gtk_image_new_from_stock (GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (about), image34);
-
-	bugs_menuitem = gtk_image_menu_item_new_with_mnemonic (_("Known _bugs in this version..."));
-	tempImage = gtk_image_new_from_stock (GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_MENU);
-	gtk_image_menu_item_set_image (GTK_IMAGE_MENU_ITEM (bugs_menuitem), tempImage);
-	gtk_tooltips_set_tip (tooltips, bugs_menuitem, _("View list of known Gerbv bugs"), NULL);	
-	gtk_container_add (GTK_CONTAINER (menuitem_help_menu), bugs_menuitem);
-
-	/* Create toolbar (button bar) beneath main menu */
-	toolbar_hbox = gtk_hbox_new (FALSE, 0);
-	gtk_box_pack_start (GTK_BOX (vbox1), toolbar_hbox, FALSE, FALSE, 0);
-
-	handlebox = gtk_handle_box_new ();
-	
-	gtk_box_pack_start (GTK_BOX (toolbar_hbox), handlebox, TRUE, TRUE, 0);
-
-	button_toolbar = gtk_toolbar_new ();
-	gtk_widget_set_size_request (button_toolbar, 500, -1);
-	gtk_container_add (GTK_CONTAINER (handlebox), button_toolbar);
-	gtk_toolbar_set_style (GTK_TOOLBAR (button_toolbar), GTK_TOOLBAR_ICONS);
-	/*tmp_toolbar_icon_size = gtk_toolbar_get_icon_size (GTK_TOOLBAR (button_toolbar));*/
-
-	toolbutton_new = (GtkWidget*) gtk_tool_button_new_from_stock (GTK_STOCK_NEW);
-	gtk_tooltips_set_tip (tooltips, toolbutton_new, _("Close all layers and start a new project"), NULL);
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toolbutton_new);
-
-	toolbutton_open = (GtkWidget*) gtk_tool_button_new_from_stock (GTK_STOCK_OPEN);
-	gtk_tooltips_set_tip (tooltips, toolbutton_open,
-			_("Open Gerbv project, Gerber, drill, "
-				"or pick&place files"), NULL);
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toolbutton_open);
-
-	toolbutton_revert = (GtkWidget*) gtk_tool_button_new_from_stock (GTK_STOCK_REVERT_TO_SAVED);
-	gtk_tooltips_set_tip (tooltips, toolbutton_revert, _("Reload all layers in project"), NULL);
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toolbutton_revert);
-
-	toolbutton_save = (GtkWidget*) gtk_tool_button_new_from_stock (GTK_STOCK_SAVE);
-	gtk_tooltips_set_tip (tooltips, toolbutton_save, _("Save the current project"), NULL);
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toolbutton_save);
-
-	separatortoolitem1 = (GtkWidget*) gtk_separator_tool_item_new ();
-	gtk_container_add (GTK_CONTAINER (button_toolbar), separatortoolitem1);
-#if GTK_CHECK_VERSION(2,10,0)
-	toolbutton_print = (GtkWidget*) gtk_tool_button_new_from_stock (GTK_STOCK_PRINT);
-	gtk_tooltips_set_tip (tooltips, toolbutton_print, _("Print the visible layers"), NULL);
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toolbutton_print);
-
-	separatortoolitem2 = (GtkWidget*) gtk_separator_tool_item_new ();
-	gtk_container_add (GTK_CONTAINER (button_toolbar), separatortoolitem2);
-#endif
-	toolbutton_zoom_in = (GtkWidget*) gtk_tool_button_new_from_stock (GTK_STOCK_ZOOM_IN);
-	gtk_tooltips_set_tip (tooltips, toolbutton_zoom_in, _("Zoom in"), NULL);
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toolbutton_zoom_in);
+    {  // units submenu
+        gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(render_fast), TRUE);
 
-	toolbutton_zoom_out = (GtkWidget*) gtk_tool_button_new_from_stock (GTK_STOCK_ZOOM_OUT);
-	gtk_tooltips_set_tip (tooltips, toolbutton_zoom_out, _("Zoom out"), NULL);
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toolbutton_zoom_out);
+        menuitem_view_unit = gtk_menu_item_new_with_mnemonic(_("U_nits"));
+        gtk_container_add(GTK_CONTAINER(menuitem_view_menu), menuitem_view_unit);
 
-	toolbutton_zoom_fit = (GtkWidget*) gtk_tool_button_new_from_stock (GTK_STOCK_ZOOM_FIT);
-	gtk_tooltips_set_tip (tooltips, toolbutton_zoom_fit, _("Zoom to fit all visible layers in the window"), NULL);
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toolbutton_zoom_fit);
+        menuitem_view_unit_menu = gtk_menu_new();
+        gtk_menu_set_accel_group(GTK_MENU(menuitem_view_unit_menu), accel_group);
+        gtk_menu_set_accel_path(GTK_MENU(menuitem_view_unit_menu), ACCEL_VIEW_UNITS);
+        gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem_view_unit), menuitem_view_unit_menu);
 
-/* Turn these on later when we have icons for these buttons */
-/*
-	separatortoolitem3 = (GtkWidget*) gtk_separator_tool_item_new ();
-	gtk_container_add (GTK_CONTAINER (button_toolbar), separatortoolitem3);
+        menu_view_unit_group = NULL;
 
-	toolbutton_analyze = (GtkWidget*) gtk_tool_button_new_from_stock ("gtk-apply");
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toolbutton_analyze);
+        unit_mil             = gtk_radio_menu_item_new_with_mnemonic(menu_view_unit_group, _("mi_l"));
+        menu_view_unit_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(unit_mil));
+        gtk_container_add(GTK_CONTAINER(menuitem_view_unit_menu), unit_mil);
 
-	toolbutton_validate = (GtkWidget*) gtk_tool_button_new_from_stock ("gtk-apply");
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toolbutton_validate);
+        unit_mm              = gtk_radio_menu_item_new_with_mnemonic(menu_view_unit_group, _("_mm"));
+        menu_view_unit_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(unit_mm));
+        gtk_container_add(GTK_CONTAINER(menuitem_view_unit_menu), unit_mm);
 
-	toolbutton_control = (GtkWidget*) gtk_tool_button_new_from_stock ("gtk-apply");
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toolbutton_control);
-*/
+        unit_in              = gtk_radio_menu_item_new_with_mnemonic(menu_view_unit_group, _("_in"));
+        menu_view_unit_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(unit_in));
+        gtk_container_add(GTK_CONTAINER(menuitem_view_unit_menu), unit_in);
 
-	separatortoolitem4 = (GtkWidget*) gtk_separator_tool_item_new ();
-	gtk_container_add (GTK_CONTAINER (button_toolbar), separatortoolitem4);
-	toggletoolbutton_pointer = (GtkWidget*) gtk_toggle_tool_button_new();
-	pointerimage = gtk_image_new_from_pixbuf(pointerpixbuf);
-	gtk_tool_button_set_icon_widget(GTK_TOOL_BUTTON(toggletoolbutton_pointer),
-					pointerimage);
-	gtk_tooltips_set_tip (tooltips, toggletoolbutton_pointer, _("Select objects on the screen"), NULL);	
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toggletoolbutton_pointer);
-	toggletoolbutton_pan = (GtkWidget*) gtk_toggle_tool_button_new();
-	moveimage = gtk_image_new_from_pixbuf(movepixbuf);
-	gtk_tool_button_set_icon_widget(GTK_TOOL_BUTTON(toggletoolbutton_pan),
-					moveimage);
-	gtk_tooltips_set_tip (tooltips, toggletoolbutton_pan, _("Pan by left clicking and dragging"), NULL);
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toggletoolbutton_pan);
-	
-
-	toggletoolbutton_zoom = (GtkWidget*) gtk_toggle_tool_button_new();
-	zoomimage = gtk_image_new_from_pixbuf(zoompixbuf);
-	gtk_tool_button_set_icon_widget(GTK_TOOL_BUTTON(toggletoolbutton_zoom),
-					zoomimage);
-	gtk_tooltips_set_tip (tooltips, toggletoolbutton_zoom, _("Zoom by left clicking or dragging"), NULL);
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toggletoolbutton_zoom);
-
-	toggletoolbutton_measure = (GtkWidget*) gtk_toggle_tool_button_new();
-	measureimage = gtk_image_new_from_pixbuf(measurepixbuf);
-	gtk_tool_button_set_icon_widget(GTK_TOOL_BUTTON(toggletoolbutton_measure),
-					measureimage);
-	gtk_tooltips_set_tip (tooltips, toggletoolbutton_measure, _("Measure distances on the screen"), NULL);
-	gtk_container_add (GTK_CONTAINER (button_toolbar), toggletoolbutton_measure);
-	
-	hpaned1 = gtk_hpaned_new ();
-	gtk_box_pack_start (GTK_BOX (vbox1), hpaned1, TRUE, TRUE, 0);
-	gtk_paned_set_position (GTK_PANED (hpaned1), 225);
-
-	sidepane_vbox = gtk_vbox_new (FALSE, 0);
-	gtk_widget_set_size_request (sidepane_vbox, 150, -1);
-
-	gtk_paned_pack1 (GTK_PANED (hpaned1), sidepane_vbox, FALSE, FALSE);
-	gtk_container_set_border_width (GTK_CONTAINER (sidepane_vbox), 5);
-
-	sidepane_notebook = gtk_notebook_new ();
-	gtk_widget_set_size_request (sidepane_notebook, 100, -1);
-	gtk_box_pack_start (GTK_BOX (sidepane_vbox), sidepane_notebook, TRUE, TRUE, 0);
-
-	vbox10 = gtk_vbox_new (FALSE, 3);
-	gtk_container_add (GTK_CONTAINER (sidepane_notebook), vbox10);
-	gtk_widget_set_size_request (vbox10, 82, -1);
-	gtk_container_set_border_width (GTK_CONTAINER (vbox10), 4);
-
-	hbox4 = gtk_hbox_new (FALSE, 0);
-	gtk_box_pack_start (GTK_BOX (vbox10), hbox4, FALSE, FALSE, 0);
-
-	render_combobox = gtk_combo_box_new_text ();
-	gtk_box_pack_start (GTK_BOX (hbox4), render_combobox, TRUE, TRUE, 0);
-	gtk_tooltips_set_tip (tooltips, render_combobox,
-			_("Rendering type"), NULL);
-
-	gtk_combo_box_append_text (GTK_COMBO_BOX (render_combobox), _("Fast"));
-	gtk_combo_box_append_text (GTK_COMBO_BOX (render_combobox), _("Fast, with XOR"));
-	gtk_combo_box_append_text (GTK_COMBO_BOX (render_combobox), _("Normal"));
-	gtk_combo_box_append_text (GTK_COMBO_BOX (render_combobox), _("High quality"));
-
-	if (screen.settings) {
-		g_settings_bind (screen.settings, "visual-rendering-type",
-				render_combobox, "active",
-				G_SETTINGS_BIND_DEFAULT);
-
-		/* Sync menu item render type */
-		screenRenderInfo.renderType =
-			gtk_combo_box_get_active (
-					GTK_COMBO_BOX (render_combobox));
-		if ((unsigned int)screenRenderInfo.renderType <
-				GERBV_RENDER_TYPE_MAX) {
-			gtk_check_menu_item_set_active (
-					screen.win.menu_view_render_group[
-						screenRenderInfo.renderType],
-						TRUE);
-		}
-	} else {
-		gtk_combo_box_set_active (GTK_COMBO_BOX(render_combobox),
-				screenRenderInfo.renderType);
-	}
+        screen.win.menu_view_unit_group = malloc(3 * sizeof(GtkWidget*));
+        if (screen.win.menu_view_unit_group == NULL)
+            GERB_FATAL_ERROR("malloc for display unit synchronization failed in %s()", __FUNCTION__);
 
-	scrolledwindow1 = gtk_scrolled_window_new (NULL, NULL);
-	gtk_box_pack_start (GTK_BOX (vbox10), scrolledwindow1, TRUE, TRUE, 0);
-	gtk_container_set_border_width (GTK_CONTAINER (scrolledwindow1), 2);
-	gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolledwindow1), 
-					GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
-	gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolledwindow1), 
-					     GTK_SHADOW_IN);
-
-	hbox1 = gtk_hbox_new (TRUE, 0);
-	gtk_box_pack_start (GTK_BOX (vbox10), hbox1, FALSE, FALSE, 0);
-
-	button4 = gtk_button_new ();
-	gtk_box_pack_start (GTK_BOX (hbox1), button4, FALSE, TRUE, 0);
-
-	image8 = gtk_image_new_from_stock (GTK_STOCK_ADD, GTK_ICON_SIZE_BUTTON);
-	gtk_container_add (GTK_CONTAINER (button4), image8);
-	gtk_tooltips_set_tip (tooltips, button4,
-			_("Open Gerbv project, Gerber, drill, "
-				"or pick&place files"), NULL);
-
-	button5 = gtk_button_new ();
-	gtk_box_pack_start (GTK_BOX (hbox1), button5, FALSE, TRUE, 0);
-
-	image9 = gtk_image_new_from_stock (GTK_STOCK_GO_DOWN, GTK_ICON_SIZE_BUTTON);
-	gtk_container_add (GTK_CONTAINER (button5), image9);
-	gtk_tooltips_set_tip (tooltips, button5,
-			_("Move the active layer one step down"), NULL);
-
-	button6 = gtk_button_new ();
-	gtk_box_pack_start (GTK_BOX (hbox1), button6, FALSE, TRUE, 0);
-
-	image10 = gtk_image_new_from_stock (GTK_STOCK_GO_UP, GTK_ICON_SIZE_BUTTON);
-	gtk_container_add (GTK_CONTAINER (button6), image10);
-	gtk_tooltips_set_tip (tooltips, button6,
-			_("Move the active layer one step up"), NULL);
-
-	button7 = gtk_button_new ();
-	gtk_box_pack_start (GTK_BOX (hbox1), button7, FALSE, TRUE, 0);
-
-	image11 = gtk_image_new_from_stock (GTK_STOCK_REMOVE, GTK_ICON_SIZE_BUTTON);
-	gtk_container_add (GTK_CONTAINER (button7), image11);
-	gtk_tooltips_set_tip (tooltips, button7,
-			_("Remove the active layer"), NULL);
-
-	Layer_label = gtk_label_new (_("Layers"));
-	gtk_notebook_set_tab_label (GTK_NOTEBOOK (sidepane_notebook), 
-				    gtk_notebook_get_nth_page (GTK_NOTEBOOK (sidepane_notebook), 0), 
-				    Layer_label);
-
-	vbox11 = gtk_vbox_new (FALSE, 2);
-	gtk_container_add (GTK_CONTAINER (sidepane_notebook), vbox11);
-	gtk_container_set_border_width (GTK_CONTAINER (vbox11), 3);
-
-	messages_scrolledwindow = gtk_scrolled_window_new (NULL, NULL);
-	gtk_box_pack_start (GTK_BOX (vbox11), messages_scrolledwindow, TRUE, TRUE, 0);
-	gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (messages_scrolledwindow), 
-					GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
-
-	message_textview = gtk_text_view_new ();
-	gtk_container_add (GTK_CONTAINER (messages_scrolledwindow), message_textview);
-	gtk_text_view_set_editable (GTK_TEXT_VIEW (message_textview), FALSE);
-	gtk_text_view_set_wrap_mode (GTK_TEXT_VIEW (message_textview), GTK_WRAP_WORD);
-	gtk_text_view_set_cursor_visible (GTK_TEXT_VIEW (message_textview), FALSE);
-
-	clear_messages_button = gtk_button_new_from_stock (GTK_STOCK_CLEAR);
-	gtk_tooltips_set_tip (tooltips, clear_messages_button,
-			_("Clear all messages and accumulated sum"), NULL);
-	gtk_box_pack_start (GTK_BOX (vbox11), clear_messages_button, FALSE, FALSE, 0);
-
-	Message_label = gtk_label_new (_("Messages"));
-	gtk_notebook_set_tab_label (GTK_NOTEBOOK (sidepane_notebook), 
-				    gtk_notebook_get_nth_page (GTK_NOTEBOOK (sidepane_notebook), 1), 
-				    Message_label);
-
-	vbox2 = gtk_vbox_new (FALSE, 4);
-	gtk_paned_pack2 (GTK_PANED (hpaned1), vbox2, TRUE, FALSE);
-	gtk_container_set_border_width (GTK_CONTAINER (vbox2), 4);
-	
-	main_view_table = gtk_table_new (3, 3, FALSE);
-	gtk_box_pack_start (GTK_BOX (vbox2), main_view_table, TRUE, TRUE, 0);
-
-	hRuler = gtk_hruler_new ();
-	gtk_table_attach (GTK_TABLE (main_view_table), hRuler, 1, 2, 0, 1,
-	                  (GtkAttachOptions) (GTK_EXPAND | GTK_FILL),
-	                  (GtkAttachOptions) (GTK_FILL), 0, 0);
-	gtk_ruler_set_range (GTK_RULER (hRuler), 0, 100, 8.56051, 1000);
-
-	vRuler = gtk_vruler_new ();
-	gtk_table_attach (GTK_TABLE (main_view_table), vRuler, 0, 1, 1, 2,
-	                  (GtkAttachOptions) (GTK_FILL),
-	                  (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), 0, 0);
-	gtk_ruler_set_range (GTK_RULER (vRuler), 0, 100, 8.37341, 1000);
-
-	drawingarea = gtk_drawing_area_new();
-	gtk_table_attach (GTK_TABLE (main_view_table), drawingarea, 1, 2, 1, 2,
-	                  (GtkAttachOptions) (GTK_FILL),
-	                  (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), 0, 0);
-	
-	hAdjustment = (GtkWidget *) gtk_adjustment_new (0.0, -1000.0, 1000.0, 1000.0, 1000.0, 500.0);
-	vAdjustment = (GtkWidget *) gtk_adjustment_new (0.0, -1000.0, 1000.0, 1000.0, 1000.0, 500.0);
-	
-	hScrollbar = gtk_hscrollbar_new (GTK_ADJUSTMENT (hAdjustment));
-	gtk_table_attach (GTK_TABLE (main_view_table), hScrollbar, 1, 2, 2, 3,
-	                  (GtkAttachOptions) (GTK_FILL),
-	                  (GtkAttachOptions) (GTK_FILL), 0, 0);
-	                  
-	vScrollbar = gtk_vscrollbar_new (GTK_ADJUSTMENT (vAdjustment));
-	gtk_table_attach (GTK_TABLE (main_view_table), vScrollbar, 2, 3, 1, 2,
-	                  (GtkAttachOptions) (GTK_FILL),
-	                  (GtkAttachOptions) (GTK_FILL), 0, 0);
-	
-	hbox5 = gtk_hbox_new (FALSE, 10);
-	gtk_box_pack_start (GTK_BOX (vbox2), hbox5, FALSE, FALSE, 0);
-
-	statusbar_label_left = gtk_label_new ("");
-	gtk_box_pack_start (GTK_BOX (hbox5), statusbar_label_left, FALSE, FALSE, 0);
-	gtk_label_set_justify (GTK_LABEL (statusbar_label_left), GTK_JUSTIFY_CENTER);
-
-	statusUnitComboBox = gtk_combo_box_new_text ();
-	gtk_box_pack_start (GTK_BOX (hbox5), statusUnitComboBox, FALSE, FALSE, 0);
-	gtk_combo_box_append_text (GTK_COMBO_BOX (statusUnitComboBox), _("mil"));
-	gtk_combo_box_append_text (GTK_COMBO_BOX (statusUnitComboBox), _("mm"));
-	gtk_combo_box_append_text (GTK_COMBO_BOX (statusUnitComboBox), _("in"));
-	screen.win.statusUnitComboBox = statusUnitComboBox;
-
-	/* 1. Set default unit */
-	int screen_unit_orig = screen.unit;
-	/* Trigger change */
-
-	gtk_combo_box_set_active (GTK_COMBO_BOX (statusUnitComboBox),
-			screen_unit_orig);
-	/* Update unit item in menu */
-	callbacks_statusbar_unit_combo_box_changed (
-			GTK_COMBO_BOX (statusUnitComboBox),
-			GINT_TO_POINTER (TRUE));
-
-	/* 2. Try to set unit from stored settings */
-	if (screen.settings) {
-		g_settings_bind (screen.settings, "visual-unit",
-				statusUnitComboBox, "active",
-				G_SETTINGS_BIND_DEFAULT);
-		/* Update unit item in menu */
-		callbacks_statusbar_unit_combo_box_changed (
-				GTK_COMBO_BOX (statusUnitComboBox),
-				GINT_TO_POINTER (TRUE));
-	}
+        screen.win.menu_view_unit_group[GERBV_MILS] = GTK_CHECK_MENU_ITEM(unit_mil);
+        screen.win.menu_view_unit_group[GERBV_MMS]  = GTK_CHECK_MENU_ITEM(unit_mm);
+        screen.win.menu_view_unit_group[GERBV_INS]  = GTK_CHECK_MENU_ITEM(unit_in);
+    }
 
-	/* 3. Override unit from cmdline */
-	if (screen.unit_is_from_cmdline) {
-		gtk_combo_box_set_active (GTK_COMBO_BOX (statusUnitComboBox),
-				screen_unit_orig);
-		/* Update unit item in menu */
-		callbacks_statusbar_unit_combo_box_changed (
-				GTK_COMBO_BOX (statusUnitComboBox),
-				GINT_TO_POINTER (TRUE));
-	}
+    /* --- Next menu item (Current Layer) --- */
+    menuitem_layer = gtk_menu_item_new_with_mnemonic(_("_Layer"));
+    gtk_container_add(GTK_CONTAINER(menubar1), menuitem_layer);
+
+    menuitem_layer_menu = gtk_menu_new();
+    gtk_menu_set_accel_group(GTK_MENU(menuitem_layer_menu), accel_group);
+    gtk_menu_set_accel_path(GTK_MENU(menuitem_layer_menu), ACCEL_LAYER);
+    gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem_layer), menuitem_layer_menu);
+
+    layer_visibility = gtk_menu_item_new_with_mnemonic(_("Toggle _visibility"));
+    gtk_tooltips_set_tip(tooltips, layer_visibility, _("Toggles the visibility of the active layer"), NULL);
+    gtk_container_add(GTK_CONTAINER(menuitem_layer_menu), layer_visibility);
+
+    layer_visibility_all_on = gtk_image_menu_item_new_with_mnemonic(_("All o_n"));
+    SET_ACCELS(layer_visibility_all_on, ACCEL_LAYER_ALL_ON);
+    gtk_tooltips_set_tip(tooltips, layer_visibility_all_on, _("Turn on visibility of all layers"), NULL);
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_YES, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(layer_visibility_all_on), tempImage);
+    gtk_container_add(GTK_CONTAINER(menuitem_layer_menu), layer_visibility_all_on);
+
+    layer_visibility_all_off = gtk_image_menu_item_new_with_mnemonic(_("All _off"));
+    SET_ACCELS(layer_visibility_all_off, ACCEL_LAYER_ALL_OFF);
+    gtk_tooltips_set_tip(tooltips, layer_visibility_all_off, _("Turn off visibility of all layers"), NULL);
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_NO, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(layer_visibility_all_off), tempImage);
+    gtk_container_add(GTK_CONTAINER(menuitem_layer_menu), layer_visibility_all_off);
+
+    layer_invert = gtk_menu_item_new_with_mnemonic(_("_Invert color"));
+    gtk_tooltips_set_tip(tooltips, layer_invert, _("Invert the display polarity of the active layer"), NULL);
+    gtk_container_add(GTK_CONTAINER(menuitem_layer_menu), layer_invert);
+
+    layer_color = gtk_image_menu_item_new_with_mnemonic(_("_Change color"));
+    SET_ACCELS(layer_color, ACCEL_LAYER_COLOR);
+    gtk_tooltips_set_tip(tooltips, layer_color, _("Change the display color of the active layer"), NULL);
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_SELECT_COLOR, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(layer_color), tempImage);
+    gtk_container_add(GTK_CONTAINER(menuitem_layer_menu), layer_color);
+
+    gtk_container_add(GTK_CONTAINER(menuitem_layer_menu), gtk_separator_menu_item_new());
+
+    layer_reload = gtk_image_menu_item_new_with_mnemonic(_("_Reload layer"));
+    gtk_tooltips_set_tip(tooltips, layer_reload, _("Reload the active layer from disk"), NULL);
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_REVERT_TO_SAVED, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(layer_reload), tempImage);
+    gtk_container_add(GTK_CONTAINER(menuitem_layer_menu), layer_reload);
+
+    layer_edit = gtk_image_menu_item_new_with_mnemonic(_("_Edit layer"));
+    gtk_container_add(GTK_CONTAINER(menuitem_layer_menu), layer_edit);
+    gtk_tooltips_set_tip(tooltips, layer_edit, _("Translate, scale, rotate or mirror the active layer"), NULL);
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_EDIT, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(layer_edit), tempImage);
+
+    layer_format = gtk_image_menu_item_new_with_mnemonic(_("Edit file _format"));
+    gtk_tooltips_set_tip(
+        tooltips, layer_format,
+        _("View and edit the numerical format used to parse "
+          "the active layer"),
+        NULL
+    );
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_PREFERENCES, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(layer_format), tempImage);
+    gtk_container_add(GTK_CONTAINER(menuitem_layer_menu), layer_format);
+
+    gtk_container_add(GTK_CONTAINER(menuitem_layer_menu), gtk_separator_menu_item_new());
+
+    layer_up = gtk_image_menu_item_new_with_mnemonic(_("Move u_p"));
+    gtk_tooltips_set_tip(tooltips, layer_up, _("Move the active layer one step up"), NULL);
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_GO_UP, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(layer_up), tempImage);
+    SET_ACCELS(layer_up, ACCEL_LAYER_UP);
+    gtk_container_add(GTK_CONTAINER(menuitem_layer_menu), layer_up);
+
+    layer_down = gtk_image_menu_item_new_with_mnemonic(_("Move dow_n"));
+    gtk_tooltips_set_tip(tooltips, layer_down, _("Move the active layer one step down"), NULL);
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_GO_DOWN, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(layer_down), tempImage);
+    SET_ACCELS(layer_down, ACCEL_LAYER_DOWN);
+    gtk_container_add(GTK_CONTAINER(menuitem_layer_menu), layer_down);
+
+    layer_remove = gtk_image_menu_item_new_with_mnemonic(_("_Delete"));
+    gtk_tooltips_set_tip(tooltips, layer_remove, _("Remove the active layer"), NULL);
+    tempImage = gtk_image_new_from_stock(GTK_STOCK_REMOVE, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(layer_remove), tempImage);
+    SET_ACCELS(layer_remove, ACCEL_LAYER_DELETE);
+    gtk_container_add(GTK_CONTAINER(menuitem_layer_menu), layer_remove);
+
+    /* The callbacks need this reference to grey the layer menu out, if there are none loaded. */
+    screen.win.curLayerMenuItem = menuitem_layer;
+
+    /* Use the "Current Layer" menu as right click popup menu for layer tree */
+    screen.win.layerTreePopupMenu = menuitem_layer_menu;
+
+    /* --- Next menu item (Analyze) --- */
+    menuitem_analyze              = gtk_menu_item_new_with_mnemonic(_("_Analyze"));
+    screen.win.curAnalyzeMenuItem = menuitem_analyze;
+    gtk_container_add(GTK_CONTAINER(menubar1), menuitem_analyze);
+
+    screen.selectionInfo.selectedNodeArray = selection_new_array();
+
+    menuitem_analyze_menu = gtk_menu_new();
+    gtk_menu_set_accel_group(GTK_MENU(menuitem_analyze_menu), accel_group);
+    gtk_menu_set_accel_path(GTK_MENU(menuitem_analyze_menu), ACCEL_ANAL);
+    gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem_analyze), menuitem_analyze_menu);
+
+    analyze_active_gerbers = gtk_menu_item_new_with_mnemonic(_("Analyze visible _Gerber layers"));
+    gtk_tooltips_set_tip(
+        tooltips, analyze_active_gerbers,
+        _("Examine a detailed analysis of the contents "
+          "of all visible Gerber layers"),
+        NULL
+    );
+    gtk_container_add(GTK_CONTAINER(menuitem_analyze_menu), analyze_active_gerbers);
+
+    analyze_active_drill = gtk_menu_item_new_with_mnemonic(_("Analyze visible _drill layers"));
+    gtk_tooltips_set_tip(
+        tooltips, analyze_active_drill,
+        _("Examine a detailed analysis of the contents "
+          "of all visible drill layers"),
+        NULL
+    );
+    gtk_container_add(GTK_CONTAINER(menuitem_analyze_menu), analyze_active_drill);
+
+    analyze_benchmark = gtk_menu_item_new_with_mnemonic(_("_Benchmark"));
+    gtk_tooltips_set_tip(
+        tooltips, analyze_benchmark,
+        _("Benchmark different rendering methods. Will make "
+          "the application unresponsive for 1 minute!"),
+        NULL
+    );
+    gtk_container_add(GTK_CONTAINER(menuitem_analyze_menu), gtk_separator_menu_item_new());
+    gtk_container_add(GTK_CONTAINER(menuitem_analyze_menu), analyze_benchmark);
+
+    /* Wait and add in for 2.1??
+    control_gerber_options = gtk_menu_item_new_with_mnemonic (_("Control Gerber options..."));
+    gtk_tooltips_set_tip (tooltips, control_gerber_options, _("Set which Gerber features should be displayed"), NULL);
+    gtk_container_add (GTK_CONTAINER (menuitem_analyze_menu), control_gerber_options);
+    */
+    menuitem_tools = gtk_menu_item_new_with_mnemonic(_("_Tools"));
+    gtk_container_add(GTK_CONTAINER(menubar1), menuitem_tools);
+
+    menuitem_tools_menu = gtk_menu_new();
+    gtk_menu_set_accel_group(GTK_MENU(menuitem_tools_menu), accel_group);
+    gtk_menu_set_accel_path(GTK_MENU(menuitem_tools_menu), ACCEL_TOOLS);
+    gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem_tools), menuitem_tools_menu);
+    pointer_tool = gtk_image_menu_item_new_with_mnemonic(_("_Pointer Tool"));
+    tempImage    = gtk_image_new_from_pixbuf(pointerpixbuf);
+    gtk_image_menu_item_set_image((GtkImageMenuItem*)pointer_tool, tempImage);
+    SET_ACCELS(pointer_tool, ACCEL_TOOLS_POINTER);
+    gtk_container_add(GTK_CONTAINER(menuitem_tools_menu), pointer_tool);
+    gtk_tooltips_set_tip(tooltips, pointer_tool, _("Select objects on the screen"), NULL);
+    pan_tool  = gtk_image_menu_item_new_with_mnemonic(_("Pa_n Tool"));
+    tempImage = gtk_image_new_from_pixbuf(movepixbuf);
+    gtk_image_menu_item_set_image((GtkImageMenuItem*)pan_tool, tempImage);
+    SET_ACCELS(pan_tool, ACCEL_TOOLS_PAN);
+    gtk_container_add(GTK_CONTAINER(menuitem_tools_menu), pan_tool);
+    gtk_tooltips_set_tip(tooltips, pan_tool, _("Pan by left clicking and dragging"), NULL);
+
+    zoom_tool = gtk_image_menu_item_new_with_mnemonic(_("_Zoom Tool"));
+    tempImage = gtk_image_new_from_pixbuf(zoompixbuf);
+    gtk_image_menu_item_set_image((GtkImageMenuItem*)zoom_tool, tempImage);
+    SET_ACCELS(zoom_tool, ACCEL_TOOLS_ZOOM);
+    gtk_container_add(GTK_CONTAINER(menuitem_tools_menu), zoom_tool);
+    gtk_tooltips_set_tip(tooltips, zoom_tool, _("Zoom by left clicking or dragging"), NULL);
+
+    measure_tool = gtk_image_menu_item_new_with_mnemonic(_("_Measure Tool"));
+    tempImage    = gtk_image_new_from_pixbuf(measurepixbuf);
+    gtk_image_menu_item_set_image((GtkImageMenuItem*)measure_tool, tempImage);
+    SET_ACCELS(measure_tool, ACCEL_TOOLS_MEASURE);
+    gtk_container_add(GTK_CONTAINER(menuitem_tools_menu), measure_tool);
+    gtk_tooltips_set_tip(tooltips, measure_tool, _("Measure distances on the screen"), NULL);
+
+    menuitem_help = gtk_menu_item_new_with_mnemonic(_("_Help"));
+    gtk_container_add(GTK_CONTAINER(menubar1), menuitem_help);
+
+    menuitem_help_menu = gtk_menu_new();
+    gtk_menu_set_accel_group(GTK_MENU(menuitem_help_menu), accel_group);
+    gtk_menu_set_accel_path(GTK_MENU(menuitem_help_menu), ACCEL_HELP);
+    gtk_menu_item_set_submenu(GTK_MENU_ITEM(menuitem_help), menuitem_help_menu);
+
+    /* Not ready for 2.0
+    online_manual = gtk_menu_item_new_with_mnemonic (_("_Online Manual..."));
+    gtk_container_add (GTK_CONTAINER (menuitem_help_menu), online_manual);
+    gtk_tooltips_set_tip (tooltips, online_manual, _("View the online help documentation"), NULL);
+    */
+
+    about = gtk_image_menu_item_new_with_mnemonic(_("_About Gerbv..."));
+    gtk_container_add(GTK_CONTAINER(menuitem_help_menu), about);
+    gtk_tooltips_set_tip(tooltips, about, _("View information about Gerbv"), NULL);
+    image34 = gtk_image_new_from_stock(GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(about), image34);
+
+    bugs_menuitem = gtk_image_menu_item_new_with_mnemonic(_("Known _bugs in this version..."));
+    tempImage     = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_MENU);
+    gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(bugs_menuitem), tempImage);
+    gtk_tooltips_set_tip(tooltips, bugs_menuitem, _("View list of known Gerbv bugs"), NULL);
+    gtk_container_add(GTK_CONTAINER(menuitem_help_menu), bugs_menuitem);
+
+    /* Create toolbar (button bar) beneath main menu */
+    toolbar_hbox = gtk_hbox_new(FALSE, 0);
+    gtk_box_pack_start(GTK_BOX(vbox1), toolbar_hbox, FALSE, FALSE, 0);
+
+    handlebox = gtk_handle_box_new();
+
+    gtk_box_pack_start(GTK_BOX(toolbar_hbox), handlebox, TRUE, TRUE, 0);
+
+    button_toolbar = gtk_toolbar_new();
+    gtk_widget_set_size_request(button_toolbar, 500, -1);
+    gtk_container_add(GTK_CONTAINER(handlebox), button_toolbar);
+    gtk_toolbar_set_style(GTK_TOOLBAR(button_toolbar), GTK_TOOLBAR_ICONS);
+    /*tmp_toolbar_icon_size = gtk_toolbar_get_icon_size (GTK_TOOLBAR (button_toolbar));*/
+
+    toolbutton_new = (GtkWidget*)gtk_tool_button_new_from_stock(GTK_STOCK_NEW);
+    gtk_tooltips_set_tip(tooltips, toolbutton_new, _("Close all layers and start a new project"), NULL);
+    gtk_container_add(GTK_CONTAINER(button_toolbar), toolbutton_new);
+
+    toolbutton_open = (GtkWidget*)gtk_tool_button_new_from_stock(GTK_STOCK_OPEN);
+    gtk_tooltips_set_tip(
+        tooltips, toolbutton_open,
+        _("Open Gerbv project, Gerber, drill, "
+          "or pick&place files"),
+        NULL
+    );
+    gtk_container_add(GTK_CONTAINER(button_toolbar), toolbutton_open);
+
+    toolbutton_revert = (GtkWidget*)gtk_tool_button_new_from_stock(GTK_STOCK_REVERT_TO_SAVED);
+    gtk_tooltips_set_tip(tooltips, toolbutton_revert, _("Reload all layers in project"), NULL);
+    gtk_container_add(GTK_CONTAINER(button_toolbar), toolbutton_revert);
+
+    toolbutton_save = (GtkWidget*)gtk_tool_button_new_from_stock(GTK_STOCK_SAVE);
+    gtk_tooltips_set_tip(tooltips, toolbutton_save, _("Save the current project"), NULL);
+    gtk_container_add(GTK_CONTAINER(button_toolbar), toolbutton_save);
+
+    separatortoolitem1 = (GtkWidget*)gtk_separator_tool_item_new();
+    gtk_container_add(GTK_CONTAINER(button_toolbar), separatortoolitem1);
+#if GTK_CHECK_VERSION(2, 10, 0)
+    toolbutton_print = (GtkWidget*)gtk_tool_button_new_from_stock(GTK_STOCK_PRINT);
+    gtk_tooltips_set_tip(tooltips, toolbutton_print, _("Print the visible layers"), NULL);
+    gtk_container_add(GTK_CONTAINER(button_toolbar), toolbutton_print);
+
+    separatortoolitem2 = (GtkWidget*)gtk_separator_tool_item_new();
+    gtk_container_add(GTK_CONTAINER(button_toolbar), separatortoolitem2);
+#endif
+    toolbutton_zoom_in = (GtkWidget*)gtk_tool_button_new_from_stock(GTK_STOCK_ZOOM_IN);
+    gtk_tooltips_set_tip(tooltips, toolbutton_zoom_in, _("Zoom in"), NULL);
+    gtk_container_add(GTK_CONTAINER(button_toolbar), toolbutton_zoom_in);
+
+    toolbutton_zoom_out = (GtkWidget*)gtk_tool_button_new_from_stock(GTK_STOCK_ZOOM_OUT);
+    gtk_tooltips_set_tip(tooltips, toolbutton_zoom_out, _("Zoom out"), NULL);
+    gtk_container_add(GTK_CONTAINER(button_toolbar), toolbutton_zoom_out);
+
+    toolbutton_zoom_fit = (GtkWidget*)gtk_tool_button_new_from_stock(GTK_STOCK_ZOOM_FIT);
+    gtk_tooltips_set_tip(tooltips, toolbutton_zoom_fit, _("Zoom to fit all visible layers in the window"), NULL);
+    gtk_container_add(GTK_CONTAINER(button_toolbar), toolbutton_zoom_fit);
+
+    /* Turn these on later when we have icons for these buttons */
+    /*
+        separatortoolitem3 = (GtkWidget*) gtk_separator_tool_item_new ();
+        gtk_container_add (GTK_CONTAINER (button_toolbar), separatortoolitem3);
+
+        toolbutton_analyze = (GtkWidget*) gtk_tool_button_new_from_stock ("gtk-apply");
+        gtk_container_add (GTK_CONTAINER (button_toolbar), toolbutton_analyze);
+
+        toolbutton_validate = (GtkWidget*) gtk_tool_button_new_from_stock ("gtk-apply");
+        gtk_container_add (GTK_CONTAINER (button_toolbar), toolbutton_validate);
+
+        toolbutton_control = (GtkWidget*) gtk_tool_button_new_from_stock ("gtk-apply");
+        gtk_container_add (GTK_CONTAINER (button_toolbar), toolbutton_control);
+    */
+
+    separatortoolitem4 = (GtkWidget*)gtk_separator_tool_item_new();
+    gtk_container_add(GTK_CONTAINER(button_toolbar), separatortoolitem4);
+    toggletoolbutton_pointer = (GtkWidget*)gtk_toggle_tool_button_new();
+    pointerimage             = gtk_image_new_from_pixbuf(pointerpixbuf);
+    gtk_tool_button_set_icon_widget(GTK_TOOL_BUTTON(toggletoolbutton_pointer), pointerimage);
+    gtk_tooltips_set_tip(tooltips, toggletoolbutton_pointer, _("Select objects on the screen"), NULL);
+    gtk_container_add(GTK_CONTAINER(button_toolbar), toggletoolbutton_pointer);
+    toggletoolbutton_pan = (GtkWidget*)gtk_toggle_tool_button_new();
+    moveimage            = gtk_image_new_from_pixbuf(movepixbuf);
+    gtk_tool_button_set_icon_widget(GTK_TOOL_BUTTON(toggletoolbutton_pan), moveimage);
+    gtk_tooltips_set_tip(tooltips, toggletoolbutton_pan, _("Pan by left clicking and dragging"), NULL);
+    gtk_container_add(GTK_CONTAINER(button_toolbar), toggletoolbutton_pan);
+
+    toggletoolbutton_zoom = (GtkWidget*)gtk_toggle_tool_button_new();
+    zoomimage             = gtk_image_new_from_pixbuf(zoompixbuf);
+    gtk_tool_button_set_icon_widget(GTK_TOOL_BUTTON(toggletoolbutton_zoom), zoomimage);
+    gtk_tooltips_set_tip(tooltips, toggletoolbutton_zoom, _("Zoom by left clicking or dragging"), NULL);
+    gtk_container_add(GTK_CONTAINER(button_toolbar), toggletoolbutton_zoom);
+
+    toggletoolbutton_measure = (GtkWidget*)gtk_toggle_tool_button_new();
+    measureimage             = gtk_image_new_from_pixbuf(measurepixbuf);
+    gtk_tool_button_set_icon_widget(GTK_TOOL_BUTTON(toggletoolbutton_measure), measureimage);
+    gtk_tooltips_set_tip(tooltips, toggletoolbutton_measure, _("Measure distances on the screen"), NULL);
+    gtk_container_add(GTK_CONTAINER(button_toolbar), toggletoolbutton_measure);
+
+    hpaned1 = gtk_hpaned_new();
+    gtk_box_pack_start(GTK_BOX(vbox1), hpaned1, TRUE, TRUE, 0);
+    gtk_paned_set_position(GTK_PANED(hpaned1), 225);
+
+    sidepane_vbox = gtk_vbox_new(FALSE, 0);
+    gtk_widget_set_size_request(sidepane_vbox, 150, -1);
+
+    gtk_paned_pack1(GTK_PANED(hpaned1), sidepane_vbox, FALSE, FALSE);
+    gtk_container_set_border_width(GTK_CONTAINER(sidepane_vbox), 5);
+
+    sidepane_notebook = gtk_notebook_new();
+    gtk_widget_set_size_request(sidepane_notebook, 100, -1);
+    gtk_box_pack_start(GTK_BOX(sidepane_vbox), sidepane_notebook, TRUE, TRUE, 0);
+
+    vbox10 = gtk_vbox_new(FALSE, 3);
+    gtk_container_add(GTK_CONTAINER(sidepane_notebook), vbox10);
+    gtk_widget_set_size_request(vbox10, 82, -1);
+    gtk_container_set_border_width(GTK_CONTAINER(vbox10), 4);
+
+    hbox4 = gtk_hbox_new(FALSE, 0);
+    gtk_box_pack_start(GTK_BOX(vbox10), hbox4, FALSE, FALSE, 0);
+
+    render_combobox = gtk_combo_box_new_text();
+    gtk_box_pack_start(GTK_BOX(hbox4), render_combobox, TRUE, TRUE, 0);
+    gtk_tooltips_set_tip(tooltips, render_combobox, _("Rendering type"), NULL);
+
+    gtk_combo_box_append_text(GTK_COMBO_BOX(render_combobox), _("Fast"));
+    gtk_combo_box_append_text(GTK_COMBO_BOX(render_combobox), _("Fast, with XOR"));
+    gtk_combo_box_append_text(GTK_COMBO_BOX(render_combobox), _("Normal"));
+    gtk_combo_box_append_text(GTK_COMBO_BOX(render_combobox), _("High quality"));
+
+    if (screen.settings) {
+        g_settings_bind(screen.settings, "visual-rendering-type", render_combobox, "active", G_SETTINGS_BIND_DEFAULT);
+
+        /* Sync menu item render type */
+        screenRenderInfo.renderType = gtk_combo_box_get_active(GTK_COMBO_BOX(render_combobox));
+        if ((unsigned int)screenRenderInfo.renderType < GERBV_RENDER_TYPE_MAX) {
+            gtk_check_menu_item_set_active(screen.win.menu_view_render_group[screenRenderInfo.renderType], TRUE);
+        }
+    } else {
+        gtk_combo_box_set_active(GTK_COMBO_BOX(render_combobox), screenRenderInfo.renderType);
+    }
+
+    scrolledwindow1 = gtk_scrolled_window_new(NULL, NULL);
+    gtk_box_pack_start(GTK_BOX(vbox10), scrolledwindow1, TRUE, TRUE, 0);
+    gtk_container_set_border_width(GTK_CONTAINER(scrolledwindow1), 2);
+    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolledwindow1), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
+    gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scrolledwindow1), GTK_SHADOW_IN);
+
+    hbox1 = gtk_hbox_new(TRUE, 0);
+    gtk_box_pack_start(GTK_BOX(vbox10), hbox1, FALSE, FALSE, 0);
+
+    button4 = gtk_button_new();
+    gtk_box_pack_start(GTK_BOX(hbox1), button4, FALSE, TRUE, 0);
+
+    image8 = gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_BUTTON);
+    gtk_container_add(GTK_CONTAINER(button4), image8);
+    gtk_tooltips_set_tip(
+        tooltips, button4,
+        _("Open Gerbv project, Gerber, drill, "
+          "or pick&place files"),
+        NULL
+    );
+
+    button5 = gtk_button_new();
+    gtk_box_pack_start(GTK_BOX(hbox1), button5, FALSE, TRUE, 0);
+
+    image9 = gtk_image_new_from_stock(GTK_STOCK_GO_DOWN, GTK_ICON_SIZE_BUTTON);
+    gtk_container_add(GTK_CONTAINER(button5), image9);
+    gtk_tooltips_set_tip(tooltips, button5, _("Move the active layer one step down"), NULL);
+
+    button6 = gtk_button_new();
+    gtk_box_pack_start(GTK_BOX(hbox1), button6, FALSE, TRUE, 0);
+
+    image10 = gtk_image_new_from_stock(GTK_STOCK_GO_UP, GTK_ICON_SIZE_BUTTON);
+    gtk_container_add(GTK_CONTAINER(button6), image10);
+    gtk_tooltips_set_tip(tooltips, button6, _("Move the active layer one step up"), NULL);
+
+    button7 = gtk_button_new();
+    gtk_box_pack_start(GTK_BOX(hbox1), button7, FALSE, TRUE, 0);
+
+    image11 = gtk_image_new_from_stock(GTK_STOCK_REMOVE, GTK_ICON_SIZE_BUTTON);
+    gtk_container_add(GTK_CONTAINER(button7), image11);
+    gtk_tooltips_set_tip(tooltips, button7, _("Remove the active layer"), NULL);
+
+    Layer_label = gtk_label_new(_("Layers"));
+    gtk_notebook_set_tab_label(
+        GTK_NOTEBOOK(sidepane_notebook), gtk_notebook_get_nth_page(GTK_NOTEBOOK(sidepane_notebook), 0), Layer_label
+    );
+
+    vbox11 = gtk_vbox_new(FALSE, 2);
+    gtk_container_add(GTK_CONTAINER(sidepane_notebook), vbox11);
+    gtk_container_set_border_width(GTK_CONTAINER(vbox11), 3);
+
+    messages_scrolledwindow = gtk_scrolled_window_new(NULL, NULL);
+    gtk_box_pack_start(GTK_BOX(vbox11), messages_scrolledwindow, TRUE, TRUE, 0);
+    gtk_scrolled_window_set_policy(
+        GTK_SCROLLED_WINDOW(messages_scrolledwindow), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC
+    );
+
+    message_textview = gtk_text_view_new();
+    gtk_container_add(GTK_CONTAINER(messages_scrolledwindow), message_textview);
+    gtk_text_view_set_editable(GTK_TEXT_VIEW(message_textview), FALSE);
+    gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(message_textview), GTK_WRAP_WORD);
+    gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(message_textview), FALSE);
+
+    clear_messages_button = gtk_button_new_from_stock(GTK_STOCK_CLEAR);
+    gtk_tooltips_set_tip(tooltips, clear_messages_button, _("Clear all messages and accumulated sum"), NULL);
+    gtk_box_pack_start(GTK_BOX(vbox11), clear_messages_button, FALSE, FALSE, 0);
+
+    Message_label = gtk_label_new(_("Messages"));
+    gtk_notebook_set_tab_label(
+        GTK_NOTEBOOK(sidepane_notebook), gtk_notebook_get_nth_page(GTK_NOTEBOOK(sidepane_notebook), 1), Message_label
+    );
+
+    vbox2 = gtk_vbox_new(FALSE, 4);
+    gtk_paned_pack2(GTK_PANED(hpaned1), vbox2, TRUE, FALSE);
+    gtk_container_set_border_width(GTK_CONTAINER(vbox2), 4);
+
+    main_view_table = gtk_table_new(3, 3, FALSE);
+    gtk_box_pack_start(GTK_BOX(vbox2), main_view_table, TRUE, TRUE, 0);
+
+    hRuler = gtk_hruler_new();
+    gtk_table_attach(
+        GTK_TABLE(main_view_table), hRuler, 1, 2, 0, 1, (GtkAttachOptions)(GTK_EXPAND | GTK_FILL),
+        (GtkAttachOptions)(GTK_FILL), 0, 0
+    );
+    gtk_ruler_set_range(GTK_RULER(hRuler), 0, 100, 8.56051, 1000);
+
+    vRuler = gtk_vruler_new();
+    gtk_table_attach(
+        GTK_TABLE(main_view_table), vRuler, 0, 1, 1, 2, (GtkAttachOptions)(GTK_FILL),
+        (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), 0, 0
+    );
+    gtk_ruler_set_range(GTK_RULER(vRuler), 0, 100, 8.37341, 1000);
+
+    drawingarea = gtk_drawing_area_new();
+    gtk_table_attach(
+        GTK_TABLE(main_view_table), drawingarea, 1, 2, 1, 2, (GtkAttachOptions)(GTK_FILL),
+        (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), 0, 0
+    );
+
+    hAdjustment = (GtkWidget*)gtk_adjustment_new(0.0, -1000.0, 1000.0, 1000.0, 1000.0, 500.0);
+    vAdjustment = (GtkWidget*)gtk_adjustment_new(0.0, -1000.0, 1000.0, 1000.0, 1000.0, 500.0);
+
+    hScrollbar = gtk_hscrollbar_new(GTK_ADJUSTMENT(hAdjustment));
+    gtk_table_attach(
+        GTK_TABLE(main_view_table), hScrollbar, 1, 2, 2, 3, (GtkAttachOptions)(GTK_FILL), (GtkAttachOptions)(GTK_FILL),
+        0, 0
+    );
+
+    vScrollbar = gtk_vscrollbar_new(GTK_ADJUSTMENT(vAdjustment));
+    gtk_table_attach(
+        GTK_TABLE(main_view_table), vScrollbar, 2, 3, 1, 2, (GtkAttachOptions)(GTK_FILL), (GtkAttachOptions)(GTK_FILL),
+        0, 0
+    );
+
+    hbox5 = gtk_hbox_new(FALSE, 10);
+    gtk_box_pack_start(GTK_BOX(vbox2), hbox5, FALSE, FALSE, 0);
+
+    statusbar_label_left = gtk_label_new("");
+    gtk_box_pack_start(GTK_BOX(hbox5), statusbar_label_left, FALSE, FALSE, 0);
+    gtk_label_set_justify(GTK_LABEL(statusbar_label_left), GTK_JUSTIFY_CENTER);
+
+    statusUnitComboBox = gtk_combo_box_new_text();
+    gtk_box_pack_start(GTK_BOX(hbox5), statusUnitComboBox, FALSE, FALSE, 0);
+    gtk_combo_box_append_text(GTK_COMBO_BOX(statusUnitComboBox), _("mil"));
+    gtk_combo_box_append_text(GTK_COMBO_BOX(statusUnitComboBox), _("mm"));
+    gtk_combo_box_append_text(GTK_COMBO_BOX(statusUnitComboBox), _("in"));
+    screen.win.statusUnitComboBox = statusUnitComboBox;
+
+    /* 1. Set default unit */
+    int screen_unit_orig = screen.unit;
+    /* Trigger change */
+
+    gtk_combo_box_set_active(GTK_COMBO_BOX(statusUnitComboBox), screen_unit_orig);
+    /* Update unit item in menu */
+    callbacks_statusbar_unit_combo_box_changed(GTK_COMBO_BOX(statusUnitComboBox), GINT_TO_POINTER(TRUE));
+
+    /* 2. Try to set unit from stored settings */
+    if (screen.settings) {
+        g_settings_bind(screen.settings, "visual-unit", statusUnitComboBox, "active", G_SETTINGS_BIND_DEFAULT);
+        /* Update unit item in menu */
+        callbacks_statusbar_unit_combo_box_changed(GTK_COMBO_BOX(statusUnitComboBox), GINT_TO_POINTER(TRUE));
+    }
+
+    /* 3. Override unit from cmdline */
+    if (screen.unit_is_from_cmdline) {
+        gtk_combo_box_set_active(GTK_COMBO_BOX(statusUnitComboBox), screen_unit_orig);
+        /* Update unit item in menu */
+        callbacks_statusbar_unit_combo_box_changed(GTK_COMBO_BOX(statusUnitComboBox), GINT_TO_POINTER(TRUE));
+    }
 
-	statusbar_label_right = gtk_label_new ("");
-	gtk_box_pack_start (GTK_BOX (hbox5), statusbar_label_right, TRUE, TRUE, 0);
-	gtk_label_set_ellipsize (GTK_LABEL (statusbar_label_right), PANGO_ELLIPSIZE_END);
-	gtk_misc_set_alignment (GTK_MISC (statusbar_label_right), 0, 0.5);
+    statusbar_label_right = gtk_label_new("");
+    gtk_box_pack_start(GTK_BOX(hbox5), statusbar_label_right, TRUE, TRUE, 0);
+    gtk_label_set_ellipsize(GTK_LABEL(statusbar_label_right), PANGO_ELLIPSIZE_END);
+    gtk_misc_set_alignment(GTK_MISC(statusbar_label_right), 0, 0.5);
 
     /*
      *  Connect signals to widgets
      */
 
-	/* --- File menu --- */
-	g_signal_connect ((gpointer) new_project, "activate",
-	                  G_CALLBACK (callbacks_new_project_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) open, "activate",
-					  G_CALLBACK (callbacks_open_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) revert, "activate",
-	                  G_CALLBACK (callbacks_revert_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) save_layer, "activate",
-	                  G_CALLBACK (callbacks_save_layer_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) save_as_layer, "activate",
-	                  G_CALLBACK (callbacks_generic_save_activate),
-	                  (gpointer) CALLBACKS_SAVE_LAYER_AS);
-	g_signal_connect ((gpointer) save, "activate",
-	                  G_CALLBACK (callbacks_save_project_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) save_as, "activate",
-	                  G_CALLBACK (callbacks_generic_save_activate),
-	                  (gpointer) CALLBACKS_SAVE_PROJECT_AS);
-	g_signal_connect ((gpointer) png, "activate",
-	                  G_CALLBACK (callbacks_generic_save_activate),
-	                 (gpointer)  CALLBACKS_SAVE_FILE_PNG);
-
-	g_signal_connect ((gpointer) pdf, "activate",
-	                 G_CALLBACK (callbacks_generic_save_activate),
-	                  (gpointer) CALLBACKS_SAVE_FILE_PDF);
-	g_signal_connect ((gpointer) svg, "activate",
-	                  G_CALLBACK (callbacks_generic_save_activate),
-	                  (gpointer) CALLBACKS_SAVE_FILE_SVG);
-	g_signal_connect ((gpointer) postscript, "activate",
-	                  G_CALLBACK (callbacks_generic_save_activate),
-	                  (gpointer) CALLBACKS_SAVE_FILE_PS);
-	g_signal_connect ((gpointer) geda_pcb, "activate",
-	                  G_CALLBACK (callbacks_generic_save_activate),
-	                  (gpointer) CALLBACKS_SAVE_FILE_GEDA_PCB);
+    /* --- File menu --- */
+    g_signal_connect((gpointer)new_project, "activate", G_CALLBACK(callbacks_new_project_activate), NULL);
+    g_signal_connect((gpointer)open, "activate", G_CALLBACK(callbacks_open_activate), NULL);
+    g_signal_connect((gpointer)revert, "activate", G_CALLBACK(callbacks_revert_activate), NULL);
+    g_signal_connect((gpointer)save_layer, "activate", G_CALLBACK(callbacks_save_layer_activate), NULL);
+    g_signal_connect(
+        (gpointer)save_as_layer, "activate", G_CALLBACK(callbacks_generic_save_activate),
+        (gpointer)CALLBACKS_SAVE_LAYER_AS
+    );
+    g_signal_connect((gpointer)save, "activate", G_CALLBACK(callbacks_save_project_activate), NULL);
+    g_signal_connect(
+        (gpointer)save_as, "activate", G_CALLBACK(callbacks_generic_save_activate), (gpointer)CALLBACKS_SAVE_PROJECT_AS
+    );
+    g_signal_connect(
+        (gpointer)png, "activate", G_CALLBACK(callbacks_generic_save_activate), (gpointer)CALLBACKS_SAVE_FILE_PNG
+    );
+
+    g_signal_connect(
+        (gpointer)pdf, "activate", G_CALLBACK(callbacks_generic_save_activate), (gpointer)CALLBACKS_SAVE_FILE_PDF
+    );
+    g_signal_connect(
+        (gpointer)svg, "activate", G_CALLBACK(callbacks_generic_save_activate), (gpointer)CALLBACKS_SAVE_FILE_SVG
+    );
+    g_signal_connect(
+        (gpointer)postscript, "activate", G_CALLBACK(callbacks_generic_save_activate), (gpointer)CALLBACKS_SAVE_FILE_PS
+    );
+    g_signal_connect(
+        (gpointer)geda_pcb, "activate", G_CALLBACK(callbacks_generic_save_activate),
+        (gpointer)CALLBACKS_SAVE_FILE_GEDA_PCB
+    );
 #if HAVE_LIBDXFLIB
-	g_signal_connect ((gpointer) dxf, "activate",
-	                  G_CALLBACK (callbacks_generic_save_activate),
-	                  (gpointer) CALLBACKS_SAVE_FILE_DXF);
+    g_signal_connect(
+        (gpointer)dxf, "activate", G_CALLBACK(callbacks_generic_save_activate), (gpointer)CALLBACKS_SAVE_FILE_DXF
+    );
 #endif
-	g_signal_connect ((gpointer) rs274x, "activate",
-	                  G_CALLBACK (callbacks_generic_save_activate),
-	                  (gpointer) CALLBACKS_SAVE_FILE_RS274X);
-	g_signal_connect ((gpointer) drill, "activate",
-	                  G_CALLBACK (callbacks_generic_save_activate),
-	                  (gpointer) CALLBACKS_SAVE_FILE_DRILL);
-	g_signal_connect ((gpointer) idrill, "activate",
-	                  G_CALLBACK (callbacks_generic_save_activate),
-	                  (gpointer) CALLBACKS_SAVE_FILE_IDRILL);
-	g_signal_connect ((gpointer) rs274xm, "activate",
-	                  G_CALLBACK (callbacks_generic_save_activate),
-	                  (gpointer) CALLBACKS_SAVE_FILE_RS274XM);
-	g_signal_connect ((gpointer) drillm, "activate",
-	                  G_CALLBACK (callbacks_generic_save_activate),
-	                  (gpointer) CALLBACKS_SAVE_FILE_DRILLM);
-
-#if GTK_CHECK_VERSION(2,10,0)
-	g_signal_connect ((gpointer) print, "activate",
-	                  G_CALLBACK (callbacks_print_activate),
-	                  NULL);
+    g_signal_connect(
+        (gpointer)rs274x, "activate", G_CALLBACK(callbacks_generic_save_activate), (gpointer)CALLBACKS_SAVE_FILE_RS274X
+    );
+    g_signal_connect(
+        (gpointer)drill, "activate", G_CALLBACK(callbacks_generic_save_activate), (gpointer)CALLBACKS_SAVE_FILE_DRILL
+    );
+    g_signal_connect(
+        (gpointer)idrill, "activate", G_CALLBACK(callbacks_generic_save_activate), (gpointer)CALLBACKS_SAVE_FILE_IDRILL
+    );
+    g_signal_connect(
+        (gpointer)rs274xm, "activate", G_CALLBACK(callbacks_generic_save_activate),
+        (gpointer)CALLBACKS_SAVE_FILE_RS274XM
+    );
+    g_signal_connect(
+        (gpointer)drillm, "activate", G_CALLBACK(callbacks_generic_save_activate), (gpointer)CALLBACKS_SAVE_FILE_DRILLM
+    );
+
+#if GTK_CHECK_VERSION(2, 10, 0)
+    g_signal_connect((gpointer)print, "activate", G_CALLBACK(callbacks_print_activate), NULL);
 #endif
-	g_signal_connect ((gpointer) quit, "activate",
-	                  G_CALLBACK (callbacks_quit_activate),
-	                  NULL);
-
-	/* --- Edit menu --- */
-	g_signal_connect ((gpointer) delete_selected, "activate",
-	                  G_CALLBACK (callbacks_delete_objects_clicked),
-	                  NULL);
-	g_signal_connect ((gpointer) properties_selected, "activate",
-	                  G_CALLBACK (callbacks_display_object_properties_clicked),
-	                  NULL);
-	g_signal_connect ((gpointer) screen.win.curEditAlingItem[0], "activate",
-			G_CALLBACK (callbacks_align_files_from_sel_clicked),
-			GINT_TO_POINTER(0));
-	g_signal_connect ((gpointer) screen.win.curEditAlingItem[1], "activate",
-			G_CALLBACK (callbacks_align_files_from_sel_clicked),
-			GINT_TO_POINTER(1));
-
-	/* --- View menu --- */
-	g_signal_connect ((gpointer) view_fullscreen, "activate",
-	                  G_CALLBACK (callbacks_fullscreen_toggled),
-	                  GINT_TO_POINTER(0));
-	g_signal_connect ((gpointer) show_toolbar, "toggled",
-	                  G_CALLBACK (callbacks_show_toolbar_toggled),
-	                  toolbar_hbox);
-	g_signal_connect ((gpointer) show_sidepane, "toggled",
-	                  G_CALLBACK (callbacks_show_sidepane_toggled),
-	                  sidepane_vbox);
-	g_signal_connect ((gpointer) show_selection_on_invisible, "toggled",
-	                  G_CALLBACK (callbacks_show_selection_on_invisible),
-	                  NULL);
-	g_signal_connect ((gpointer) show_cross_on_drill_holes, "toggled",
-	                  G_CALLBACK (callbacks_show_cross_on_drill_holes),
-	                  NULL);
-	g_signal_connect ((gpointer) toggle_layer_visibility_item1, "activate",
-	                  G_CALLBACK (callbacks_toggle_layer_visibility_activate),
-	                  GINT_TO_POINTER(0));
-	g_signal_connect ((gpointer) toggle_layer_visibility_item2, "activate",
-	                  G_CALLBACK (callbacks_toggle_layer_visibility_activate),
-	                  GINT_TO_POINTER(1));
-	g_signal_connect ((gpointer) toggle_layer_visibility_item3, "activate",
-	                  G_CALLBACK (callbacks_toggle_layer_visibility_activate),
-	                  GINT_TO_POINTER(2));
-	g_signal_connect ((gpointer) toggle_layer_visibility_item4, "activate",
-	                  G_CALLBACK (callbacks_toggle_layer_visibility_activate),
-	                  GINT_TO_POINTER(3));
-	g_signal_connect ((gpointer) toggle_layer_visibility_item5, "activate",
-	                  G_CALLBACK (callbacks_toggle_layer_visibility_activate),
-	                  GINT_TO_POINTER(4));
-	g_signal_connect ((gpointer) toggle_layer_visibility_item6, "activate",
-	                  G_CALLBACK (callbacks_toggle_layer_visibility_activate),
-	                  GINT_TO_POINTER(5));
-	g_signal_connect ((gpointer) toggle_layer_visibility_item7, "activate",
-	                  G_CALLBACK (callbacks_toggle_layer_visibility_activate),
-	                  GINT_TO_POINTER(6));
-	g_signal_connect ((gpointer) toggle_layer_visibility_item8, "activate",
-	                  G_CALLBACK (callbacks_toggle_layer_visibility_activate),
-	                  GINT_TO_POINTER(7));
-	g_signal_connect ((gpointer) toggle_layer_visibility_item9, "activate",
-	                  G_CALLBACK (callbacks_toggle_layer_visibility_activate),
-	                  GINT_TO_POINTER(8));
-	g_signal_connect ((gpointer) toggle_layer_visibility_item10, "activate",
-	                  G_CALLBACK (callbacks_toggle_layer_visibility_activate),
-	                  GINT_TO_POINTER(9));
-	g_signal_connect ((gpointer) zoom_in, "activate",
-	                  G_CALLBACK (callbacks_zoom_in_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) zoom_out, "activate",
-	                  G_CALLBACK (callbacks_zoom_out_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) fit_to_window, "activate",
-	                  G_CALLBACK (callbacks_fit_to_window_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) backgroundColor, "activate",
-	                  G_CALLBACK (callbacks_change_background_color_clicked),
-	                  NULL);
-	g_signal_connect ((gpointer) unit_mil, "activate",
-	                  G_CALLBACK (callbacks_viewmenu_units_changed),
-	                  GINT_TO_POINTER(GERBV_MILS));
-	g_signal_connect ((gpointer) unit_mm, "activate",
-	                  G_CALLBACK (callbacks_viewmenu_units_changed),
-	                  GINT_TO_POINTER(GERBV_MMS));
-	g_signal_connect ((gpointer) unit_in, "activate",
-	                  G_CALLBACK (callbacks_viewmenu_units_changed),
-	                  GINT_TO_POINTER(GERBV_INS));
-
-	/* --- Current Layer menu --- */
-	g_signal_connect ((gpointer) layer_visibility, "activate",
-			G_CALLBACK (callbacks_toggle_layer_visibility_activate),
-			GINT_TO_POINTER (LAYER_SELECTED));
-	g_signal_connect ((gpointer) layer_visibility_all_on, "activate",
-			G_CALLBACK (callbacks_toggle_layer_visibility_activate),
-			GINT_TO_POINTER (LAYER_ALL_ON));
-	g_signal_connect ((gpointer) layer_visibility_all_off, "activate",
-			G_CALLBACK (callbacks_toggle_layer_visibility_activate),
-			GINT_TO_POINTER (LAYER_ALL_OFF));
-	g_signal_connect ((gpointer) layer_invert, "activate", G_CALLBACK (callbacks_invert_layer_clicked), NULL);
-	g_signal_connect ((gpointer) layer_color, "activate", G_CALLBACK (callbacks_change_layer_color_clicked), NULL);
-	g_signal_connect ((gpointer) layer_reload, "activate", G_CALLBACK (callbacks_reload_layer_clicked), NULL);
-	g_signal_connect ((gpointer) layer_edit, "activate", G_CALLBACK (callbacks_change_layer_edit_clicked), NULL);
-	g_signal_connect ((gpointer) layer_format, "activate", G_CALLBACK (callbacks_change_layer_format_clicked), NULL);
-	g_signal_connect ((gpointer) layer_remove, "activate", G_CALLBACK (callbacks_remove_layer_button_clicked), NULL);
-	g_signal_connect ((gpointer) layer_up, "activate", G_CALLBACK (callbacks_move_layer_up_menu_activate), NULL);
-	g_signal_connect ((gpointer) layer_down, "activate", G_CALLBACK (callbacks_move_layer_down_menu_activate), NULL);
-
-	/* --- Analyze menu --- */
-	g_signal_connect ((gpointer) analyze_active_gerbers, "activate",
-	                  G_CALLBACK (callbacks_analyze_active_gerbers_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) analyze_active_drill, "activate",
-	                  G_CALLBACK (callbacks_analyze_active_drill_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) analyze_benchmark, "activate",
-	                  G_CALLBACK (callbacks_benchmark_clicked),
-	                  NULL);
-
-
-	/* Wait for 2.1
-	g_signal_connect ((gpointer) control_gerber_options, "activate",
-	                  G_CALLBACK (callbacks_control_gerber_options_activate),
-	                  NULL);
-	*/
-
-	/* --- Tools menu --- */
-	g_signal_connect ((gpointer) pointer_tool, "activate",
-	                  G_CALLBACK (callbacks_change_tool), (gpointer) 0);
-	g_signal_connect ((gpointer) pan_tool, "activate",
-	                  G_CALLBACK (callbacks_change_tool), (gpointer) 1);
-	g_signal_connect ((gpointer) zoom_tool, "activate",
-	                  G_CALLBACK (callbacks_change_tool), (gpointer) 2);
-	g_signal_connect ((gpointer) measure_tool, "activate",
-	                  G_CALLBACK (callbacks_change_tool), (gpointer) 3);
-
-	/* --- Help menu --- */
-	/*
-	g_signal_connect ((gpointer) online_manual, "activate",
-	                  G_CALLBACK (callbacks_online_manual_activate),
-	                  NULL);
-	*/
-	g_signal_connect ((gpointer) about, "activate",
-	                  G_CALLBACK (callbacks_about_activate),
-	                  NULL);
-
-	g_signal_connect ((gpointer) bugs_menuitem, "activate",
-	                  G_CALLBACK (callbacks_bugs_activate),
-	                  NULL);
-
-	/* End of Glade generated code */
-	g_signal_connect ((gpointer) toolbutton_new, "clicked",
-	                  G_CALLBACK (callbacks_new_project_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) toolbutton_save, "clicked",
-	                  G_CALLBACK (callbacks_save_project_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) toolbutton_open, "clicked",
-					  G_CALLBACK (callbacks_open_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) toolbutton_revert, "clicked",
-	                  G_CALLBACK (callbacks_revert_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) clear_messages_button, "clicked",
-	                  G_CALLBACK (callbacks_clear_messages_button_clicked),
-	                  NULL);
-#if GTK_CHECK_VERSION(2,10,0)
-	g_signal_connect ((gpointer) toolbutton_print, "clicked",
-	                  G_CALLBACK (callbacks_print_activate),
-	                  NULL);
+    g_signal_connect((gpointer)quit, "activate", G_CALLBACK(callbacks_quit_activate), NULL);
+
+    /* --- Edit menu --- */
+    g_signal_connect((gpointer)delete_selected, "activate", G_CALLBACK(callbacks_delete_objects_clicked), NULL);
+    g_signal_connect(
+        (gpointer)properties_selected, "activate", G_CALLBACK(callbacks_display_object_properties_clicked), NULL
+    );
+    g_signal_connect(
+        (gpointer)screen.win.curEditAlingItem[0], "activate", G_CALLBACK(callbacks_align_files_from_sel_clicked),
+        GINT_TO_POINTER(0)
+    );
+    g_signal_connect(
+        (gpointer)screen.win.curEditAlingItem[1], "activate", G_CALLBACK(callbacks_align_files_from_sel_clicked),
+        GINT_TO_POINTER(1)
+    );
+
+    /* --- View menu --- */
+    g_signal_connect(
+        (gpointer)view_fullscreen, "activate", G_CALLBACK(callbacks_fullscreen_toggled), GINT_TO_POINTER(0)
+    );
+    g_signal_connect((gpointer)show_toolbar, "toggled", G_CALLBACK(callbacks_show_toolbar_toggled), toolbar_hbox);
+    g_signal_connect((gpointer)show_sidepane, "toggled", G_CALLBACK(callbacks_show_sidepane_toggled), sidepane_vbox);
+    g_signal_connect(
+        (gpointer)show_selection_on_invisible, "toggled", G_CALLBACK(callbacks_show_selection_on_invisible), NULL
+    );
+    g_signal_connect(
+        (gpointer)show_cross_on_drill_holes, "toggled", G_CALLBACK(callbacks_show_cross_on_drill_holes), NULL
+    );
+    g_signal_connect(
+        (gpointer)toggle_layer_visibility_item1, "activate", G_CALLBACK(callbacks_toggle_layer_visibility_activate),
+        GINT_TO_POINTER(0)
+    );
+    g_signal_connect(
+        (gpointer)toggle_layer_visibility_item2, "activate", G_CALLBACK(callbacks_toggle_layer_visibility_activate),
+        GINT_TO_POINTER(1)
+    );
+    g_signal_connect(
+        (gpointer)toggle_layer_visibility_item3, "activate", G_CALLBACK(callbacks_toggle_layer_visibility_activate),
+        GINT_TO_POINTER(2)
+    );
+    g_signal_connect(
+        (gpointer)toggle_layer_visibility_item4, "activate", G_CALLBACK(callbacks_toggle_layer_visibility_activate),
+        GINT_TO_POINTER(3)
+    );
+    g_signal_connect(
+        (gpointer)toggle_layer_visibility_item5, "activate", G_CALLBACK(callbacks_toggle_layer_visibility_activate),
+        GINT_TO_POINTER(4)
+    );
+    g_signal_connect(
+        (gpointer)toggle_layer_visibility_item6, "activate", G_CALLBACK(callbacks_toggle_layer_visibility_activate),
+        GINT_TO_POINTER(5)
+    );
+    g_signal_connect(
+        (gpointer)toggle_layer_visibility_item7, "activate", G_CALLBACK(callbacks_toggle_layer_visibility_activate),
+        GINT_TO_POINTER(6)
+    );
+    g_signal_connect(
+        (gpointer)toggle_layer_visibility_item8, "activate", G_CALLBACK(callbacks_toggle_layer_visibility_activate),
+        GINT_TO_POINTER(7)
+    );
+    g_signal_connect(
+        (gpointer)toggle_layer_visibility_item9, "activate", G_CALLBACK(callbacks_toggle_layer_visibility_activate),
+        GINT_TO_POINTER(8)
+    );
+    g_signal_connect(
+        (gpointer)toggle_layer_visibility_item10, "activate", G_CALLBACK(callbacks_toggle_layer_visibility_activate),
+        GINT_TO_POINTER(9)
+    );
+    g_signal_connect((gpointer)zoom_in, "activate", G_CALLBACK(callbacks_zoom_in_activate), NULL);
+    g_signal_connect((gpointer)zoom_out, "activate", G_CALLBACK(callbacks_zoom_out_activate), NULL);
+    g_signal_connect((gpointer)fit_to_window, "activate", G_CALLBACK(callbacks_fit_to_window_activate), NULL);
+    g_signal_connect(
+        (gpointer)backgroundColor, "activate", G_CALLBACK(callbacks_change_background_color_clicked), NULL
+    );
+    g_signal_connect(
+        (gpointer)unit_mil, "activate", G_CALLBACK(callbacks_viewmenu_units_changed), GINT_TO_POINTER(GERBV_MILS)
+    );
+    g_signal_connect(
+        (gpointer)unit_mm, "activate", G_CALLBACK(callbacks_viewmenu_units_changed), GINT_TO_POINTER(GERBV_MMS)
+    );
+    g_signal_connect(
+        (gpointer)unit_in, "activate", G_CALLBACK(callbacks_viewmenu_units_changed), GINT_TO_POINTER(GERBV_INS)
+    );
+
+    /* --- Current Layer menu --- */
+    g_signal_connect(
+        (gpointer)layer_visibility, "activate", G_CALLBACK(callbacks_toggle_layer_visibility_activate),
+        GINT_TO_POINTER(LAYER_SELECTED)
+    );
+    g_signal_connect(
+        (gpointer)layer_visibility_all_on, "activate", G_CALLBACK(callbacks_toggle_layer_visibility_activate),
+        GINT_TO_POINTER(LAYER_ALL_ON)
+    );
+    g_signal_connect(
+        (gpointer)layer_visibility_all_off, "activate", G_CALLBACK(callbacks_toggle_layer_visibility_activate),
+        GINT_TO_POINTER(LAYER_ALL_OFF)
+    );
+    g_signal_connect((gpointer)layer_invert, "activate", G_CALLBACK(callbacks_invert_layer_clicked), NULL);
+    g_signal_connect((gpointer)layer_color, "activate", G_CALLBACK(callbacks_change_layer_color_clicked), NULL);
+    g_signal_connect((gpointer)layer_reload, "activate", G_CALLBACK(callbacks_reload_layer_clicked), NULL);
+    g_signal_connect((gpointer)layer_edit, "activate", G_CALLBACK(callbacks_change_layer_edit_clicked), NULL);
+    g_signal_connect((gpointer)layer_format, "activate", G_CALLBACK(callbacks_change_layer_format_clicked), NULL);
+    g_signal_connect((gpointer)layer_remove, "activate", G_CALLBACK(callbacks_remove_layer_button_clicked), NULL);
+    g_signal_connect((gpointer)layer_up, "activate", G_CALLBACK(callbacks_move_layer_up_menu_activate), NULL);
+    g_signal_connect((gpointer)layer_down, "activate", G_CALLBACK(callbacks_move_layer_down_menu_activate), NULL);
+
+    /* --- Analyze menu --- */
+    g_signal_connect(
+        (gpointer)analyze_active_gerbers, "activate", G_CALLBACK(callbacks_analyze_active_gerbers_activate), NULL
+    );
+    g_signal_connect(
+        (gpointer)analyze_active_drill, "activate", G_CALLBACK(callbacks_analyze_active_drill_activate), NULL
+    );
+    g_signal_connect((gpointer)analyze_benchmark, "activate", G_CALLBACK(callbacks_benchmark_clicked), NULL);
+
+    /* Wait for 2.1
+    g_signal_connect ((gpointer) control_gerber_options, "activate",
+                      G_CALLBACK (callbacks_control_gerber_options_activate),
+                      NULL);
+    */
+
+    /* --- Tools menu --- */
+    g_signal_connect((gpointer)pointer_tool, "activate", G_CALLBACK(callbacks_change_tool), (gpointer)0);
+    g_signal_connect((gpointer)pan_tool, "activate", G_CALLBACK(callbacks_change_tool), (gpointer)1);
+    g_signal_connect((gpointer)zoom_tool, "activate", G_CALLBACK(callbacks_change_tool), (gpointer)2);
+    g_signal_connect((gpointer)measure_tool, "activate", G_CALLBACK(callbacks_change_tool), (gpointer)3);
+
+    /* --- Help menu --- */
+    /*
+    g_signal_connect ((gpointer) online_manual, "activate",
+                      G_CALLBACK (callbacks_online_manual_activate),
+                      NULL);
+    */
+    g_signal_connect((gpointer)about, "activate", G_CALLBACK(callbacks_about_activate), NULL);
+
+    g_signal_connect((gpointer)bugs_menuitem, "activate", G_CALLBACK(callbacks_bugs_activate), NULL);
+
+    /* End of Glade generated code */
+    g_signal_connect((gpointer)toolbutton_new, "clicked", G_CALLBACK(callbacks_new_project_activate), NULL);
+    g_signal_connect((gpointer)toolbutton_save, "clicked", G_CALLBACK(callbacks_save_project_activate), NULL);
+    g_signal_connect((gpointer)toolbutton_open, "clicked", G_CALLBACK(callbacks_open_activate), NULL);
+    g_signal_connect((gpointer)toolbutton_revert, "clicked", G_CALLBACK(callbacks_revert_activate), NULL);
+    g_signal_connect(
+        (gpointer)clear_messages_button, "clicked", G_CALLBACK(callbacks_clear_messages_button_clicked), NULL
+    );
+#if GTK_CHECK_VERSION(2, 10, 0)
+    g_signal_connect((gpointer)toolbutton_print, "clicked", G_CALLBACK(callbacks_print_activate), NULL);
 #endif
-	g_signal_connect ((gpointer) toolbutton_zoom_in, "clicked",
-	                  G_CALLBACK (callbacks_zoom_in_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) toolbutton_zoom_out, "clicked",
-	                  G_CALLBACK (callbacks_zoom_out_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) toolbutton_zoom_fit, "clicked",
-	                  G_CALLBACK (callbacks_fit_to_window_activate),
-	                  NULL);
-	g_signal_connect ((gpointer) toggletoolbutton_pointer, "clicked",
-	                  G_CALLBACK (callbacks_change_tool), (gpointer) 0);
-	g_signal_connect ((gpointer) toggletoolbutton_pan, "clicked",
-	                  G_CALLBACK (callbacks_change_tool), (gpointer) 1);
-	g_signal_connect ((gpointer) toggletoolbutton_zoom, "clicked",
-	                  G_CALLBACK (callbacks_change_tool), (gpointer) 2);
-	g_signal_connect ((gpointer) toggletoolbutton_measure, "clicked",
-	                  G_CALLBACK (callbacks_change_tool), (gpointer) 3);
-
-	g_signal_connect ((gpointer) statusUnitComboBox, "changed",
-	                  G_CALLBACK (callbacks_statusbar_unit_combo_box_changed),
-	                  NULL);
-	                  
-	g_signal_connect ((gpointer) button4, "clicked",
-	                  G_CALLBACK (callbacks_add_layer_button_clicked), NULL);
-	g_signal_connect ((gpointer) button7, "clicked",
-	                  G_CALLBACK (callbacks_remove_layer_button_clicked), NULL);
-	g_signal_connect ((gpointer) button5, "clicked",
-	                  G_CALLBACK (callbacks_move_layer_down_button_clicked), NULL);
-	g_signal_connect ((gpointer) button6, "clicked",
-	                  G_CALLBACK (callbacks_move_layer_up_button_clicked), NULL);
-
-	g_signal_connect ((gpointer) hAdjustment, "value-changed",
-	                  G_CALLBACK (callbacks_hadjustment_value_changed), NULL);
-	g_signal_connect ((gpointer) vAdjustment, "value-changed",
-	                  G_CALLBACK (callbacks_vadjustment_value_changed), NULL);
-	g_signal_connect ((gpointer) hScrollbar, "button-press-event",
-	                  G_CALLBACK (callbacks_scrollbar_button_pressed), NULL);                 
-	g_signal_connect ((gpointer) hScrollbar, "button-release-event",
-	                  G_CALLBACK (callbacks_scrollbar_button_released), NULL);
-	g_signal_connect ((gpointer) vScrollbar, "button-press-event",
-	                  G_CALLBACK (callbacks_scrollbar_button_pressed), NULL);
-	g_signal_connect ((gpointer) vScrollbar, "button-release-event",
-	                  G_CALLBACK (callbacks_scrollbar_button_released), NULL);
-
-	gtk_window_add_accel_group (GTK_WINDOW (mainWindow), accel_group);
-
-	GtkListStore *list_store;
-
-	list_store = gtk_list_store_new (4,	G_TYPE_BOOLEAN,
-		GDK_TYPE_PIXBUF, G_TYPE_STRING, G_TYPE_STRING);
-		
-	GtkWidget *tree;
-
-	tree = gtk_tree_view_new_with_model (GTK_TREE_MODEL (list_store));
-	GtkCellRenderer *renderer;
-	GtkTreeViewColumn *column;
-
-	renderer = gtk_cell_renderer_toggle_new ();
-	column = gtk_tree_view_column_new_with_attributes ("Visible",
-	                                                renderer,
-	                                                "active", 0,
-	                                                NULL);
-	gtk_tree_view_column_set_min_width ((GtkTreeViewColumn *)column, 25);
-	gtk_tree_view_append_column (GTK_TREE_VIEW (tree), column);
-
-	renderer = gtk_cell_renderer_pixbuf_new ();
-	column = gtk_tree_view_column_new_with_attributes ("Color",
-	                                                renderer,
-	                                                "pixbuf", 1, NULL);
-	gtk_tree_view_append_column (GTK_TREE_VIEW (tree), column);
-
-	renderer = gtk_cell_renderer_text_new ();
-	g_object_set (G_OBJECT (renderer), "foreground", "red", "xalign", 0.5,
-			"family", "Times", "size-points", 12.0, NULL);
-	column = gtk_tree_view_column_new_with_attributes ("Modified",
-	                                                renderer,
-	                                                "text", 3,
-	                                                NULL);
-	gtk_tree_view_append_column (GTK_TREE_VIEW (tree), column);
-	gtk_tree_view_column_set_min_width  ((GtkTreeViewColumn *)column,20);
-	
-	renderer = gtk_cell_renderer_text_new ();
-	column = gtk_tree_view_column_new_with_attributes ("Name",
-	                                                renderer,
-	                                                "markup", 2,
-	                                                NULL);
-	gtk_tree_view_append_column (GTK_TREE_VIEW (tree), column);
-
-	gtk_tree_view_set_headers_visible   ((GtkTreeView *)tree, FALSE);
-	gtk_signal_connect(GTK_OBJECT(tree), "key-press-event",
-		GTK_SIGNAL_FUNC(callbacks_layer_tree_key_press), NULL);
-	gtk_signal_connect(GTK_OBJECT(tree), "button-press-event",
-		GTK_SIGNAL_FUNC(callbacks_layer_tree_button_press), NULL);
-	gtk_container_add (GTK_CONTAINER (scrolledwindow1), tree);
-	
-	GtkTreeSelection *selection;
-	selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree));
-	gtk_tree_selection_set_mode (selection, GTK_SELECTION_BROWSE);
-	gtk_tree_view_set_enable_search (GTK_TREE_VIEW (tree), FALSE);
-	gtk_tree_view_set_reorderable (GTK_TREE_VIEW (tree), TRUE);
-
-	g_signal_connect (G_OBJECT(list_store), "row-inserted",
-			  G_CALLBACK (callbacks_layer_tree_row_inserted), NULL);
-	/* steal the focus to the tree to make sure none of the buttons are focused */
-	gtk_widget_grab_focus (tree);
-	/*
-	* Connect all events on drawing area 
-	*/    
-	gtk_signal_connect(GTK_OBJECT(drawingarea), "expose_event",
-		       GTK_SIGNAL_FUNC(callbacks_drawingarea_expose_event), NULL);
-	gtk_signal_connect(GTK_OBJECT(drawingarea),"configure_event",
-		       GTK_SIGNAL_FUNC(callbacks_drawingarea_configure_event), NULL);
-	gtk_signal_connect(GTK_OBJECT(drawingarea), "motion_notify_event",
-		       GTK_SIGNAL_FUNC(callbacks_drawingarea_motion_notify_event), NULL);
-	gtk_signal_connect(GTK_OBJECT(drawingarea), "button_press_event",
-		       GTK_SIGNAL_FUNC(callbacks_drawingarea_button_press_event), NULL);
-	gtk_signal_connect(GTK_OBJECT(drawingarea), "button_release_event",
-		       GTK_SIGNAL_FUNC(callbacks_drawingarea_button_release_event), NULL);
-	gtk_signal_connect_after(GTK_OBJECT(mainWindow), "key_press_event",
-		       GTK_SIGNAL_FUNC(callbacks_window_key_press_event), NULL);
-	gtk_signal_connect_after(GTK_OBJECT(mainWindow), "key_release_event",
-		       GTK_SIGNAL_FUNC(callbacks_window_key_release_event), NULL);
-	gtk_signal_connect_after(GTK_OBJECT(mainWindow), "scroll_event",
-		       GTK_SIGNAL_FUNC(callbacks_window_scroll_event), NULL);
-	gtk_signal_connect_after(GTK_OBJECT(mainWindow), "delete_event",
-		       GTK_SIGNAL_FUNC(callbacks_quit_activate), NULL);
-	
-	gtk_widget_set_events(drawingarea, GDK_EXPOSURE_MASK
-			  | GDK_LEAVE_NOTIFY_MASK
-			  | GDK_ENTER_NOTIFY_MASK
-			  | GDK_BUTTON_PRESS_MASK
-			  | GDK_BUTTON_RELEASE_MASK
-			  | GDK_KEY_PRESS_MASK
-			  | GDK_KEY_RELEASE_MASK
-			  | GDK_POINTER_MOTION_MASK
-			  | GDK_POINTER_MOTION_HINT_MASK
-			  | GDK_SCROLL_MASK
-			  );
-
-	/*
-	 * Setup some GTK+ defaults.
-	 * These should really be somewhere else.
-	 */
-	GdkColor zoom_outline_color = {0, 50000, 50000, 50000};
-	GdkColor dist_measure_color = {0, 60000, 30000, 65000};       
-	GdkColor selection_color = {0, 65000, 65000, 65000};
-	
-	screen.zoom_outline_color = zoom_outline_color;
-	screen.dist_measure_color = dist_measure_color;
-	screen.selection_color = selection_color;
-
-	screen.length_sum = 0;
-
-	screen.drawing_area = drawingarea;
-	screen.win.hAdjustment = hAdjustment;
-	screen.win.vAdjustment = vAdjustment;
-	screen.win.hRuler = hRuler;
-	screen.win.vRuler = vRuler;	
-	screen.win.sidepane_notebook = sidepane_notebook;
-	screen.win.sidepaneRenderComboBox = GTK_COMBO_BOX(render_combobox);
-	screen.win.toolButtonPointer = toggletoolbutton_pointer;
-	screen.win.toolButtonPan = toggletoolbutton_pan;
-	screen.win.toolButtonZoom = toggletoolbutton_zoom;
-	screen.win.toolButtonMeasure = toggletoolbutton_measure;
-
-	/* make sure tooltips show on gtk <2.12 systems */
-	gtk_tooltips_enable (tooltips);
-
-	gint width, height;
-
-	/* Good defaults according to Ales. Gives aspect ratio
-	 * of 1.3333... */
-	if (req_width != -1 && req_height != -1) {
-		width = req_width;
-		height = req_height;
-	} else {
-		GdkScreen *screen;
-		int nmonitors;
-
-		screen = gdk_screen_get_default();
-		nmonitors = gdk_screen_get_n_monitors(screen);
-
-		width = gdk_screen_get_width(screen) * 3/4 / nmonitors;
-		height = gdk_screen_get_height(screen) * 3/4 / nmonitors;
-	}
+    g_signal_connect((gpointer)toolbutton_zoom_in, "clicked", G_CALLBACK(callbacks_zoom_in_activate), NULL);
+    g_signal_connect((gpointer)toolbutton_zoom_out, "clicked", G_CALLBACK(callbacks_zoom_out_activate), NULL);
+    g_signal_connect((gpointer)toolbutton_zoom_fit, "clicked", G_CALLBACK(callbacks_fit_to_window_activate), NULL);
+    g_signal_connect((gpointer)toggletoolbutton_pointer, "clicked", G_CALLBACK(callbacks_change_tool), (gpointer)0);
+    g_signal_connect((gpointer)toggletoolbutton_pan, "clicked", G_CALLBACK(callbacks_change_tool), (gpointer)1);
+    g_signal_connect((gpointer)toggletoolbutton_zoom, "clicked", G_CALLBACK(callbacks_change_tool), (gpointer)2);
+    g_signal_connect((gpointer)toggletoolbutton_measure, "clicked", G_CALLBACK(callbacks_change_tool), (gpointer)3);
+
+    g_signal_connect(
+        (gpointer)statusUnitComboBox, "changed", G_CALLBACK(callbacks_statusbar_unit_combo_box_changed), NULL
+    );
+
+    g_signal_connect((gpointer)button4, "clicked", G_CALLBACK(callbacks_add_layer_button_clicked), NULL);
+    g_signal_connect((gpointer)button7, "clicked", G_CALLBACK(callbacks_remove_layer_button_clicked), NULL);
+    g_signal_connect((gpointer)button5, "clicked", G_CALLBACK(callbacks_move_layer_down_button_clicked), NULL);
+    g_signal_connect((gpointer)button6, "clicked", G_CALLBACK(callbacks_move_layer_up_button_clicked), NULL);
+
+    g_signal_connect((gpointer)hAdjustment, "value-changed", G_CALLBACK(callbacks_hadjustment_value_changed), NULL);
+    g_signal_connect((gpointer)vAdjustment, "value-changed", G_CALLBACK(callbacks_vadjustment_value_changed), NULL);
+    g_signal_connect((gpointer)hScrollbar, "button-press-event", G_CALLBACK(callbacks_scrollbar_button_pressed), NULL);
+    g_signal_connect(
+        (gpointer)hScrollbar, "button-release-event", G_CALLBACK(callbacks_scrollbar_button_released), NULL
+    );
+    g_signal_connect((gpointer)vScrollbar, "button-press-event", G_CALLBACK(callbacks_scrollbar_button_pressed), NULL);
+    g_signal_connect(
+        (gpointer)vScrollbar, "button-release-event", G_CALLBACK(callbacks_scrollbar_button_released), NULL
+    );
+
+    gtk_window_add_accel_group(GTK_WINDOW(mainWindow), accel_group);
+
+    GtkListStore* list_store;
+
+    list_store = gtk_list_store_new(4, G_TYPE_BOOLEAN, GDK_TYPE_PIXBUF, G_TYPE_STRING, G_TYPE_STRING);
+
+    GtkWidget* tree;
+
+    tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL(list_store));
+    GtkCellRenderer*   renderer;
+    GtkTreeViewColumn* column;
+
+    renderer = gtk_cell_renderer_toggle_new();
+    column   = gtk_tree_view_column_new_with_attributes("Visible", renderer, "active", 0, NULL);
+    gtk_tree_view_column_set_min_width((GtkTreeViewColumn*)column, 25);
+    gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column);
+
+    renderer = gtk_cell_renderer_pixbuf_new();
+    column   = gtk_tree_view_column_new_with_attributes("Color", renderer, "pixbuf", 1, NULL);
+    gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column);
+
+    renderer = gtk_cell_renderer_text_new();
+    g_object_set(G_OBJECT(renderer), "foreground", "red", "xalign", 0.5, "family", "Times", "size-points", 12.0, NULL);
+    column = gtk_tree_view_column_new_with_attributes("Modified", renderer, "text", 3, NULL);
+    gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column);
+    gtk_tree_view_column_set_min_width((GtkTreeViewColumn*)column, 20);
+
+    renderer = gtk_cell_renderer_text_new();
+    column   = gtk_tree_view_column_new_with_attributes("Name", renderer, "markup", 2, NULL);
+    gtk_tree_view_append_column(GTK_TREE_VIEW(tree), column);
+
+    gtk_tree_view_set_headers_visible((GtkTreeView*)tree, FALSE);
+    gtk_signal_connect(GTK_OBJECT(tree), "key-press-event", GTK_SIGNAL_FUNC(callbacks_layer_tree_key_press), NULL);
+    gtk_signal_connect(
+        GTK_OBJECT(tree), "button-press-event", GTK_SIGNAL_FUNC(callbacks_layer_tree_button_press), NULL
+    );
+    gtk_container_add(GTK_CONTAINER(scrolledwindow1), tree);
+
+    GtkTreeSelection* selection;
+    selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(tree));
+    gtk_tree_selection_set_mode(selection, GTK_SELECTION_BROWSE);
+    gtk_tree_view_set_enable_search(GTK_TREE_VIEW(tree), FALSE);
+    gtk_tree_view_set_reorderable(GTK_TREE_VIEW(tree), TRUE);
+
+    g_signal_connect(G_OBJECT(list_store), "row-inserted", G_CALLBACK(callbacks_layer_tree_row_inserted), NULL);
+    /* steal the focus to the tree to make sure none of the buttons are focused */
+    gtk_widget_grab_focus(tree);
+    /*
+     * Connect all events on drawing area
+     */
+    gtk_signal_connect(
+        GTK_OBJECT(drawingarea), "expose_event", GTK_SIGNAL_FUNC(callbacks_drawingarea_expose_event), NULL
+    );
+    gtk_signal_connect(
+        GTK_OBJECT(drawingarea), "configure_event", GTK_SIGNAL_FUNC(callbacks_drawingarea_configure_event), NULL
+    );
+    gtk_signal_connect(
+        GTK_OBJECT(drawingarea), "motion_notify_event", GTK_SIGNAL_FUNC(callbacks_drawingarea_motion_notify_event), NULL
+    );
+    gtk_signal_connect(
+        GTK_OBJECT(drawingarea), "button_press_event", GTK_SIGNAL_FUNC(callbacks_drawingarea_button_press_event), NULL
+    );
+    gtk_signal_connect(
+        GTK_OBJECT(drawingarea), "button_release_event", GTK_SIGNAL_FUNC(callbacks_drawingarea_button_release_event),
+        NULL
+    );
+    gtk_signal_connect_after(
+        GTK_OBJECT(mainWindow), "key_press_event", GTK_SIGNAL_FUNC(callbacks_window_key_press_event), NULL
+    );
+    gtk_signal_connect_after(
+        GTK_OBJECT(mainWindow), "key_release_event", GTK_SIGNAL_FUNC(callbacks_window_key_release_event), NULL
+    );
+    gtk_signal_connect_after(
+        GTK_OBJECT(mainWindow), "scroll_event", GTK_SIGNAL_FUNC(callbacks_window_scroll_event), NULL
+    );
+    gtk_signal_connect_after(GTK_OBJECT(mainWindow), "delete_event", GTK_SIGNAL_FUNC(callbacks_quit_activate), NULL);
+
+    gtk_widget_set_events(
+        drawingarea, GDK_EXPOSURE_MASK | GDK_LEAVE_NOTIFY_MASK | GDK_ENTER_NOTIFY_MASK | GDK_BUTTON_PRESS_MASK
+                         | GDK_BUTTON_RELEASE_MASK | GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_POINTER_MOTION_MASK
+                         | GDK_POINTER_MOTION_HINT_MASK | GDK_SCROLL_MASK
+    );
 
-	gtk_window_set_default_size(GTK_WINDOW(mainWindow), width, height);
-
-	/* Restore main window size */
-	if (screen.settings && req_width == -1 && req_height == -1) {
-		GVariant *var;
-		const gint32 *xy;
-		gsize num;
-		gboolean is_max;
-
-		var = g_settings_get_value (screen.settings, "window-size");
-		xy = g_variant_get_fixed_array (var, &num, sizeof (*xy));
-		if (num == 2)
-			gtk_window_set_default_size (GTK_WINDOW (mainWindow),
-					xy[0], xy[1]);
-		g_variant_unref (var);
-
-		var = g_settings_get_value (screen.settings, "window-position");
-		xy = g_variant_get_fixed_array (var, &num, sizeof (*xy));
-		if (num == 2)
-			gtk_window_move (GTK_WINDOW (mainWindow), xy[0], xy[1]);
-		g_variant_unref (var);
-
-		is_max = g_settings_get_boolean (
-				screen.settings, "window-maximized");
-		if (is_max)
-			gtk_window_maximize (GTK_WINDOW (mainWindow));
-	}
+    /*
+     * Setup some GTK+ defaults.
+     * These should really be somewhere else.
+     */
+    GdkColor zoom_outline_color = { 0, 50000, 50000, 50000 };
+    GdkColor dist_measure_color = { 0, 60000, 30000, 65000 };
+    GdkColor selection_color    = { 0, 65000, 65000, 65000 };
+
+    screen.zoom_outline_color = zoom_outline_color;
+    screen.dist_measure_color = dist_measure_color;
+    screen.selection_color    = selection_color;
+
+    screen.length_sum = 0;
+
+    screen.drawing_area               = drawingarea;
+    screen.win.hAdjustment            = hAdjustment;
+    screen.win.vAdjustment            = vAdjustment;
+    screen.win.hRuler                 = hRuler;
+    screen.win.vRuler                 = vRuler;
+    screen.win.sidepane_notebook      = sidepane_notebook;
+    screen.win.sidepaneRenderComboBox = GTK_COMBO_BOX(render_combobox);
+    screen.win.toolButtonPointer      = toggletoolbutton_pointer;
+    screen.win.toolButtonPan          = toggletoolbutton_pan;
+    screen.win.toolButtonZoom         = toggletoolbutton_zoom;
+    screen.win.toolButtonMeasure      = toggletoolbutton_measure;
+
+    /* make sure tooltips show on gtk <2.12 systems */
+    gtk_tooltips_enable(tooltips);
+
+    gint width, height;
+
+    /* Good defaults according to Ales. Gives aspect ratio
+     * of 1.3333... */
+    if (req_width != -1 && req_height != -1) {
+        width  = req_width;
+        height = req_height;
+    } else {
+        GdkScreen* screen;
+        int        nmonitors;
 
-	g_object_set (G_OBJECT(gtk_settings_get_default()),
-			"gtk-can-change-accels", TRUE, NULL);
-	interface_load_accels ();
+        screen    = gdk_screen_get_default();
+        nmonitors = gdk_screen_get_n_monitors(screen);
 
-	gtk_widget_show_all (mainWindow);
+        width  = gdk_screen_get_width(screen) * 3 / 4 / nmonitors;
+        height = gdk_screen_get_height(screen) * 3 / 4 / nmonitors;
+    }
 
-	screen.win.messageTextView = message_textview;
-	screen.win.statusMessageLeft = statusbar_label_left;
-	screen.win.statusMessageRight = statusbar_label_right;
-	screen.win.layerTree = tree;
-	screen.win.treeIsUpdating = FALSE;
+    gtk_window_set_default_size(GTK_WINDOW(mainWindow), width, height);
+
+    /* Restore main window size */
+    if (screen.settings && req_width == -1 && req_height == -1) {
+        GVariant*     var;
+        const gint32* xy;
+        gsize         num;
+        gboolean      is_max;
+
+        var = g_settings_get_value(screen.settings, "window-size");
+        xy  = g_variant_get_fixed_array(var, &num, sizeof(*xy));
+        if (num == 2)
+            gtk_window_set_default_size(GTK_WINDOW(mainWindow), xy[0], xy[1]);
+        g_variant_unref(var);
+
+        var = g_settings_get_value(screen.settings, "window-position");
+        xy  = g_variant_get_fixed_array(var, &num, sizeof(*xy));
+        if (num == 2)
+            gtk_window_move(GTK_WINDOW(mainWindow), xy[0], xy[1]);
+        g_variant_unref(var);
+
+        is_max = g_settings_get_boolean(screen.settings, "window-maximized");
+        if (is_max)
+            gtk_window_maximize(GTK_WINDOW(mainWindow));
+    }
 
-	/* Request label largest width: negative mils coords require largest space */
-	utf8_snprintf (str_coord, MAX_COORDLEN, _(gerbv_coords_pattern_mils_str),
-		COORD2MILS (-screenRenderInfo.displayWidth/2.0/GERBV_SCALE_MIN),
-		COORD2MILS (-screenRenderInfo.displayHeight/2.0/GERBV_SCALE_MIN));
+    g_object_set(G_OBJECT(gtk_settings_get_default()), "gtk-can-change-accels", TRUE, NULL);
+    interface_load_accels();
 
-	request_label_max_size_by_text (screen.win.statusMessageLeft, str_coord);
+    gtk_widget_show_all(mainWindow);
 
-	callbacks_change_tool (NULL, (gpointer) 0);
-	rename_main_window("",mainWindow);
+    screen.win.messageTextView    = message_textview;
+    screen.win.statusMessageLeft  = statusbar_label_left;
+    screen.win.statusMessageRight = statusbar_label_right;
+    screen.win.layerTree          = tree;
+    screen.win.treeIsUpdating     = FALSE;
 
-	set_window_icon (mainWindow);
-	callbacks_update_layer_tree ();
+    /* Request label largest width: negative mils coords require largest space */
+    utf8_snprintf(
+        str_coord, MAX_COORDLEN, _(gerbv_coords_pattern_mils_str),
+        COORD2MILS(-screenRenderInfo.displayWidth / 2.0 / GERBV_SCALE_MIN),
+        COORD2MILS(-screenRenderInfo.displayHeight / 2.0 / GERBV_SCALE_MIN)
+    );
 
-	/* Set GTK error log handler */
-	g_log_set_handler (NULL,
-		G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION | G_LOG_LEVEL_MASK,
-		callbacks_handle_log_messages, NULL);
+    request_label_max_size_by_text(screen.win.statusMessageLeft, str_coord);
 
-	/* Output temporary stored log messages */
-	extern GArray *log_array_tmp;
-	struct log_struct log_item;
+    callbacks_change_tool(NULL, (gpointer)0);
+    rename_main_window("", mainWindow);
 
-	for (guint i = 0; i < log_array_tmp->len; i++) {
-		log_item = g_array_index (log_array_tmp, struct log_struct, i);
-		callbacks_handle_log_messages (log_item.domain, log_item.level,
-				log_item.message, NULL);
-		g_free(log_item.domain);
-		g_free(log_item.message);
-	}
-	g_array_free (log_array_tmp, TRUE);
-
-	/* connect this signals as late as possible to avoid triggering them before
-	   the gui is drawn */
-	g_signal_connect ((gpointer) render_fast, "activate",
-	                  G_CALLBACK (callbacks_viewmenu_rendertype_changed),
-	                  GINT_TO_POINTER(GERBV_RENDER_TYPE_GDK));
-	g_signal_connect ((gpointer) render_fast_xor, "activate",
-	                  G_CALLBACK (callbacks_viewmenu_rendertype_changed),
-	                  GINT_TO_POINTER(GERBV_RENDER_TYPE_GDK_XOR));
-	g_signal_connect ((gpointer) render_normal, "activate",
-	                  G_CALLBACK (callbacks_viewmenu_rendertype_changed),
-	                  GINT_TO_POINTER(GERBV_RENDER_TYPE_CAIRO_NORMAL));
-	g_signal_connect ((gpointer) render_hq, "activate",
-	                  G_CALLBACK (callbacks_viewmenu_rendertype_changed),
-	                  GINT_TO_POINTER(GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY));
-	g_signal_connect ((gpointer) render_combobox, "changed",
-	                  G_CALLBACK (callbacks_sidepane_render_type_combo_box_changed),
-	                  NULL);
-	gtk_main();
-	interface_save_accels ();
+    set_window_icon(mainWindow);
+    callbacks_update_layer_tree();
+
+    /* Set GTK error log handler */
+    g_log_set_handler(
+        NULL, G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION | G_LOG_LEVEL_MASK, callbacks_handle_log_messages, NULL
+    );
+
+    /* Output temporary stored log messages */
+    extern GArray*    log_array_tmp;
+    struct log_struct log_item;
+
+    for (guint i = 0; i < log_array_tmp->len; i++) {
+        log_item = g_array_index(log_array_tmp, struct log_struct, i);
+        callbacks_handle_log_messages(log_item.domain, log_item.level, log_item.message, NULL);
+        g_free(log_item.domain);
+        g_free(log_item.message);
+    }
+    g_array_free(log_array_tmp, TRUE);
+
+    /* connect this signals as late as possible to avoid triggering them before
+       the gui is drawn */
+    g_signal_connect(
+        (gpointer)render_fast, "activate", G_CALLBACK(callbacks_viewmenu_rendertype_changed),
+        GINT_TO_POINTER(GERBV_RENDER_TYPE_GDK)
+    );
+    g_signal_connect(
+        (gpointer)render_fast_xor, "activate", G_CALLBACK(callbacks_viewmenu_rendertype_changed),
+        GINT_TO_POINTER(GERBV_RENDER_TYPE_GDK_XOR)
+    );
+    g_signal_connect(
+        (gpointer)render_normal, "activate", G_CALLBACK(callbacks_viewmenu_rendertype_changed),
+        GINT_TO_POINTER(GERBV_RENDER_TYPE_CAIRO_NORMAL)
+    );
+    g_signal_connect(
+        (gpointer)render_hq, "activate", G_CALLBACK(callbacks_viewmenu_rendertype_changed),
+        GINT_TO_POINTER(GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY)
+    );
+    g_signal_connect(
+        (gpointer)render_combobox, "changed", G_CALLBACK(callbacks_sidepane_render_type_combo_box_changed), NULL
+    );
+    gtk_main();
+    interface_save_accels();
 }
 
 /* ----------------------------------------------------  */
-void 
-interface_set_render_type (int t)
-{
-	if (t >= GERBV_RENDER_TYPE_MAX)
-		return;
+void
+interface_set_render_type(int t) {
+    if (t >= GERBV_RENDER_TYPE_MAX)
+        return;
 
-	screenRenderInfo.renderType = t;
+    screenRenderInfo.renderType = t;
 
-	/* make sure the interface is already up before calling
-	 * gtk_combo_box_set_active()
-	 */
-	if (!screen.win.sidepaneRenderComboBox)
-		return;
+    /* make sure the interface is already up before calling
+     * gtk_combo_box_set_active()
+     */
+    if (!screen.win.sidepaneRenderComboBox)
+        return;
 
-	gtk_combo_box_set_active (GTK_COMBO_BOX (screen.win.sidepaneRenderComboBox), t);
-	gtk_check_menu_item_set_active (screen.win.menu_view_render_group[t], TRUE);
+    gtk_combo_box_set_active(GTK_COMBO_BOX(screen.win.sidepaneRenderComboBox), t);
+    gtk_check_menu_item_set_active(screen.win.menu_view_render_group[t], TRUE);
 }
 
 /* ----------------------------------------------------  */
 /**
-  * This dialog box shows a message and two buttons:
-  * "True" and "False".  It returns gboolean 1 if the
-  * user clicked "True", and gboolean 0 if the user
-  * clicked "False".
-  *
-  */
+ * This dialog box shows a message and two buttons:
+ * "True" and "False".  It returns gboolean 1 if the
+ * user clicked "True", and gboolean 0 if the user
+ * clicked "False".
+ *
+ */
 
 gboolean
-interface_get_alert_dialog_response (const gchar *primaryText,
-				     const gchar *secondaryText,
-				     gboolean show_checkbox,
-				     gboolean *ask_to_show_again,
-				     const gchar *true_button_label,
-				     const gchar *false_button_label)
-     /* This fcn returns TRUE if the user presses the OK button,
-	otherwise it returns FALSE. */
+interface_get_alert_dialog_response(
+    const gchar* primaryText, const gchar* secondaryText, gboolean show_checkbox, gboolean* ask_to_show_again,
+    const gchar* true_button_label, const gchar* false_button_label
+)
+/* This fcn returns TRUE if the user presses the OK button,
+otherwise it returns FALSE. */
 {
-  /* Set show_checkbox = TRUE to show "do not show this again" checkbox. */
-  /* Point ask_to_show_again to the variable to set to not show the checkbox. */
-  GtkWidget *dialog1;
-  GtkWidget *dialog_vbox1;
-  GtkWidget *hbox1;
-  GtkWidget *image1;
-  GtkWidget *label1;
-  GtkWidget *checkbox=NULL;
-  GtkWidget *dialog_action_area1;
-  GtkWidget *true_button, *false_button;
-  gboolean returnVal = FALSE;
-
-  dialog1 = gtk_dialog_new ();
-  gtk_window_set_title (GTK_WINDOW (dialog1), _("Gerbv Alert"));
-  gtk_container_set_border_width (GTK_CONTAINER (dialog1), 6);
-  gtk_window_set_resizable (GTK_WINDOW (dialog1), FALSE);
-  gtk_window_set_type_hint (GTK_WINDOW (dialog1), GDK_WINDOW_TYPE_HINT_DIALOG);
-  gtk_dialog_set_has_separator (GTK_DIALOG (dialog1), FALSE);
-
-  dialog_vbox1 = GTK_DIALOG (dialog1)->vbox;
-
-  hbox1 = gtk_hbox_new (FALSE, 12);
-  gtk_box_pack_start (GTK_BOX (dialog_vbox1), hbox1, TRUE, TRUE, 0);
-  gtk_container_set_border_width (GTK_CONTAINER (hbox1), 6);
-
-  image1 = gtk_image_new_from_icon_name (GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
-  gtk_box_pack_start (GTK_BOX (hbox1), image1, TRUE, TRUE, 0);
-  gtk_misc_set_alignment (GTK_MISC (image1), 0.5, 0);
-
-  gchar *labelMessage = g_strconcat ("<span weight=\"bold\" size=\"larger\">", _(primaryText),
-  		"</span>\n<span/>\n", _(secondaryText), NULL);
-  label1 = gtk_label_new (labelMessage);
-  g_free (labelMessage);
-  GtkWidget *vbox9 = gtk_vbox_new (FALSE, 0);
-  gtk_box_pack_start (GTK_BOX (vbox9), label1, FALSE, FALSE, 0);
-  gtk_box_pack_start (GTK_BOX (hbox1), vbox9, FALSE, FALSE, 0);
-  gtk_label_set_use_markup (GTK_LABEL (label1), TRUE);
-  gtk_label_set_line_wrap (GTK_LABEL (label1), TRUE);
-
-  // even with no checkbox, this extra hbox gives the recommended 24 px space between the
-  //   label and the buttons
-  GtkWidget *hbox2 = gtk_hbox_new (FALSE, 12);
-  if (show_checkbox) {
-    GtkWidget *label3 = gtk_label_new ("    ");
-
-    checkbox =  gtk_check_button_new_with_label(_("Do not show this dialog again."));
-    gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON(checkbox), FALSE);
-    gtk_box_pack_start (GTK_BOX (hbox2), label3, FALSE, FALSE, 0);
-    gtk_box_pack_start (GTK_BOX (hbox2), checkbox, FALSE, FALSE, 0);
-  }
-  gtk_box_pack_start (GTK_BOX (vbox9), hbox2, FALSE, FALSE, 12);
-  
-  dialog_action_area1 = GTK_DIALOG (dialog1)->action_area;
-  gtk_button_box_set_layout (GTK_BUTTON_BOX (dialog_action_area1), GTK_BUTTONBOX_END);
-
-  if (false_button_label) {
-    false_button = gtk_button_new_from_stock (false_button_label);
-    gtk_dialog_add_action_widget (GTK_DIALOG (dialog1),
-	false_button, GTK_RESPONSE_CANCEL);
-    GTK_WIDGET_SET_FLAGS (false_button, GTK_CAN_DEFAULT);
-    gtk_widget_grab_default (false_button);
-    gtk_widget_grab_focus (false_button);
-  }
-
-  if (true_button_label) {
-    true_button = gtk_button_new_from_stock (true_button_label);
-    gtk_dialog_add_action_widget (GTK_DIALOG (dialog1),
-		  true_button, GTK_RESPONSE_OK);
-    GTK_WIDGET_SET_FLAGS (true_button, GTK_CAN_DEFAULT);
-  }
-
-  gtk_widget_show_all (dialog1);
-
-  if (gtk_dialog_run ((GtkDialog*)dialog1) == GTK_RESPONSE_OK) {
-    /* check to see if user clicked on "do not show again" box */
-    if ((show_checkbox == TRUE) &&
-	(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkbox)) == TRUE) &&
-	(ask_to_show_again != NULL) ) {
-      /* The user clicked the "do not show again box".  Set corresponding
-       * flag to FALSE. */
-      *ask_to_show_again = FALSE;
+    /* Set show_checkbox = TRUE to show "do not show this again" checkbox. */
+    /* Point ask_to_show_again to the variable to set to not show the checkbox. */
+    GtkWidget* dialog1;
+    GtkWidget* dialog_vbox1;
+    GtkWidget* hbox1;
+    GtkWidget* image1;
+    GtkWidget* label1;
+    GtkWidget* checkbox = NULL;
+    GtkWidget* dialog_action_area1;
+    GtkWidget *true_button, *false_button;
+    gboolean   returnVal = FALSE;
+
+    dialog1 = gtk_dialog_new();
+    gtk_window_set_title(GTK_WINDOW(dialog1), _("Gerbv Alert"));
+    gtk_container_set_border_width(GTK_CONTAINER(dialog1), 6);
+    gtk_window_set_resizable(GTK_WINDOW(dialog1), FALSE);
+    gtk_window_set_type_hint(GTK_WINDOW(dialog1), GDK_WINDOW_TYPE_HINT_DIALOG);
+    gtk_dialog_set_has_separator(GTK_DIALOG(dialog1), FALSE);
+
+    dialog_vbox1 = GTK_DIALOG(dialog1)->vbox;
+
+    hbox1 = gtk_hbox_new(FALSE, 12);
+    gtk_box_pack_start(GTK_BOX(dialog_vbox1), hbox1, TRUE, TRUE, 0);
+    gtk_container_set_border_width(GTK_CONTAINER(hbox1), 6);
+
+    image1 = gtk_image_new_from_icon_name(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
+    gtk_box_pack_start(GTK_BOX(hbox1), image1, TRUE, TRUE, 0);
+    gtk_misc_set_alignment(GTK_MISC(image1), 0.5, 0);
+
+    gchar* labelMessage = g_strconcat(
+        "<span weight=\"bold\" size=\"larger\">", _(primaryText), "</span>\n<span/>\n", _(secondaryText), NULL
+    );
+    label1 = gtk_label_new(labelMessage);
+    g_free(labelMessage);
+    GtkWidget* vbox9 = gtk_vbox_new(FALSE, 0);
+    gtk_box_pack_start(GTK_BOX(vbox9), label1, FALSE, FALSE, 0);
+    gtk_box_pack_start(GTK_BOX(hbox1), vbox9, FALSE, FALSE, 0);
+    gtk_label_set_use_markup(GTK_LABEL(label1), TRUE);
+    gtk_label_set_line_wrap(GTK_LABEL(label1), TRUE);
+
+    // even with no checkbox, this extra hbox gives the recommended 24 px space between the
+    //   label and the buttons
+    GtkWidget* hbox2 = gtk_hbox_new(FALSE, 12);
+    if (show_checkbox) {
+        GtkWidget* label3 = gtk_label_new("    ");
+
+        checkbox = gtk_check_button_new_with_label(_("Do not show this dialog again."));
+        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbox), FALSE);
+        gtk_box_pack_start(GTK_BOX(hbox2), label3, FALSE, FALSE, 0);
+        gtk_box_pack_start(GTK_BOX(hbox2), checkbox, FALSE, FALSE, 0);
+    }
+    gtk_box_pack_start(GTK_BOX(vbox9), hbox2, FALSE, FALSE, 12);
+
+    dialog_action_area1 = GTK_DIALOG(dialog1)->action_area;
+    gtk_button_box_set_layout(GTK_BUTTON_BOX(dialog_action_area1), GTK_BUTTONBOX_END);
+
+    if (false_button_label) {
+        false_button = gtk_button_new_from_stock(false_button_label);
+        gtk_dialog_add_action_widget(GTK_DIALOG(dialog1), false_button, GTK_RESPONSE_CANCEL);
+        GTK_WIDGET_SET_FLAGS(false_button, GTK_CAN_DEFAULT);
+        gtk_widget_grab_default(false_button);
+        gtk_widget_grab_focus(false_button);
+    }
+
+    if (true_button_label) {
+        true_button = gtk_button_new_from_stock(true_button_label);
+        gtk_dialog_add_action_widget(GTK_DIALOG(dialog1), true_button, GTK_RESPONSE_OK);
+        GTK_WIDGET_SET_FLAGS(true_button, GTK_CAN_DEFAULT);
+    }
+
+    gtk_widget_show_all(dialog1);
+
+    if (gtk_dialog_run((GtkDialog*)dialog1) == GTK_RESPONSE_OK) {
+        /* check to see if user clicked on "do not show again" box */
+        if ((show_checkbox == TRUE) && (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkbox)) == TRUE)
+            && (ask_to_show_again != NULL)) {
+            /* The user clicked the "do not show again box".  Set corresponding
+             * flag to FALSE. */
+            *ask_to_show_again = FALSE;
+        }
+        returnVal = TRUE;
     }
-    returnVal = TRUE;
-  }
-  gtk_widget_destroy (dialog1);
-		
-  return returnVal;
+    gtk_widget_destroy(dialog1);
+
+    return returnVal;
 }
 
 static void
-interface_reopen_question_callback_select_all (GtkWidget *checkbox,
-						gpointer user_data)
-{
+interface_reopen_question_callback_select_all(GtkWidget* checkbox, gpointer user_data) {
 
-  /* Set select all checkbox if it was inconsistent. */
-  if (gtk_toggle_button_get_inconsistent (GTK_TOGGLE_BUTTON (checkbox)))
-    gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (checkbox), TRUE);
+    /* Set select all checkbox if it was inconsistent. */
+    if (gtk_toggle_button_get_inconsistent(GTK_TOGGLE_BUTTON(checkbox)))
+        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbox), TRUE);
 
-  gtk_toggle_button_set_inconsistent (GTK_TOGGLE_BUTTON (checkbox), FALSE);
+    gtk_toggle_button_set_inconsistent(GTK_TOGGLE_BUTTON(checkbox), FALSE);
 
-  for (GSList *cb = user_data; cb; cb = cb->next) {
-    gtk_toggle_button_set_active (cb->data,
-	gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (checkbox)));
-  }
+    for (GSList* cb = user_data; cb; cb = cb->next) {
+        gtk_toggle_button_set_active(cb->data, gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkbox)));
+    }
 }
 
 struct interface_reopen_question_struct {
-  GtkWidget *set_all_checkbox;
-  GSList *checkbox_list;
+    GtkWidget* set_all_checkbox;
+    GSList*    checkbox_list;
 };
 
 static void
-interface_reopen_question_callback_checkbox(GtkWidget *checkbox,
-						gpointer user_data)
-{
-  struct interface_reopen_question_struct *st = user_data;
-  gboolean all_set = TRUE, all_clear = TRUE;
+interface_reopen_question_callback_checkbox(GtkWidget* checkbox, gpointer user_data) {
+    struct interface_reopen_question_struct* st      = user_data;
+    gboolean                                 all_set = TRUE, all_clear = TRUE;
+
+    if (st->set_all_checkbox == NULL)
+        return;
+
+    for (GSList* cb = st->checkbox_list; cb; cb = cb->next) {
+        if (gtk_toggle_button_get_active(cb->data))
+            all_clear = FALSE;
+        else
+            all_set = FALSE;
+    }
 
-  if (st->set_all_checkbox == NULL)
-    return;
+    gtk_toggle_button_set_inconsistent(GTK_TOGGLE_BUTTON(st->set_all_checkbox), FALSE);
 
-  for (GSList *cb = st->checkbox_list; cb; cb = cb->next) {
-    if (gtk_toggle_button_get_active(cb->data))
-      all_clear = FALSE;
+    if (all_set)
+        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(st->set_all_checkbox), TRUE);
+    else if (all_clear)
+        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(st->set_all_checkbox), FALSE);
     else
-      all_set = FALSE;
-  }
-
-  gtk_toggle_button_set_inconsistent (
-      GTK_TOGGLE_BUTTON (st->set_all_checkbox), FALSE);
-
-  if (all_set)
-    gtk_toggle_button_set_active (
-	GTK_TOGGLE_BUTTON (st->set_all_checkbox), TRUE);
-  else if (all_clear)
-    gtk_toggle_button_set_active (
-	GTK_TOGGLE_BUTTON (st->set_all_checkbox), FALSE);
-  else
-    gtk_toggle_button_set_inconsistent (
-	GTK_TOGGLE_BUTTON (st->set_all_checkbox), TRUE);
+        gtk_toggle_button_set_inconsistent(GTK_TOGGLE_BUTTON(st->set_all_checkbox), TRUE);
 }
 
 /* Add checkboxes for filenames and return list with checkbox widgets */
-static GSList *
-interface_reopen_question_add_filename_checkboxes (
-		GSList *fns, GSList *fns_is_mod,
-		GSList *fns_cnt, GSList *fns_lay_num, GtkWidget *box)
-{
-  GtkWidget *scrl_win, *vbox;
-  GSList *checkboxes = NULL;
-
-  scrl_win = gtk_scrolled_window_new (NULL, NULL);
-  gtk_box_pack_start (GTK_BOX (box), scrl_win, TRUE, TRUE, 0);
-  gtk_container_set_border_width (GTK_CONTAINER (scrl_win), 2);
-  gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrl_win), 
-				GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
-
-  vbox = gtk_vbox_new (FALSE, 2);
-  gtk_scrolled_window_add_with_viewport (GTK_SCROLLED_WINDOW (scrl_win), vbox);
-
-  for (unsigned int i = 0; i < g_slist_length (fns); i++) { 
-    GtkWidget *cb;
-    GString *g_str = g_string_new (NULL);
-    gchar *bn = g_path_get_basename (g_slist_nth_data (fns, i));
-    int cnt = GPOINTER_TO_INT (g_slist_nth_data (fns_cnt, i));
-    int lay_num = 1 + GPOINTER_TO_INT (g_slist_nth_data (fns_lay_num, i));
-
-    if (GPOINTER_TO_INT (g_slist_nth_data (fns_is_mod, i))) {
-      /* Layer is modified */
-      if (cnt > 1)
-	g_string_printf (g_str, ngettext(
-	      "<b>%d</b>  *<i>%s</i> (<b>changed</b>, %d layer)",
-	      "<b>%d</b>  *<i>%s</i> (<b>changed</b>, %d layers)", cnt),
-			lay_num, bn, cnt);
-      else 
-	g_string_printf (g_str, _("<b>%d</b>  *<i>%s</i> (<b>changed</b>)"),
-			lay_num, bn);
-    } else {
-      /* Layer is not modified */
-      if (cnt > 1)
-	g_string_printf (g_str, ngettext(
-	      "<b>%d</b>  %s (%d layer)",
-	      "<b>%d</b>  %s (%d layers)", cnt), lay_num, bn, cnt);
-      else 
-	g_string_printf (g_str, _("<b>%d</b>  %s"), lay_num, bn);
+static GSList*
+interface_reopen_question_add_filename_checkboxes(
+    GSList* fns, GSList* fns_is_mod, GSList* fns_cnt, GSList* fns_lay_num, GtkWidget* box
+) {
+    GtkWidget *scrl_win, *vbox;
+    GSList*    checkboxes = NULL;
+
+    scrl_win = gtk_scrolled_window_new(NULL, NULL);
+    gtk_box_pack_start(GTK_BOX(box), scrl_win, TRUE, TRUE, 0);
+    gtk_container_set_border_width(GTK_CONTAINER(scrl_win), 2);
+    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrl_win), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
+
+    vbox = gtk_vbox_new(FALSE, 2);
+    gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrl_win), vbox);
+
+    for (unsigned int i = 0; i < g_slist_length(fns); i++) {
+        GtkWidget* cb;
+        GString*   g_str   = g_string_new(NULL);
+        gchar*     bn      = g_path_get_basename(g_slist_nth_data(fns, i));
+        int        cnt     = GPOINTER_TO_INT(g_slist_nth_data(fns_cnt, i));
+        int        lay_num = 1 + GPOINTER_TO_INT(g_slist_nth_data(fns_lay_num, i));
+
+        if (GPOINTER_TO_INT(g_slist_nth_data(fns_is_mod, i))) {
+            /* Layer is modified */
+            if (cnt > 1)
+                g_string_printf(
+                    g_str,
+                    ngettext(
+                        "<b>%d</b>  *<i>%s</i> (<b>changed</b>, %d layer)",
+                        "<b>%d</b>  *<i>%s</i> (<b>changed</b>, %d layers)", cnt
+                    ),
+                    lay_num, bn, cnt
+                );
+            else
+                g_string_printf(g_str, _("<b>%d</b>  *<i>%s</i> (<b>changed</b>)"), lay_num, bn);
+        } else {
+            /* Layer is not modified */
+            if (cnt > 1)
+                g_string_printf(
+                    g_str, ngettext("<b>%d</b>  %s (%d layer)", "<b>%d</b>  %s (%d layers)", cnt), lay_num, bn, cnt
+                );
+            else
+                g_string_printf(g_str, _("<b>%d</b>  %s"), lay_num, bn);
+        }
+        g_free(bn);
+
+        cb = gtk_check_button_new_with_label("");
+        gtk_label_set_markup(GTK_LABEL(gtk_bin_get_child(GTK_BIN(cb))), g_str->str);
+        g_string_free(g_str, TRUE);
+        checkboxes = g_slist_append(checkboxes, cb);
+        gtk_box_pack_start(GTK_BOX(vbox), cb, FALSE, FALSE, 0);
     }
-    g_free (bn);
-
-    cb = gtk_check_button_new_with_label ("");
-    gtk_label_set_markup (GTK_LABEL (gtk_bin_get_child (GTK_BIN (cb))),
-				g_str->str);
-    g_string_free (g_str, TRUE);
-    checkboxes = g_slist_append (checkboxes, cb);
-    gtk_box_pack_start (GTK_BOX (vbox), cb, FALSE, FALSE, 0);
-  }
 
-  return checkboxes;
+    return checkboxes;
 }
 
-
 /* ----------------------------------------------------  */
 /**
-  * This dialog box shows a text message with three buttons in the case
-  * if the file to be open was already loaded:
-  * "Reload" (the already loaded file)
-  * "Open as new layer"
-  * "Skip loading"
-  */
+ * This dialog box shows a text message with three buttons in the case
+ * if the file to be open was already loaded:
+ * "Reload" (the already loaded file)
+ * "Open as new layer"
+ * "Skip loading"
+ */
 int
-interface_reopen_question (GSList *fns, GSList *fns_is_mod,
-				GSList *fns_cnt, GSList *fns_lay_num)
-{
-  GtkDialog *dialog;
-  GtkWidget *hbox, *vbox_main, *image,
-	    *selectAllCheckBox = NULL;
-  GSList *fnCheckButtons = NULL;
-  GtkWidget *label, *reloadButton, *openAsNewButton;
-  struct interface_reopen_question_struct checkboxes_struct;
-  GString *g_str = g_string_new (NULL);
-  guint fns_len;
-  gint ret = 0;
-
-  fns_len = g_slist_length (fns);
-  if (0 == fns_len)
-    return GTK_RESPONSE_NONE;
-
-  dialog = GTK_DIALOG (gtk_dialog_new());
-  gtk_window_set_title (GTK_WINDOW (dialog), _("Gerbv — Reload Files"));
-  gtk_container_set_border_width (GTK_CONTAINER (dialog), 6);
-  gtk_window_set_type_hint (GTK_WINDOW (dialog), GDK_WINDOW_TYPE_HINT_DIALOG);
-  gtk_dialog_set_has_separator (dialog, FALSE);
-
-  hbox = gtk_hbox_new (FALSE, 12);
-  gtk_box_pack_start (GTK_BOX (dialog->vbox), hbox, TRUE, TRUE, 0);
-  gtk_container_set_border_width (GTK_CONTAINER (hbox), 6);
-
-  image = gtk_image_new_from_icon_name (GTK_STOCK_DIALOG_WARNING,
-		  GTK_ICON_SIZE_DIALOG);
-  gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
-  gtk_misc_set_alignment (GTK_MISC (image), 0, 0);
-
-  vbox_main = gtk_vbox_new (FALSE, 0);
-  gtk_box_pack_start (GTK_BOX (hbox), vbox_main, TRUE, TRUE, 0);
-
-  g_string_printf (g_str, "<span size=\"larger\">");
-  g_string_append_printf (g_str, ngettext(
-			  "%u file is already loaded from directory",
-			  "%u files are already loaded from directory",
-			  fns_len), fns_len);
-  g_string_append_printf (g_str, "</span>\n\"%s\"",
-		  g_path_get_dirname (fns->data));
-
-  /* Add title */
-  label = gtk_label_new (g_str->str);
-  gtk_box_pack_start (GTK_BOX (vbox_main), label, FALSE, FALSE, 0);
-  gtk_label_set_use_markup (GTK_LABEL (label), TRUE);
-  gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
-  gtk_label_set_line_wrap  (GTK_LABEL (label), TRUE);
-  gtk_label_set_selectable (GTK_LABEL (label), TRUE);
-  g_string_free (g_str, TRUE);
-
-  fnCheckButtons = interface_reopen_question_add_filename_checkboxes (
-					fns, fns_is_mod,
-					fns_cnt, fns_lay_num, vbox_main);
-
-  /* Add "Select all" checkbox */
-  if (fns_len > 1) {
-    selectAllCheckBox =
-	    gtk_check_button_new_with_mnemonic (_("Select _all"));
-
-    g_signal_connect ((gpointer) selectAllCheckBox, "toggled",
-	G_CALLBACK (interface_reopen_question_callback_select_all),
-	fnCheckButtons);
-
-    gtk_box_pack_start (GTK_BOX(vbox_main), selectAllCheckBox, FALSE, FALSE, 0);
-  }
-
-  /* Select all chekboxes by default */
-  if (fns_len > 1) {
-    gtk_toggle_button_set_active (
-	GTK_TOGGLE_BUTTON(selectAllCheckBox), TRUE);
-  } else {
-    /* Only one checkbox in list */
-    gtk_toggle_button_set_active (
-	GTK_TOGGLE_BUTTON(fnCheckButtons->data), TRUE);
-  }
-
-  checkboxes_struct.checkbox_list = fnCheckButtons;
-  checkboxes_struct.set_all_checkbox = selectAllCheckBox;
-
-  /* Set callback for each file checkbox */
-  for (GSList *cb = checkboxes_struct.checkbox_list; cb; cb = cb->next) {
-    g_signal_connect ((gpointer) cb->data, "toggled",
-	G_CALLBACK (interface_reopen_question_callback_checkbox),
-	&checkboxes_struct);
-  }
-
-  gtk_button_box_set_layout (GTK_BUTTON_BOX (dialog->action_area),
-		  GTK_BUTTONBOX_END);
-
-  reloadButton = gtk_button_new_with_mnemonic (_("_Reload"));
-  gtk_widget_set_tooltip_text (reloadButton,
-				_("Reload layers with selected files"));
-  gtk_dialog_add_action_widget (dialog, reloadButton, GTK_RESPONSE_YES);
-  GTK_WIDGET_SET_FLAGS (reloadButton, GTK_CAN_DEFAULT);
-
-  openAsNewButton = gtk_button_new_with_mnemonic (_("Add as _new"));
-  gtk_widget_set_tooltip_text (openAsNewButton,
-				_("Add selected files as new layers"));
-  gtk_dialog_add_action_widget (dialog, openAsNewButton, GTK_RESPONSE_OK);
-
-  gtk_dialog_add_action_widget (dialog,
-      gtk_button_new_from_stock (GTK_STOCK_CANCEL), GTK_RESPONSE_CANCEL);
-
-  gtk_widget_show_all (GTK_WIDGET(dialog));
-
-  ret = gtk_dialog_run (dialog);
-
-  /* Mark with NULL filenames list data with unchecked filenames */
-  for (GSList *cb = fnCheckButtons, *fn = fns;
-			cb && fn; cb = cb->next, fn = fn->next) {
-    if (!gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (cb->data)))
-      fn->data = NULL;
-  }
-
-  g_slist_free_full (fnCheckButtons, (GDestroyNotify)gtk_widget_destroy);
-  gtk_widget_destroy (GTK_WIDGET(dialog));
-
-  return ret;
-}
+interface_reopen_question(GSList* fns, GSList* fns_is_mod, GSList* fns_cnt, GSList* fns_lay_num) {
+    GtkDialog*                              dialog;
+    GtkWidget *                             hbox, *vbox_main, *image, *selectAllCheckBox = NULL;
+    GSList*                                 fnCheckButtons = NULL;
+    GtkWidget *                             label, *reloadButton, *openAsNewButton;
+    struct interface_reopen_question_struct checkboxes_struct;
+    GString*                                g_str = g_string_new(NULL);
+    guint                                   fns_len;
+    gint                                    ret = 0;
+
+    fns_len = g_slist_length(fns);
+    if (0 == fns_len)
+        return GTK_RESPONSE_NONE;
+
+    dialog = GTK_DIALOG(gtk_dialog_new());
+    gtk_window_set_title(GTK_WINDOW(dialog), _("Gerbv — Reload Files"));
+    gtk_container_set_border_width(GTK_CONTAINER(dialog), 6);
+    gtk_window_set_type_hint(GTK_WINDOW(dialog), GDK_WINDOW_TYPE_HINT_DIALOG);
+    gtk_dialog_set_has_separator(dialog, FALSE);
+
+    hbox = gtk_hbox_new(FALSE, 12);
+    gtk_box_pack_start(GTK_BOX(dialog->vbox), hbox, TRUE, TRUE, 0);
+    gtk_container_set_border_width(GTK_CONTAINER(hbox), 6);
+
+    image = gtk_image_new_from_icon_name(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
+    gtk_box_pack_start(GTK_BOX(hbox), image, FALSE, FALSE, 0);
+    gtk_misc_set_alignment(GTK_MISC(image), 0, 0);
+
+    vbox_main = gtk_vbox_new(FALSE, 0);
+    gtk_box_pack_start(GTK_BOX(hbox), vbox_main, TRUE, TRUE, 0);
+
+    g_string_printf(g_str, "<span size=\"larger\">");
+    g_string_append_printf(
+        g_str,
+        ngettext("%u file is already loaded from directory", "%u files are already loaded from directory", fns_len),
+        fns_len
+    );
+    g_string_append_printf(g_str, "</span>\n\"%s\"", g_path_get_dirname(fns->data));
+
+    /* Add title */
+    label = gtk_label_new(g_str->str);
+    gtk_box_pack_start(GTK_BOX(vbox_main), label, FALSE, FALSE, 0);
+    gtk_label_set_use_markup(GTK_LABEL(label), TRUE);
+    gtk_misc_set_alignment(GTK_MISC(label), 0, 0);
+    gtk_label_set_line_wrap(GTK_LABEL(label), TRUE);
+    gtk_label_set_selectable(GTK_LABEL(label), TRUE);
+    g_string_free(g_str, TRUE);
+
+    fnCheckButtons =
+        interface_reopen_question_add_filename_checkboxes(fns, fns_is_mod, fns_cnt, fns_lay_num, vbox_main);
+
+    /* Add "Select all" checkbox */
+    if (fns_len > 1) {
+        selectAllCheckBox = gtk_check_button_new_with_mnemonic(_("Select _all"));
+
+        g_signal_connect(
+            (gpointer)selectAllCheckBox, "toggled", G_CALLBACK(interface_reopen_question_callback_select_all),
+            fnCheckButtons
+        );
+
+        gtk_box_pack_start(GTK_BOX(vbox_main), selectAllCheckBox, FALSE, FALSE, 0);
+    }
+
+    /* Select all chekboxes by default */
+    if (fns_len > 1) {
+        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(selectAllCheckBox), TRUE);
+    } else {
+        /* Only one checkbox in list */
+        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(fnCheckButtons->data), TRUE);
+    }
+
+    checkboxes_struct.checkbox_list    = fnCheckButtons;
+    checkboxes_struct.set_all_checkbox = selectAllCheckBox;
+
+    /* Set callback for each file checkbox */
+    for (GSList* cb = checkboxes_struct.checkbox_list; cb; cb = cb->next) {
+        g_signal_connect(
+            (gpointer)cb->data, "toggled", G_CALLBACK(interface_reopen_question_callback_checkbox), &checkboxes_struct
+        );
+    }
+
+    gtk_button_box_set_layout(GTK_BUTTON_BOX(dialog->action_area), GTK_BUTTONBOX_END);
+
+    reloadButton = gtk_button_new_with_mnemonic(_("_Reload"));
+    gtk_widget_set_tooltip_text(reloadButton, _("Reload layers with selected files"));
+    gtk_dialog_add_action_widget(dialog, reloadButton, GTK_RESPONSE_YES);
+    GTK_WIDGET_SET_FLAGS(reloadButton, GTK_CAN_DEFAULT);
+
+    openAsNewButton = gtk_button_new_with_mnemonic(_("Add as _new"));
+    gtk_widget_set_tooltip_text(openAsNewButton, _("Add selected files as new layers"));
+    gtk_dialog_add_action_widget(dialog, openAsNewButton, GTK_RESPONSE_OK);
 
+    gtk_dialog_add_action_widget(dialog, gtk_button_new_from_stock(GTK_STOCK_CANCEL), GTK_RESPONSE_CANCEL);
+
+    gtk_widget_show_all(GTK_WIDGET(dialog));
+
+    ret = gtk_dialog_run(dialog);
+
+    /* Mark with NULL filenames list data with unchecked filenames */
+    for (GSList *cb = fnCheckButtons, *fn = fns; cb && fn; cb = cb->next, fn = fn->next) {
+        if (!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(cb->data)))
+            fn->data = NULL;
+    }
+
+    g_slist_free_full(fnCheckButtons, (GDestroyNotify)gtk_widget_destroy);
+    gtk_widget_destroy(GTK_WIDGET(dialog));
+
+    return ret;
+}
 
 /* ----------------------------------------------------  */
 /**
-  * This dialog box shows a textmessage and one button:
-  * "OK".  It does not return anything.
-  *
-  */
+ * This dialog box shows a textmessage and one button:
+ * "OK".  It does not return anything.
+ *
+ */
 void
-interface_show_alert_dialog (gchar *primaryText, gchar *secondaryText, 
-			     gboolean show_checkbox, gboolean *ask_to_show_again )
-     /* This fcn tells the user something, and only displays "OK" */
+interface_show_alert_dialog(
+    gchar* primaryText, gchar* secondaryText, gboolean show_checkbox, gboolean* ask_to_show_again
+)
+/* This fcn tells the user something, and only displays "OK" */
 {
-  /* Set show_checkbox = TRUE to show "do not show this again" checkbox. */
-  /* Point ask_to_show_again to the variable to set to not show the checkbox. */
-  GtkWidget *dialog1;
-  GtkWidget *dialog_vbox1;
-  GtkWidget *hbox1;
-  GtkWidget *image1;
-  GtkWidget *label1;
-  GtkWidget *checkbox=NULL;
-  GtkWidget *dialog_action_area1;
-  GtkWidget *okbutton1;
-
-  dialog1 = gtk_dialog_new ();
-  gtk_container_set_border_width (GTK_CONTAINER (dialog1), 6);
-  gtk_window_set_resizable (GTK_WINDOW (dialog1), FALSE);
-  gtk_window_set_type_hint (GTK_WINDOW (dialog1), GDK_WINDOW_TYPE_HINT_DIALOG);
-  gtk_dialog_set_has_separator (GTK_DIALOG (dialog1), FALSE);
-
-  dialog_vbox1 = GTK_DIALOG (dialog1)->vbox;
-
-  hbox1 = gtk_hbox_new (FALSE, 12);
-  gtk_box_pack_start (GTK_BOX (dialog_vbox1), hbox1, TRUE, TRUE, 0);
-  gtk_container_set_border_width (GTK_CONTAINER (hbox1), 6);
-
-  image1 = gtk_image_new_from_icon_name (GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
-  gtk_box_pack_start (GTK_BOX (hbox1), image1, TRUE, TRUE, 0);
-  gtk_misc_set_alignment (GTK_MISC (image1), 0.5, 0);
-
-  gchar *labelMessage = g_strconcat ("<span weight=\"bold\" size=\"larger\">", _(primaryText),
-  		"</span>\n<span/>\n", _(secondaryText), NULL);
-  label1 = gtk_label_new (labelMessage);
-  g_free (labelMessage);
-  
-  GtkWidget *vbox9 = gtk_vbox_new (FALSE, 0);
-  gtk_box_pack_start (GTK_BOX (vbox9), label1, FALSE, FALSE, 0);
-  gtk_label_set_use_markup (GTK_LABEL (label1), TRUE);
-  gtk_label_set_line_wrap (GTK_LABEL (label1), TRUE);
-  gtk_box_pack_start (GTK_BOX (hbox1), vbox9, FALSE, FALSE, 0);
-  
-  GtkWidget *hbox2 = gtk_hbox_new (FALSE, 12);
-  if (show_checkbox) {
-    GtkWidget *label3 = gtk_label_new ("    ");
-
-    checkbox =  gtk_check_button_new_with_label(_("Do not show this dialog again."));
-    gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON(checkbox), FALSE);
-    gtk_box_pack_start (GTK_BOX (hbox2), label3, FALSE, FALSE, 0);
-    gtk_box_pack_start (GTK_BOX (hbox2), checkbox, FALSE, FALSE, 0);
-  }
-  gtk_box_pack_start (GTK_BOX (vbox9), hbox2, FALSE, FALSE, 12);
-  
-  dialog_action_area1 = GTK_DIALOG (dialog1)->action_area;
-  gtk_button_box_set_layout (GTK_BUTTON_BOX (dialog_action_area1), GTK_BUTTONBOX_END);
-
-  okbutton1 = gtk_button_new_from_stock (GTK_STOCK_OK);
-  gtk_dialog_add_action_widget (GTK_DIALOG (dialog1), okbutton1, GTK_RESPONSE_OK);
-  GTK_WIDGET_SET_FLAGS (okbutton1, GTK_CAN_DEFAULT);
-
-  gtk_widget_show_all (dialog1);
-
-  /* check to see if user clicked on "do not show again" box */
-  if ((show_checkbox == TRUE) &&
-      (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkbox)) == TRUE) &&
-      (ask_to_show_again != NULL) ) {
-    /* The user clicked the "do not show again box".  Set corresponding
-     * flag to FALSE. */
-    *ask_to_show_again = FALSE;
-  }
-
-  gtk_dialog_run (GTK_DIALOG(dialog1));
-  gtk_widget_destroy (dialog1);
-		
-  return;
+    /* Set show_checkbox = TRUE to show "do not show this again" checkbox. */
+    /* Point ask_to_show_again to the variable to set to not show the checkbox. */
+    GtkWidget* dialog1;
+    GtkWidget* dialog_vbox1;
+    GtkWidget* hbox1;
+    GtkWidget* image1;
+    GtkWidget* label1;
+    GtkWidget* checkbox = NULL;
+    GtkWidget* dialog_action_area1;
+    GtkWidget* okbutton1;
+
+    dialog1 = gtk_dialog_new();
+    gtk_container_set_border_width(GTK_CONTAINER(dialog1), 6);
+    gtk_window_set_resizable(GTK_WINDOW(dialog1), FALSE);
+    gtk_window_set_type_hint(GTK_WINDOW(dialog1), GDK_WINDOW_TYPE_HINT_DIALOG);
+    gtk_dialog_set_has_separator(GTK_DIALOG(dialog1), FALSE);
+
+    dialog_vbox1 = GTK_DIALOG(dialog1)->vbox;
+
+    hbox1 = gtk_hbox_new(FALSE, 12);
+    gtk_box_pack_start(GTK_BOX(dialog_vbox1), hbox1, TRUE, TRUE, 0);
+    gtk_container_set_border_width(GTK_CONTAINER(hbox1), 6);
+
+    image1 = gtk_image_new_from_icon_name(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
+    gtk_box_pack_start(GTK_BOX(hbox1), image1, TRUE, TRUE, 0);
+    gtk_misc_set_alignment(GTK_MISC(image1), 0.5, 0);
+
+    gchar* labelMessage = g_strconcat(
+        "<span weight=\"bold\" size=\"larger\">", _(primaryText), "</span>\n<span/>\n", _(secondaryText), NULL
+    );
+    label1 = gtk_label_new(labelMessage);
+    g_free(labelMessage);
+
+    GtkWidget* vbox9 = gtk_vbox_new(FALSE, 0);
+    gtk_box_pack_start(GTK_BOX(vbox9), label1, FALSE, FALSE, 0);
+    gtk_label_set_use_markup(GTK_LABEL(label1), TRUE);
+    gtk_label_set_line_wrap(GTK_LABEL(label1), TRUE);
+    gtk_box_pack_start(GTK_BOX(hbox1), vbox9, FALSE, FALSE, 0);
+
+    GtkWidget* hbox2 = gtk_hbox_new(FALSE, 12);
+    if (show_checkbox) {
+        GtkWidget* label3 = gtk_label_new("    ");
+
+        checkbox = gtk_check_button_new_with_label(_("Do not show this dialog again."));
+        gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbox), FALSE);
+        gtk_box_pack_start(GTK_BOX(hbox2), label3, FALSE, FALSE, 0);
+        gtk_box_pack_start(GTK_BOX(hbox2), checkbox, FALSE, FALSE, 0);
+    }
+    gtk_box_pack_start(GTK_BOX(vbox9), hbox2, FALSE, FALSE, 12);
+
+    dialog_action_area1 = GTK_DIALOG(dialog1)->action_area;
+    gtk_button_box_set_layout(GTK_BUTTON_BOX(dialog_action_area1), GTK_BUTTONBOX_END);
+
+    okbutton1 = gtk_button_new_from_stock(GTK_STOCK_OK);
+    gtk_dialog_add_action_widget(GTK_DIALOG(dialog1), okbutton1, GTK_RESPONSE_OK);
+    GTK_WIDGET_SET_FLAGS(okbutton1, GTK_CAN_DEFAULT);
+
+    gtk_widget_show_all(dialog1);
+
+    /* check to see if user clicked on "do not show again" box */
+    if ((show_checkbox == TRUE) && (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkbox)) == TRUE)
+        && (ask_to_show_again != NULL)) {
+        /* The user clicked the "do not show again box".  Set corresponding
+         * flag to FALSE. */
+        *ask_to_show_again = FALSE;
+    }
+
+    gtk_dialog_run(GTK_DIALOG(dialog1));
+    gtk_widget_destroy(dialog1);
+
+    return;
 }
 
 static int focused_widget_num = 0;
 
 gboolean
-focus_in_event_callback (int *widget_num)
-{
-	focused_widget_num = *widget_num;
-	return FALSE;
+focus_in_event_callback(int* widget_num) {
+    focused_widget_num = *widget_num;
+    return FALSE;
 }
 
 void
-interface_show_layer_edit_dialog (gerbv_user_transformation_t *transforms[],
-		gerbv_unit_t screenUnit) {
-	GtkWidget *dialog;
-	GtkWidget *check1,*check2,*check3,*tempWidget,*tempWidget2,*tableWidget;
-	GtkWidget *spin1,*spin2,*spin3,*spin4,*spin5;
-	GtkAdjustment *adj;
-	/* NOTE: transforms[0] is selected layer, other in array is visible. */
-	/* Copy _selected_ layer transformation to use as initial. */
-	gerbv_user_transformation_t trans_init = *transforms[0],
-					*trans = &trans_init;
+interface_show_layer_edit_dialog(gerbv_user_transformation_t* transforms[], gerbv_unit_t screenUnit) {
+    GtkWidget*     dialog;
+    GtkWidget *    check1, *check2, *check3, *tempWidget, *tempWidget2, *tableWidget;
+    GtkWidget *    spin1, *spin2, *spin3, *spin4, *spin5;
+    GtkAdjustment* adj;
+    /* NOTE: transforms[0] is selected layer, other in array is visible. */
+    /* Copy _selected_ layer transformation to use as initial. */
+    gerbv_user_transformation_t trans_init = *transforms[0], *trans = &trans_init;
 
 #if 0
 /* TODO: cancel, backup array of initial transforms */
 gerbv_user_transformation_t startTransform = trans;
 #endif
-	GtkWidget **focus_widgets[] = {&spin1, &spin2, &spin3, &spin4, &spin5, &check1, &check2, NULL};
-	int focus_nums[G_N_ELEMENTS(focus_widgets)];
-	int i;
-
-	dialog = gtk_dialog_new_with_buttons (_("Edit layer"),
-				GTK_WINDOW (screen.win.topLevelWindow),
-				GTK_DIALOG_DESTROY_WITH_PARENT,
-				_("Apply to _active"), GTK_RESPONSE_APPLY,
-				/* Yes -- apply to all visible */
-				_("Apply to _visible"), GTK_RESPONSE_YES,
-				GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE,
-				NULL);
-
-	gtk_container_set_border_width (GTK_CONTAINER (dialog), 6);
-	gtk_window_set_resizable (GTK_WINDOW (dialog), FALSE);
-	gtk_window_set_type_hint (GTK_WINDOW (dialog), GDK_WINDOW_TYPE_HINT_DIALOG);
-	gtk_dialog_set_has_separator (GTK_DIALOG (dialog), FALSE);
-
-	tableWidget = gtk_table_new (16,3,FALSE);
-	gtk_box_pack_start (GTK_BOX (GTK_DIALOG (dialog)->vbox), tableWidget, FALSE, FALSE, 0);
-
-	tempWidget = gtk_label_new (NULL);
-	gtk_label_set_markup (GTK_LABEL (tempWidget), _("<span weight=\"bold\">Translation</span>"));
-	gtk_misc_set_alignment (GTK_MISC (tempWidget), 0.0, 0.5);
-	gtk_table_attach ((GtkTable *) tableWidget, tempWidget,0,2,0,1,GTK_EXPAND|GTK_FILL,0,0,5);
-
-	tempWidget = gtk_label_new ("");
-	gtk_table_attach ((GtkTable *) tableWidget, tempWidget,0,1,1,2,GTK_EXPAND|GTK_FILL,0,0,0);
-	gdouble translateX, translateY;
-	
-	if (screenUnit == (gerbv_unit_t) GERBV_MILS) {
-		tempWidget = gtk_label_new (_("X (mils):"));
-		tempWidget2 = gtk_label_new (_("Y (mils):"));
-		translateX = trans->translateX * 1000;
-		translateY = trans->translateY * 1000;
-	}
-	else if (screen.unit == (gerbv_gui_unit_t) GERBV_MMS) {
-		tempWidget = gtk_label_new (_("X (mm):"));
-		tempWidget2 = gtk_label_new (_("Y (mm):"));
-		translateX = trans->translateX * 25.4;
-		translateY = trans->translateY * 25.4;
-	}
-	else {
-		tempWidget = gtk_label_new (_("X (inches):"));
-		tempWidget2 = gtk_label_new (_("Y (inches):"));
-		translateX = trans->translateX;
-		translateY = trans->translateY;
-	}
+    GtkWidget** focus_widgets[] = { &spin1, &spin2, &spin3, &spin4, &spin5, &check1, &check2, NULL };
+    int         focus_nums[G_N_ELEMENTS(focus_widgets)];
+    int         i;
+
+    dialog = gtk_dialog_new_with_buttons(
+        _("Edit layer"), GTK_WINDOW(screen.win.topLevelWindow), GTK_DIALOG_DESTROY_WITH_PARENT, _("Apply to _active"),
+        GTK_RESPONSE_APPLY,
+        /* Yes -- apply to all visible */
+        _("Apply to _visible"), GTK_RESPONSE_YES, GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE, NULL
+    );
+
+    gtk_container_set_border_width(GTK_CONTAINER(dialog), 6);
+    gtk_window_set_resizable(GTK_WINDOW(dialog), FALSE);
+    gtk_window_set_type_hint(GTK_WINDOW(dialog), GDK_WINDOW_TYPE_HINT_DIALOG);
+    gtk_dialog_set_has_separator(GTK_DIALOG(dialog), FALSE);
+
+    tableWidget = gtk_table_new(16, 3, FALSE);
+    gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), tableWidget, FALSE, FALSE, 0);
+
+    tempWidget = gtk_label_new(NULL);
+    gtk_label_set_markup(GTK_LABEL(tempWidget), _("<span weight=\"bold\">Translation</span>"));
+    gtk_misc_set_alignment(GTK_MISC(tempWidget), 0.0, 0.5);
+    gtk_table_attach((GtkTable*)tableWidget, tempWidget, 0, 2, 0, 1, GTK_EXPAND | GTK_FILL, 0, 0, 5);
+
+    tempWidget = gtk_label_new("");
+    gtk_table_attach((GtkTable*)tableWidget, tempWidget, 0, 1, 1, 2, GTK_EXPAND | GTK_FILL, 0, 0, 0);
+    gdouble translateX, translateY;
+
+    if (screenUnit == (gerbv_unit_t)GERBV_MILS) {
+        tempWidget  = gtk_label_new(_("X (mils):"));
+        tempWidget2 = gtk_label_new(_("Y (mils):"));
+        translateX  = trans->translateX * 1000;
+        translateY  = trans->translateY * 1000;
+    } else if (screen.unit == (gerbv_gui_unit_t)GERBV_MMS) {
+        tempWidget  = gtk_label_new(_("X (mm):"));
+        tempWidget2 = gtk_label_new(_("Y (mm):"));
+        translateX  = trans->translateX * 25.4;
+        translateY  = trans->translateY * 25.4;
+    } else {
+        tempWidget  = gtk_label_new(_("X (inches):"));
+        tempWidget2 = gtk_label_new(_("Y (inches):"));
+        translateX  = trans->translateX;
+        translateY  = trans->translateY;
+    }
 
-	gtk_misc_set_alignment (GTK_MISC (tempWidget), 0.0, 0.5);
-	gtk_table_attach ((GtkTable *) tableWidget, tempWidget,1,2,1,2,GTK_FILL,0,5,0);
-	gtk_misc_set_alignment (GTK_MISC (tempWidget2), 0.0, 0.5);
-	gtk_table_attach ((GtkTable *) tableWidget, tempWidget2,1,2,2,3,GTK_FILL,0,5,0);
-	adj = (GtkAdjustment *) gtk_adjustment_new (translateX, -1000000, 1000000, 1, 10, 0.0);
-	spin1 = (GtkWidget *) gtk_spin_button_new (adj, 0.1, 4);
-	gtk_table_attach ((GtkTable *) tableWidget, spin1,2,3,1,2,GTK_FILL,0,0,0);
-	adj = (GtkAdjustment *) gtk_adjustment_new (translateY, -1000000, 1000000, 1, 10, 0.0);
-	spin2 = (GtkWidget *) gtk_spin_button_new (adj, 0.1, 4);
-	gtk_table_attach ((GtkTable *) tableWidget, spin2,2,3,2,3,GTK_FILL,0,0,0);
-
-	gtk_table_set_row_spacing ((GtkTable *) tableWidget, 3, 8);
-	tempWidget = gtk_label_new (NULL);
-	gtk_label_set_markup (GTK_LABEL (tempWidget), _("<span weight=\"bold\">Scale</span>"));
-	gtk_misc_set_alignment (GTK_MISC (tempWidget), 0.0, 0.5);
-	gtk_table_attach ((GtkTable *) tableWidget, tempWidget,0,2,4,5,GTK_EXPAND|GTK_FILL,0,0,5);
-
-	tempWidget = gtk_label_new (_("X direction:"));
-	gtk_misc_set_alignment (GTK_MISC (tempWidget), 0.0, 0.5);
-	gtk_table_attach ((GtkTable *) tableWidget, tempWidget,1,2,5,6,GTK_FILL,0,5,0);
-	tempWidget = gtk_label_new (_("Y direction:"));
-	gtk_misc_set_alignment (GTK_MISC (tempWidget), 0.0, 0.5);
-	gtk_table_attach ((GtkTable *) tableWidget, tempWidget,1,2,6,7,GTK_FILL,0,5,0);
-	adj = (GtkAdjustment *) gtk_adjustment_new (trans->scaleX, -1000000, 1000000, 1, 10, 0.0);
-	spin3 = (GtkWidget *) gtk_spin_button_new (adj, 1, 3);
-	gtk_table_attach ((GtkTable *) tableWidget, spin3,2,3,5,6,GTK_FILL,0,0,0);
-	adj = (GtkAdjustment *) gtk_adjustment_new (trans->scaleY, -1000000, 1000000, 1, 10, 0.0);
-	spin4 = (GtkWidget *) gtk_spin_button_new (adj, 1, 3);
-	gtk_table_attach ((GtkTable *) tableWidget, spin4,2,3,6,7,GTK_FILL,0,0,0);
+    gtk_misc_set_alignment(GTK_MISC(tempWidget), 0.0, 0.5);
+    gtk_table_attach((GtkTable*)tableWidget, tempWidget, 1, 2, 1, 2, GTK_FILL, 0, 5, 0);
+    gtk_misc_set_alignment(GTK_MISC(tempWidget2), 0.0, 0.5);
+    gtk_table_attach((GtkTable*)tableWidget, tempWidget2, 1, 2, 2, 3, GTK_FILL, 0, 5, 0);
+    adj   = (GtkAdjustment*)gtk_adjustment_new(translateX, -1000000, 1000000, 1, 10, 0.0);
+    spin1 = (GtkWidget*)gtk_spin_button_new(adj, 0.1, 4);
+    gtk_table_attach((GtkTable*)tableWidget, spin1, 2, 3, 1, 2, GTK_FILL, 0, 0, 0);
+    adj   = (GtkAdjustment*)gtk_adjustment_new(translateY, -1000000, 1000000, 1, 10, 0.0);
+    spin2 = (GtkWidget*)gtk_spin_button_new(adj, 0.1, 4);
+    gtk_table_attach((GtkTable*)tableWidget, spin2, 2, 3, 2, 3, GTK_FILL, 0, 0, 0);
+
+    gtk_table_set_row_spacing((GtkTable*)tableWidget, 3, 8);
+    tempWidget = gtk_label_new(NULL);
+    gtk_label_set_markup(GTK_LABEL(tempWidget), _("<span weight=\"bold\">Scale</span>"));
+    gtk_misc_set_alignment(GTK_MISC(tempWidget), 0.0, 0.5);
+    gtk_table_attach((GtkTable*)tableWidget, tempWidget, 0, 2, 4, 5, GTK_EXPAND | GTK_FILL, 0, 0, 5);
+
+    tempWidget = gtk_label_new(_("X direction:"));
+    gtk_misc_set_alignment(GTK_MISC(tempWidget), 0.0, 0.5);
+    gtk_table_attach((GtkTable*)tableWidget, tempWidget, 1, 2, 5, 6, GTK_FILL, 0, 5, 0);
+    tempWidget = gtk_label_new(_("Y direction:"));
+    gtk_misc_set_alignment(GTK_MISC(tempWidget), 0.0, 0.5);
+    gtk_table_attach((GtkTable*)tableWidget, tempWidget, 1, 2, 6, 7, GTK_FILL, 0, 5, 0);
+    adj   = (GtkAdjustment*)gtk_adjustment_new(trans->scaleX, -1000000, 1000000, 1, 10, 0.0);
+    spin3 = (GtkWidget*)gtk_spin_button_new(adj, 1, 3);
+    gtk_table_attach((GtkTable*)tableWidget, spin3, 2, 3, 5, 6, GTK_FILL, 0, 0, 0);
+    adj   = (GtkAdjustment*)gtk_adjustment_new(trans->scaleY, -1000000, 1000000, 1, 10, 0.0);
+    spin4 = (GtkWidget*)gtk_spin_button_new(adj, 1, 3);
+    gtk_table_attach((GtkTable*)tableWidget, spin4, 2, 3, 6, 7, GTK_FILL, 0, 0, 0);
 
     check3 = gtk_check_button_new_with_label("Maintain aspect ratio");
-    gtk_toggle_button_set_active((GtkToggleButton *) check3, TRUE);
-    gtk_table_attach((GtkTable *)tableWidget, check3, 2, 3, 7, 8, GTK_FILL, 0, 0, 0);
-
-	gtk_table_set_row_spacing ((GtkTable *) tableWidget, 8, 8);
-
-	tempWidget = gtk_label_new (NULL);
-	gtk_label_set_markup (GTK_LABEL (tempWidget), _("<span weight=\"bold\">Rotation</span>"));
-	gtk_misc_set_alignment (GTK_MISC (tempWidget), 0.0, 0.5);
-	gtk_table_attach ((GtkTable *) tableWidget, tempWidget,0,2,9,10,GTK_EXPAND|GTK_FILL,0,0,5);
-
-	tempWidget = gtk_label_new (_("Rotation (degrees):"));
-	gtk_misc_set_alignment (GTK_MISC (tempWidget), 0.0, 0.5);
-	gtk_table_attach ((GtkTable *) tableWidget, tempWidget,1,2,10,11,GTK_FILL,0,5,0);
-	spin5 = gtk_combo_box_new_text();
-	gtk_combo_box_append_text (GTK_COMBO_BOX(spin5), _("None"));
-	gtk_combo_box_append_text (GTK_COMBO_BOX(spin5), _("90 deg CCW"));
-	gtk_combo_box_append_text (GTK_COMBO_BOX(spin5), _("180 deg CCW"));
-	gtk_combo_box_append_text (GTK_COMBO_BOX(spin5), _("270 deg CCW"));
-	gdouble rot_deg = RAD2DEG(trans->rotation);
-	if (rot_deg < 135 && rot_deg >= 45)
-		gtk_combo_box_set_active (GTK_COMBO_BOX(spin5), 1);
-	else if (rot_deg < 225 && rot_deg >= 135)
-		gtk_combo_box_set_active (GTK_COMBO_BOX(spin5), 2);
-	else if (rot_deg < 315 && rot_deg >= 225)
-		gtk_combo_box_set_active (GTK_COMBO_BOX(spin5), 3);
-	else
-		gtk_combo_box_set_active (GTK_COMBO_BOX(spin5), 0);
+    gtk_toggle_button_set_active((GtkToggleButton*)check3, TRUE);
+    gtk_table_attach((GtkTable*)tableWidget, check3, 2, 3, 7, 8, GTK_FILL, 0, 0, 0);
+
+    gtk_table_set_row_spacing((GtkTable*)tableWidget, 8, 8);
+
+    tempWidget = gtk_label_new(NULL);
+    gtk_label_set_markup(GTK_LABEL(tempWidget), _("<span weight=\"bold\">Rotation</span>"));
+    gtk_misc_set_alignment(GTK_MISC(tempWidget), 0.0, 0.5);
+    gtk_table_attach((GtkTable*)tableWidget, tempWidget, 0, 2, 9, 10, GTK_EXPAND | GTK_FILL, 0, 0, 5);
+
+    tempWidget = gtk_label_new(_("Rotation (degrees):"));
+    gtk_misc_set_alignment(GTK_MISC(tempWidget), 0.0, 0.5);
+    gtk_table_attach((GtkTable*)tableWidget, tempWidget, 1, 2, 10, 11, GTK_FILL, 0, 5, 0);
+    spin5 = gtk_combo_box_new_text();
+    gtk_combo_box_append_text(GTK_COMBO_BOX(spin5), _("None"));
+    gtk_combo_box_append_text(GTK_COMBO_BOX(spin5), _("90 deg CCW"));
+    gtk_combo_box_append_text(GTK_COMBO_BOX(spin5), _("180 deg CCW"));
+    gtk_combo_box_append_text(GTK_COMBO_BOX(spin5), _("270 deg CCW"));
+    gdouble rot_deg = RAD2DEG(trans->rotation);
+    if (rot_deg < 135 && rot_deg >= 45)
+        gtk_combo_box_set_active(GTK_COMBO_BOX(spin5), 1);
+    else if (rot_deg < 225 && rot_deg >= 135)
+        gtk_combo_box_set_active(GTK_COMBO_BOX(spin5), 2);
+    else if (rot_deg < 315 && rot_deg >= 225)
+        gtk_combo_box_set_active(GTK_COMBO_BOX(spin5), 3);
+    else
+        gtk_combo_box_set_active(GTK_COMBO_BOX(spin5), 0);
 #if 0
 	adj = (GtkAdjustment *) gtk_adjustment_new (RAD2DEG(trans->rotation), -1000000, 1000000,
 		1, 10, 0.0);
 	spin5 = (GtkWidget *) gtk_spin_button_new (adj, 0, 3);
 #endif
 
-	gtk_table_attach ((GtkTable *) tableWidget, spin5,2,3,10,11,GTK_FILL,0,0,0);
-
-	gtk_table_set_row_spacing ((GtkTable *) tableWidget, 10, 8);
-	tempWidget = gtk_label_new (NULL);
-	gtk_label_set_markup (GTK_LABEL (tempWidget), _("<span weight=\"bold\">Mirroring</span>"));
-	gtk_misc_set_alignment (GTK_MISC (tempWidget), 0.0, 0.5);
-	gtk_table_attach ((GtkTable *) tableWidget, tempWidget,0,2,11,12,GTK_EXPAND|GTK_FILL,0,0,5);
-
-	tempWidget = gtk_label_new (_("About X axis:"));
-	gtk_misc_set_alignment (GTK_MISC (tempWidget), 1.0, 0.5);
-	gtk_table_attach ((GtkTable *) tableWidget, tempWidget,1,2,12,13,GTK_FILL,0,5,0);
-	check1 = (GtkWidget *) gtk_check_button_new ();
-	gtk_toggle_button_set_active ((GtkToggleButton *) check1, trans->mirrorAroundX);
-	gtk_table_attach ((GtkTable *) tableWidget, check1,2,3,12,13,0,0,0,2);
-
-	tempWidget = gtk_label_new (_("About Y axis:"));
-	gtk_misc_set_alignment (GTK_MISC (tempWidget), 1.0, 0.5);
-	gtk_table_attach ((GtkTable *) tableWidget, tempWidget,1,2,13,14,GTK_FILL,0,5,0);
-	check2 = (GtkWidget *) gtk_check_button_new ();
-	gtk_toggle_button_set_active ((GtkToggleButton *) check2, trans->mirrorAroundY);
-	gtk_table_attach ((GtkTable *) tableWidget, check2,2,3,13,14,0,0,0,2);
-
-	for (i = 0; focus_widgets[i] != NULL; i++) {
-		/* Set stored focus */
-		if (i == focused_widget_num) {
-			gtk_widget_grab_focus (*focus_widgets[i]);
-		}
-
-		/* Set focus-in-event callback */
-		focus_nums[i] = i;
-		g_signal_connect_swapped ((gpointer)(*focus_widgets[i]), "focus-in-event",
-			G_CALLBACK (focus_in_event_callback), (gpointer)(focus_nums + i));
-	}
+    gtk_table_attach((GtkTable*)tableWidget, spin5, 2, 3, 10, 11, GTK_FILL, 0, 0, 0);
+
+    gtk_table_set_row_spacing((GtkTable*)tableWidget, 10, 8);
+    tempWidget = gtk_label_new(NULL);
+    gtk_label_set_markup(GTK_LABEL(tempWidget), _("<span weight=\"bold\">Mirroring</span>"));
+    gtk_misc_set_alignment(GTK_MISC(tempWidget), 0.0, 0.5);
+    gtk_table_attach((GtkTable*)tableWidget, tempWidget, 0, 2, 11, 12, GTK_EXPAND | GTK_FILL, 0, 0, 5);
+
+    tempWidget = gtk_label_new(_("About X axis:"));
+    gtk_misc_set_alignment(GTK_MISC(tempWidget), 1.0, 0.5);
+    gtk_table_attach((GtkTable*)tableWidget, tempWidget, 1, 2, 12, 13, GTK_FILL, 0, 5, 0);
+    check1 = (GtkWidget*)gtk_check_button_new();
+    gtk_toggle_button_set_active((GtkToggleButton*)check1, trans->mirrorAroundX);
+    gtk_table_attach((GtkTable*)tableWidget, check1, 2, 3, 12, 13, 0, 0, 0, 2);
+
+    tempWidget = gtk_label_new(_("About Y axis:"));
+    gtk_misc_set_alignment(GTK_MISC(tempWidget), 1.0, 0.5);
+    gtk_table_attach((GtkTable*)tableWidget, tempWidget, 1, 2, 13, 14, GTK_FILL, 0, 5, 0);
+    check2 = (GtkWidget*)gtk_check_button_new();
+    gtk_toggle_button_set_active((GtkToggleButton*)check2, trans->mirrorAroundY);
+    gtk_table_attach((GtkTable*)tableWidget, check2, 2, 3, 13, 14, 0, 0, 0, 2);
+
+    for (i = 0; focus_widgets[i] != NULL; i++) {
+        /* Set stored focus */
+        if (i == focused_widget_num) {
+            gtk_widget_grab_focus(*focus_widgets[i]);
+        }
+
+        /* Set focus-in-event callback */
+        focus_nums[i] = i;
+        g_signal_connect_swapped(
+            (gpointer)(*focus_widgets[i]), "focus-in-event", G_CALLBACK(focus_in_event_callback),
+            (gpointer)(focus_nums + i)
+        );
+    }
 
-	g_signal_connect(GTK_OBJECT(spin1), "value_changed", 
-                     GTK_SIGNAL_FUNC(callbacks_live_edit), spin1);
-	g_signal_connect(GTK_OBJECT(spin2), "value_changed", 
-                     GTK_SIGNAL_FUNC(callbacks_live_edit), spin2);
-	g_signal_connect(GTK_OBJECT(spin3), "value_changed",
-					 GTK_SIGNAL_FUNC(callbacks_live_edit), spin3);
-	g_signal_connect(GTK_OBJECT(spin4), "value_changed",
-					 GTK_SIGNAL_FUNC(callbacks_live_edit), spin4);
-	g_signal_connect(GTK_OBJECT(spin5), "changed",
-					 GTK_SIGNAL_FUNC(callbacks_live_edit), spin5);
-	g_signal_connect(GTK_OBJECT(check1), "toggled",
-					 GTK_SIGNAL_FUNC(callbacks_live_edit), check1);
-	g_signal_connect(GTK_OBJECT(check2), "toggled",
-					 GTK_SIGNAL_FUNC(callbacks_live_edit), check2);
-
-	gtk_table_set_row_spacing ((GtkTable *) tableWidget, 14, 8);
-	gtk_widget_show_all (dialog);
-	gint result = GTK_RESPONSE_APPLY;
-
-	/* Each time the user selects "apply" or "apply to all", update the
-	 * screen and re-enter the dialog loop */
-	while (result == GTK_RESPONSE_APPLY || result == GTK_RESPONSE_YES) {
-		result = gtk_dialog_run (GTK_DIALOG(dialog));
-		if (result != GTK_RESPONSE_CLOSE) {
-			/* Extract all the parameters */
-			if (screenUnit == (gerbv_unit_t) GERBV_MILS) {
-				trans->translateX = gtk_spin_button_get_value ((GtkSpinButton *) spin1)/
-					1000;
-				trans->translateY = gtk_spin_button_get_value ((GtkSpinButton *) spin2)/
-					1000;
-			} else if (screen.unit == (gerbv_gui_unit_t) GERBV_MMS) {
-				trans->translateX = gtk_spin_button_get_value ((GtkSpinButton *) spin1)/
-					25.4;
-				trans->translateY = gtk_spin_button_get_value ((GtkSpinButton *) spin2)/
-					25.4;
-			} else {
-				trans->translateX = gtk_spin_button_get_value ((GtkSpinButton *) spin1);
-				trans->translateY = gtk_spin_button_get_value ((GtkSpinButton *) spin2);
-			}
+    g_signal_connect(GTK_OBJECT(spin1), "value_changed", GTK_SIGNAL_FUNC(callbacks_live_edit), spin1);
+    g_signal_connect(GTK_OBJECT(spin2), "value_changed", GTK_SIGNAL_FUNC(callbacks_live_edit), spin2);
+    g_signal_connect(GTK_OBJECT(spin3), "value_changed", GTK_SIGNAL_FUNC(callbacks_live_edit), spin3);
+    g_signal_connect(GTK_OBJECT(spin4), "value_changed", GTK_SIGNAL_FUNC(callbacks_live_edit), spin4);
+    g_signal_connect(GTK_OBJECT(spin5), "changed", GTK_SIGNAL_FUNC(callbacks_live_edit), spin5);
+    g_signal_connect(GTK_OBJECT(check1), "toggled", GTK_SIGNAL_FUNC(callbacks_live_edit), check1);
+    g_signal_connect(GTK_OBJECT(check2), "toggled", GTK_SIGNAL_FUNC(callbacks_live_edit), check2);
+
+    gtk_table_set_row_spacing((GtkTable*)tableWidget, 14, 8);
+    gtk_widget_show_all(dialog);
+    gint result = GTK_RESPONSE_APPLY;
+
+    /* Each time the user selects "apply" or "apply to all", update the
+     * screen and re-enter the dialog loop */
+    while (result == GTK_RESPONSE_APPLY || result == GTK_RESPONSE_YES) {
+        result = gtk_dialog_run(GTK_DIALOG(dialog));
+        if (result != GTK_RESPONSE_CLOSE) {
+            /* Extract all the parameters */
+            if (screenUnit == (gerbv_unit_t)GERBV_MILS) {
+                trans->translateX = gtk_spin_button_get_value((GtkSpinButton*)spin1) / 1000;
+                trans->translateY = gtk_spin_button_get_value((GtkSpinButton*)spin2) / 1000;
+            } else if (screen.unit == (gerbv_gui_unit_t)GERBV_MMS) {
+                trans->translateX = gtk_spin_button_get_value((GtkSpinButton*)spin1) / 25.4;
+                trans->translateY = gtk_spin_button_get_value((GtkSpinButton*)spin2) / 25.4;
+            } else {
+                trans->translateX = gtk_spin_button_get_value((GtkSpinButton*)spin1);
+                trans->translateY = gtk_spin_button_get_value((GtkSpinButton*)spin2);
+            }
 
             /* Maintain Aspect Ratio? */
-            if (gtk_toggle_button_get_active((GtkToggleButton *) check3)){
-                if (trans->scaleX != gtk_spin_button_get_value ((GtkSpinButton *)spin3)){
-                    gtk_spin_button_set_value((GtkSpinButton *)spin4,
-                                              gtk_spin_button_get_value ((GtkSpinButton *)spin3));
-				}
-				
-				if (trans->scaleY != gtk_spin_button_get_value ((GtkSpinButton *)spin4)){
-					gtk_spin_button_set_value((GtkSpinButton *)spin3,
-											  gtk_spin_button_get_value ((GtkSpinButton *)spin4));
-				}
-			}
-
-			trans->scaleX = gtk_spin_button_get_value ((GtkSpinButton *)spin3);
-			trans->scaleY = gtk_spin_button_get_value ((GtkSpinButton *)spin4);
-			gint rotationIndex = gtk_combo_box_get_active ((GtkComboBox *)spin5);
-
-			if (rotationIndex == 0)
-				trans->rotation = 0;
-			else if (rotationIndex == 1)
-				trans->rotation = M_PI_2;
-			else if (rotationIndex == 2)
-				trans->rotation = M_PI;
-			else if (rotationIndex == 3)
-				trans->rotation = M_PI + M_PI_2;
-
-			trans->mirrorAroundX = gtk_toggle_button_get_active ((GtkToggleButton *) check1);
-			trans->mirrorAroundY = gtk_toggle_button_get_active ((GtkToggleButton *) check2);
-
-			if (result == GTK_RESPONSE_APPLY) {
-				/* Apply to selected layer */
-				*transforms[0] = *trans;
-			} else if (result == GTK_RESPONSE_YES) {
-				/* Apply to all visible layers (but not selected one) */
-				i = 1;
-				while (transforms[i] != NULL) {
-					*transforms[i++] = *trans;
-				}
-			}
-
-			render_refresh_rendered_image_on_screen ();
-			callbacks_update_layer_tree ();
-		}
-	}
+            if (gtk_toggle_button_get_active((GtkToggleButton*)check3)) {
+                if (trans->scaleX != gtk_spin_button_get_value((GtkSpinButton*)spin3)) {
+                    gtk_spin_button_set_value((GtkSpinButton*)spin4, gtk_spin_button_get_value((GtkSpinButton*)spin3));
+                }
+
+                if (trans->scaleY != gtk_spin_button_get_value((GtkSpinButton*)spin4)) {
+                    gtk_spin_button_set_value((GtkSpinButton*)spin3, gtk_spin_button_get_value((GtkSpinButton*)spin4));
+                }
+            }
+
+            trans->scaleX      = gtk_spin_button_get_value((GtkSpinButton*)spin3);
+            trans->scaleY      = gtk_spin_button_get_value((GtkSpinButton*)spin4);
+            gint rotationIndex = gtk_combo_box_get_active((GtkComboBox*)spin5);
+
+            if (rotationIndex == 0)
+                trans->rotation = 0;
+            else if (rotationIndex == 1)
+                trans->rotation = M_PI_2;
+            else if (rotationIndex == 2)
+                trans->rotation = M_PI;
+            else if (rotationIndex == 3)
+                trans->rotation = M_PI + M_PI_2;
+
+            trans->mirrorAroundX = gtk_toggle_button_get_active((GtkToggleButton*)check1);
+            trans->mirrorAroundY = gtk_toggle_button_get_active((GtkToggleButton*)check2);
+
+            if (result == GTK_RESPONSE_APPLY) {
+                /* Apply to selected layer */
+                *transforms[0] = *trans;
+            } else if (result == GTK_RESPONSE_YES) {
+                /* Apply to all visible layers (but not selected one) */
+                i = 1;
+                while (transforms[i] != NULL) {
+                    *transforms[i++] = *trans;
+                }
+            }
+
+            render_refresh_rendered_image_on_screen();
+            callbacks_update_layer_tree();
+        }
+    }
 #if 0
 	/* TODO: restore from backup array */
 	if (result == GTK_RESPONSE_CANCEL) {
@@ -2565,8 +2414,7 @@ gerbv_user_transformation_t startTransform = trans;
 	}
 #endif
 
-	gtk_widget_destroy (dialog);
+    gtk_widget_destroy(dialog);
 
-	return;
+    return;
 }
-
diff --git a/src/interface.h b/src/interface.h
index ec41759..9134db5 100644
--- a/src/interface.h
+++ b/src/interface.h
@@ -33,183 +33,169 @@ Otherwise the defaults given below are used.
 
 \warning There has to be a GtkStockItem variable 'stock' in scope where this macro is used.
 */
-#define SET_ACCELS_FROM_STOCK(MENU_ITEM, STOCK_ID, GERBV_ACCEL_ID)\
-gtk_menu_item_set_accel_path (GTK_MENU_ITEM (MENU_ITEM), GERBV_ACCEL_ID ## _PATH);\
-if(gtk_stock_lookup (STOCK_ID, &stock) && stock.keyval != GDK_VoidSymbol && stock.keyval != 0)\
-	gtk_accel_map_add_entry (GERBV_ACCEL_ID ## _PATH, stock.keyval, stock.modifier);\
-else\
-	gtk_accel_map_add_entry (GERBV_ACCEL_ID ## _PATH, GERBV_ACCEL_ID ## _KEY, GERBV_ACCEL_ID ## _MOD)
+#define SET_ACCELS_FROM_STOCK(MENU_ITEM, STOCK_ID, GERBV_ACCEL_ID)                                 \
+    gtk_menu_item_set_accel_path(GTK_MENU_ITEM(MENU_ITEM), GERBV_ACCEL_ID##_PATH);                 \
+    if (gtk_stock_lookup(STOCK_ID, &stock) && stock.keyval != GDK_VoidSymbol && stock.keyval != 0) \
+        gtk_accel_map_add_entry(GERBV_ACCEL_ID##_PATH, stock.keyval, stock.modifier);              \
+    else                                                                                           \
+        gtk_accel_map_add_entry(GERBV_ACCEL_ID##_PATH, GERBV_ACCEL_ID##_KEY, GERBV_ACCEL_ID##_MOD)
 
-#define SET_ACCELS(MENU_ITEM, GERBV_ACCEL_ID)\
-	gtk_menu_item_set_accel_path (GTK_MENU_ITEM (MENU_ITEM), GERBV_ACCEL_ID ## _PATH);\
-	gtk_accel_map_add_entry (GERBV_ACCEL_ID ## _PATH, GERBV_ACCEL_ID ## _KEY, GERBV_ACCEL_ID ## _MOD)
+#define SET_ACCELS(MENU_ITEM, GERBV_ACCEL_ID)                                      \
+    gtk_menu_item_set_accel_path(GTK_MENU_ITEM(MENU_ITEM), GERBV_ACCEL_ID##_PATH); \
+    gtk_accel_map_add_entry(GERBV_ACCEL_ID##_PATH, GERBV_ACCEL_ID##_KEY, GERBV_ACCEL_ID##_MOD)
 
 /* If stock items/IDs are used the ACCEL_*_PATH macros have to match the labels of the stock items.
 Otherwise the (persistent) accelerators are broken. One workaround would be to look the labels up. */
-#define GERBV_ACCELS_RELPATH ".gEDA/gerbv/accels"
-#define ACCEL_ROOT				"<main>/"
-#define ACCEL_FILE				ACCEL_ROOT "file"
-#define ACCEL_FILE_NEW_PATH			ACCEL_FILE "/New"
-#define ACCEL_FILE_NEW_KEY			GDK_n
-#define ACCEL_FILE_NEW_MOD			(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_FILE_REVERT_PATH			ACCEL_FILE "/Revert"
-#define ACCEL_FILE_REVERT_KEY			GDK_F5
-#define ACCEL_FILE_REVERT_MOD			(GdkModifierType) 0
-#define ACCEL_FILE_OPEN_LAYER_PATH		ACCEL_FILE "/Open layer(s)..."
-#define ACCEL_FILE_OPEN_LAYER_KEY		GDK_O
-#define ACCEL_FILE_OPEN_LAYER_MOD		(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_FILE_SAVE_LAYER_PATH		ACCEL_FILE "/Save active layer"
-#define ACCEL_FILE_SAVE_LAYER_KEY		GDK_S
-#define ACCEL_FILE_SAVE_LAYER_MOD		(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_FILE_SAVE_LAYER_AS_PATH		ACCEL_FILE "/Save active layer as..."
-#define ACCEL_FILE_SAVE_LAYER_AS_KEY		GDK_A
-#define ACCEL_FILE_SAVE_LAYER_AS_MOD		(GdkModifierType) GDK_CONTROL_MASK | GDK_SHIFT_MASK
-#define ACCEL_FILE_EXPORT			ACCEL_FILE "/Export"
-#define ACCEL_FILE_PRINT_PATH			ACCEL_FILE "/Print..."
-#define ACCEL_FILE_PRINT_KEY			GDK_P
-#define ACCEL_FILE_PRINT_MOD			(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_FILE_QUIT_PATH			ACCEL_FILE "/Quit"
-#define ACCEL_FILE_QUIT_KEY			GDK_Q
-#define ACCEL_FILE_QUIT_MOD			(GdkModifierType) GDK_CONTROL_MASK
-
-#define ACCEL_EDIT				ACCEL_ROOT "edit"
-#define ACCEL_EDIT_PROPERTIES_PATH		ACCEL_EDIT "/Display properties of selected object(s)"
-#define ACCEL_EDIT_PROPERTIES_KEY		GDK_Return
-#define ACCEL_EDIT_PROPERTIES_MOD		(GdkModifierType) GDK_MOD1_MASK
-#define ACCEL_EDIT_DELETE_PATH			ACCEL_EDIT "/Delete selected object(s)"
-#define ACCEL_EDIT_DELETE_KEY			GDK_Delete
-#define ACCEL_EDIT_DELETE_MOD			(GdkModifierType) 0
-
-#define ACCEL_VIEW				ACCEL_ROOT "view"
-#define ACCEL_VIEW_FULLSCREEN_PATH		ACCEL_VIEW "/Fullscreen"
-#define ACCEL_VIEW_FULLSCREEN_KEY		GDK_F11
-#define ACCEL_VIEW_FULLSCREEN_MOD		(GdkModifierType) 0
-#define ACCEL_VIEW_TOOLBAR_PATH			ACCEL_VIEW "/Show Toolbar"
-#define ACCEL_VIEW_TOOLBAR_KEY			GDK_F7
-#define ACCEL_VIEW_TOOLBAR_MOD			(GdkModifierType) 0
-#define ACCEL_VIEW_SIDEPANE_PATH		ACCEL_VIEW "/Show Sidepane"
-#define ACCEL_VIEW_SIDEPANE_KEY			GDK_F9
-#define ACCEL_VIEW_SIDEPANE_MOD			(GdkModifierType) 0
-#define ACCEL_VIEW_ALL_SELECTION_PATH		ACCEL_VIEW "/Show all selection"
-#define ACCEL_VIEW_ALL_SELECTION_KEY		GDK_l
-#define ACCEL_VIEW_ALL_SELECTION_MOD		(GdkModifierType) 0
-#define ACCEL_VIEW_CROSS_ON_DRILL_HOLES_PATH	ACCEL_VIEW "/Show cross on drill holes"
-#define ACCEL_VIEW_CROSS_ON_DRILL_HOLES_KEY	GDK_x
-#define ACCEL_VIEW_CROSS_ON_DRILL_HOLES_MOD	(GdkModifierType) 0
-#define ACCEL_VIEW_VIS				ACCEL_VIEW "/Toggle layer visibilty"
-#define ACCEL_VIEW_VIS_LAYER1_PATH		ACCEL_VIEW_VIS "/Toggle visibility of layer 1"
-#define ACCEL_VIEW_VIS_LAYER1_KEY		GDK_1
-#define ACCEL_VIEW_VIS_LAYER1_MOD		(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_VIEW_VIS_LAYER2_PATH		ACCEL_VIEW_VIS "/Toggle visibility of layer 2"
-#define ACCEL_VIEW_VIS_LAYER2_KEY		GDK_2
-#define ACCEL_VIEW_VIS_LAYER2_MOD		(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_VIEW_VIS_LAYER3_PATH		ACCEL_VIEW_VIS "/Toggle visibility of layer 3"
-#define ACCEL_VIEW_VIS_LAYER3_KEY		GDK_3
-#define ACCEL_VIEW_VIS_LAYER3_MOD		(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_VIEW_VIS_LAYER4_PATH		ACCEL_VIEW_VIS "/Toggle visibility of layer 4"
-#define ACCEL_VIEW_VIS_LAYER4_KEY		GDK_4
-#define ACCEL_VIEW_VIS_LAYER4_MOD		(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_VIEW_VIS_LAYER5_PATH		ACCEL_VIEW_VIS "/Toggle visibility of layer 5"
-#define ACCEL_VIEW_VIS_LAYER5_KEY		GDK_5
-#define ACCEL_VIEW_VIS_LAYER5_MOD		(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_VIEW_VIS_LAYER6_PATH		ACCEL_VIEW_VIS "/Toggle visibility of layer 6"
-#define ACCEL_VIEW_VIS_LAYER6_KEY		GDK_6
-#define ACCEL_VIEW_VIS_LAYER6_MOD		(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_VIEW_VIS_LAYER7_PATH		ACCEL_VIEW_VIS "/Toggle visibility of layer 7"
-#define ACCEL_VIEW_VIS_LAYER7_KEY		GDK_7
-#define ACCEL_VIEW_VIS_LAYER7_MOD		(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_VIEW_VIS_LAYER8_PATH		ACCEL_VIEW_VIS "/Toggle visibility of layer 8"
-#define ACCEL_VIEW_VIS_LAYER8_KEY		GDK_8
-#define ACCEL_VIEW_VIS_LAYER8_MOD		(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_VIEW_VIS_LAYER9_PATH		ACCEL_VIEW_VIS "/Toggle visibility of layer 9"
-#define ACCEL_VIEW_VIS_LAYER9_KEY		GDK_9
-#define ACCEL_VIEW_VIS_LAYER9_MOD		(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_VIEW_VIS_LAYER10_PATH		ACCEL_VIEW_VIS "/Toggle visibility of layer 10"
-#define ACCEL_VIEW_VIS_LAYER10_KEY		GDK_0
-#define ACCEL_VIEW_VIS_LAYER10_MOD		(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_VIEW_ZOOM_IN_PATH			ACCEL_VIEW "/Zoom In"
-#define ACCEL_VIEW_ZOOM_IN_KEY			GDK_z
-#define ACCEL_VIEW_ZOOM_IN_MOD			(GdkModifierType) 0
-#define ACCEL_VIEW_ZOOM_OUT_PATH		ACCEL_VIEW "/Zoom Out"
-#define ACCEL_VIEW_ZOOM_OUT_KEY			GDK_z
-#define ACCEL_VIEW_ZOOM_OUT_MOD			(GdkModifierType) GDK_SHIFT_MASK
-#define ACCEL_VIEW_ZOOM_FIT_PATH		ACCEL_VIEW "/Best Fit"
-#define ACCEL_VIEW_ZOOM_FIT_KEY			GDK_f
-#define ACCEL_VIEW_ZOOM_FIT_MOD			(GdkModifierType) 0
-#define ACCEL_VIEW_RENDER			ACCEL_VIEW "/Rendering"
-#define ACCEL_VIEW_UNITS			ACCEL_VIEW "/Units"
-
-#define ACCEL_LAYER				ACCEL_ROOT "layer"
-#define ACCEL_LAYER_ALL_ON_PATH			ACCEL_LAYER "/All on"
-#define ACCEL_LAYER_ALL_ON_KEY			GDK_KP_Multiply
-#define ACCEL_LAYER_ALL_ON_MOD			(GdkModifierType) 0
-#define ACCEL_LAYER_ALL_OFF_PATH		ACCEL_LAYER "/All off"
-#define ACCEL_LAYER_ALL_OFF_KEY			GDK_KP_Divide
-#define ACCEL_LAYER_ALL_OFF_MOD			(GdkModifierType) 0
-#define ACCEL_LAYER_COLOR_PATH			ACCEL_LAYER "/Change color"
-#define ACCEL_LAYER_COLOR_KEY			GDK_F6
-#define ACCEL_LAYER_COLOR_MOD			(GdkModifierType) 0
-#define ACCEL_LAYER_UP_PATH			ACCEL_LAYER "/Move up"
-#define ACCEL_LAYER_UP_KEY			GDK_Up
-#define ACCEL_LAYER_UP_MOD			(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_LAYER_DOWN_PATH			ACCEL_LAYER "/Move down"
-#define ACCEL_LAYER_DOWN_KEY			GDK_Down
-#define ACCEL_LAYER_DOWN_MOD			(GdkModifierType) GDK_CONTROL_MASK
-#define ACCEL_LAYER_DELETE_PATH			ACCEL_LAYER "/Delete"
-#define ACCEL_LAYER_DELETE_KEY			GDK_Delete
-#define ACCEL_LAYER_DELETE_MOD			(GdkModifierType) GDK_CONTROL_MASK
-
-#define ACCEL_ANAL				ACCEL_ROOT "analyze"
-
-#define ACCEL_TOOLS				ACCEL_ROOT "tools"
-#define ACCEL_TOOLS_POINTER_PATH		ACCEL_TOOLS "/Pointer Tool"
-#define ACCEL_TOOLS_POINTER_KEY			GDK_1
-#define ACCEL_TOOLS_POINTER_MOD			(GdkModifierType) 0
-#define ACCEL_TOOLS_PAN_PATH			ACCEL_TOOLS "/Pan Tool"
-#define ACCEL_TOOLS_PAN_KEY			GDK_2
-#define ACCEL_TOOLS_PAN_MOD			(GdkModifierType) 0
-#define ACCEL_TOOLS_ZOOM_PATH			ACCEL_TOOLS "/Zoom Tool"
-#define ACCEL_TOOLS_ZOOM_KEY			GDK_3
-#define ACCEL_TOOLS_ZOOM_MOD			(GdkModifierType) 0
-#define ACCEL_TOOLS_MEASURE_PATH		ACCEL_TOOLS "/Measure Tool"
-#define ACCEL_TOOLS_MEASURE_KEY			GDK_4
-#define ACCEL_TOOLS_MEASURE_MOD			(GdkModifierType) 0
-
-#define ACCEL_HELP				ACCEL_ROOT "help"
-
-void
-interface_create_gui (int req_width, int req_height);
-
-void
-interface_set_render_type (int);
-
-void rename_main_window(char const* filename, GtkWidget* main_win);
-
-void
-set_window_icon (GtkWidget * this_window);
-
-gboolean
-interface_get_alert_dialog_response (const gchar *primaryText,
-				     const gchar *secondaryText,
-				     gboolean show_checkbox,
-				     gboolean *ask_to_show_again,
-				     const gchar *true_button_label,
-				     const gchar *false_button_label);
-
-int
-interface_reopen_question (GSList *filename,
-			   GSList *is_modified,
-			   GSList *files_counter,
-			   GSList *layer_number);
-
-void
-interface_show_alert_dialog (gchar *primaryText,
-			     gchar *secondaryText,
-			     gboolean show_checkbox,
-			     gboolean *ask_to_show_again);
+#define GERBV_ACCELS_RELPATH          ".gEDA/gerbv/accels"
+#define ACCEL_ROOT                    "<main>/"
+#define ACCEL_FILE                    ACCEL_ROOT "file"
+#define ACCEL_FILE_NEW_PATH           ACCEL_FILE "/New"
+#define ACCEL_FILE_NEW_KEY            GDK_n
+#define ACCEL_FILE_NEW_MOD            (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_FILE_REVERT_PATH        ACCEL_FILE "/Revert"
+#define ACCEL_FILE_REVERT_KEY         GDK_F5
+#define ACCEL_FILE_REVERT_MOD         (GdkModifierType)0
+#define ACCEL_FILE_OPEN_LAYER_PATH    ACCEL_FILE "/Open layer(s)..."
+#define ACCEL_FILE_OPEN_LAYER_KEY     GDK_O
+#define ACCEL_FILE_OPEN_LAYER_MOD     (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_FILE_SAVE_LAYER_PATH    ACCEL_FILE "/Save active layer"
+#define ACCEL_FILE_SAVE_LAYER_KEY     GDK_S
+#define ACCEL_FILE_SAVE_LAYER_MOD     (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_FILE_SAVE_LAYER_AS_PATH ACCEL_FILE "/Save active layer as..."
+#define ACCEL_FILE_SAVE_LAYER_AS_KEY  GDK_A
+#define ACCEL_FILE_SAVE_LAYER_AS_MOD  (GdkModifierType) GDK_CONTROL_MASK | GDK_SHIFT_MASK
+#define ACCEL_FILE_EXPORT             ACCEL_FILE "/Export"
+#define ACCEL_FILE_PRINT_PATH         ACCEL_FILE "/Print..."
+#define ACCEL_FILE_PRINT_KEY          GDK_P
+#define ACCEL_FILE_PRINT_MOD          (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_FILE_QUIT_PATH          ACCEL_FILE "/Quit"
+#define ACCEL_FILE_QUIT_KEY           GDK_Q
+#define ACCEL_FILE_QUIT_MOD           (GdkModifierType) GDK_CONTROL_MASK
+
+#define ACCEL_EDIT                 ACCEL_ROOT "edit"
+#define ACCEL_EDIT_PROPERTIES_PATH ACCEL_EDIT "/Display properties of selected object(s)"
+#define ACCEL_EDIT_PROPERTIES_KEY  GDK_Return
+#define ACCEL_EDIT_PROPERTIES_MOD  (GdkModifierType) GDK_MOD1_MASK
+#define ACCEL_EDIT_DELETE_PATH     ACCEL_EDIT "/Delete selected object(s)"
+#define ACCEL_EDIT_DELETE_KEY      GDK_Delete
+#define ACCEL_EDIT_DELETE_MOD      (GdkModifierType)0
+
+#define ACCEL_VIEW                           ACCEL_ROOT "view"
+#define ACCEL_VIEW_FULLSCREEN_PATH           ACCEL_VIEW "/Fullscreen"
+#define ACCEL_VIEW_FULLSCREEN_KEY            GDK_F11
+#define ACCEL_VIEW_FULLSCREEN_MOD            (GdkModifierType)0
+#define ACCEL_VIEW_TOOLBAR_PATH              ACCEL_VIEW "/Show Toolbar"
+#define ACCEL_VIEW_TOOLBAR_KEY               GDK_F7
+#define ACCEL_VIEW_TOOLBAR_MOD               (GdkModifierType)0
+#define ACCEL_VIEW_SIDEPANE_PATH             ACCEL_VIEW "/Show Sidepane"
+#define ACCEL_VIEW_SIDEPANE_KEY              GDK_F9
+#define ACCEL_VIEW_SIDEPANE_MOD              (GdkModifierType)0
+#define ACCEL_VIEW_ALL_SELECTION_PATH        ACCEL_VIEW "/Show all selection"
+#define ACCEL_VIEW_ALL_SELECTION_KEY         GDK_l
+#define ACCEL_VIEW_ALL_SELECTION_MOD         (GdkModifierType)0
+#define ACCEL_VIEW_CROSS_ON_DRILL_HOLES_PATH ACCEL_VIEW "/Show cross on drill holes"
+#define ACCEL_VIEW_CROSS_ON_DRILL_HOLES_KEY  GDK_x
+#define ACCEL_VIEW_CROSS_ON_DRILL_HOLES_MOD  (GdkModifierType)0
+#define ACCEL_VIEW_VIS                       ACCEL_VIEW "/Toggle layer visibilty"
+#define ACCEL_VIEW_VIS_LAYER1_PATH           ACCEL_VIEW_VIS "/Toggle visibility of layer 1"
+#define ACCEL_VIEW_VIS_LAYER1_KEY            GDK_1
+#define ACCEL_VIEW_VIS_LAYER1_MOD            (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_VIEW_VIS_LAYER2_PATH           ACCEL_VIEW_VIS "/Toggle visibility of layer 2"
+#define ACCEL_VIEW_VIS_LAYER2_KEY            GDK_2
+#define ACCEL_VIEW_VIS_LAYER2_MOD            (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_VIEW_VIS_LAYER3_PATH           ACCEL_VIEW_VIS "/Toggle visibility of layer 3"
+#define ACCEL_VIEW_VIS_LAYER3_KEY            GDK_3
+#define ACCEL_VIEW_VIS_LAYER3_MOD            (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_VIEW_VIS_LAYER4_PATH           ACCEL_VIEW_VIS "/Toggle visibility of layer 4"
+#define ACCEL_VIEW_VIS_LAYER4_KEY            GDK_4
+#define ACCEL_VIEW_VIS_LAYER4_MOD            (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_VIEW_VIS_LAYER5_PATH           ACCEL_VIEW_VIS "/Toggle visibility of layer 5"
+#define ACCEL_VIEW_VIS_LAYER5_KEY            GDK_5
+#define ACCEL_VIEW_VIS_LAYER5_MOD            (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_VIEW_VIS_LAYER6_PATH           ACCEL_VIEW_VIS "/Toggle visibility of layer 6"
+#define ACCEL_VIEW_VIS_LAYER6_KEY            GDK_6
+#define ACCEL_VIEW_VIS_LAYER6_MOD            (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_VIEW_VIS_LAYER7_PATH           ACCEL_VIEW_VIS "/Toggle visibility of layer 7"
+#define ACCEL_VIEW_VIS_LAYER7_KEY            GDK_7
+#define ACCEL_VIEW_VIS_LAYER7_MOD            (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_VIEW_VIS_LAYER8_PATH           ACCEL_VIEW_VIS "/Toggle visibility of layer 8"
+#define ACCEL_VIEW_VIS_LAYER8_KEY            GDK_8
+#define ACCEL_VIEW_VIS_LAYER8_MOD            (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_VIEW_VIS_LAYER9_PATH           ACCEL_VIEW_VIS "/Toggle visibility of layer 9"
+#define ACCEL_VIEW_VIS_LAYER9_KEY            GDK_9
+#define ACCEL_VIEW_VIS_LAYER9_MOD            (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_VIEW_VIS_LAYER10_PATH          ACCEL_VIEW_VIS "/Toggle visibility of layer 10"
+#define ACCEL_VIEW_VIS_LAYER10_KEY           GDK_0
+#define ACCEL_VIEW_VIS_LAYER10_MOD           (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_VIEW_ZOOM_IN_PATH              ACCEL_VIEW "/Zoom In"
+#define ACCEL_VIEW_ZOOM_IN_KEY               GDK_z
+#define ACCEL_VIEW_ZOOM_IN_MOD               (GdkModifierType)0
+#define ACCEL_VIEW_ZOOM_OUT_PATH             ACCEL_VIEW "/Zoom Out"
+#define ACCEL_VIEW_ZOOM_OUT_KEY              GDK_z
+#define ACCEL_VIEW_ZOOM_OUT_MOD              (GdkModifierType) GDK_SHIFT_MASK
+#define ACCEL_VIEW_ZOOM_FIT_PATH             ACCEL_VIEW "/Best Fit"
+#define ACCEL_VIEW_ZOOM_FIT_KEY              GDK_f
+#define ACCEL_VIEW_ZOOM_FIT_MOD              (GdkModifierType)0
+#define ACCEL_VIEW_RENDER                    ACCEL_VIEW "/Rendering"
+#define ACCEL_VIEW_UNITS                     ACCEL_VIEW "/Units"
+
+#define ACCEL_LAYER              ACCEL_ROOT "layer"
+#define ACCEL_LAYER_ALL_ON_PATH  ACCEL_LAYER "/All on"
+#define ACCEL_LAYER_ALL_ON_KEY   GDK_KP_Multiply
+#define ACCEL_LAYER_ALL_ON_MOD   (GdkModifierType)0
+#define ACCEL_LAYER_ALL_OFF_PATH ACCEL_LAYER "/All off"
+#define ACCEL_LAYER_ALL_OFF_KEY  GDK_KP_Divide
+#define ACCEL_LAYER_ALL_OFF_MOD  (GdkModifierType)0
+#define ACCEL_LAYER_COLOR_PATH   ACCEL_LAYER "/Change color"
+#define ACCEL_LAYER_COLOR_KEY    GDK_F6
+#define ACCEL_LAYER_COLOR_MOD    (GdkModifierType)0
+#define ACCEL_LAYER_UP_PATH      ACCEL_LAYER "/Move up"
+#define ACCEL_LAYER_UP_KEY       GDK_Up
+#define ACCEL_LAYER_UP_MOD       (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_LAYER_DOWN_PATH    ACCEL_LAYER "/Move down"
+#define ACCEL_LAYER_DOWN_KEY     GDK_Down
+#define ACCEL_LAYER_DOWN_MOD     (GdkModifierType) GDK_CONTROL_MASK
+#define ACCEL_LAYER_DELETE_PATH  ACCEL_LAYER "/Delete"
+#define ACCEL_LAYER_DELETE_KEY   GDK_Delete
+#define ACCEL_LAYER_DELETE_MOD   (GdkModifierType) GDK_CONTROL_MASK
+
+#define ACCEL_ANAL ACCEL_ROOT "analyze"
+
+#define ACCEL_TOOLS              ACCEL_ROOT "tools"
+#define ACCEL_TOOLS_POINTER_PATH ACCEL_TOOLS "/Pointer Tool"
+#define ACCEL_TOOLS_POINTER_KEY  GDK_1
+#define ACCEL_TOOLS_POINTER_MOD  (GdkModifierType)0
+#define ACCEL_TOOLS_PAN_PATH     ACCEL_TOOLS "/Pan Tool"
+#define ACCEL_TOOLS_PAN_KEY      GDK_2
+#define ACCEL_TOOLS_PAN_MOD      (GdkModifierType)0
+#define ACCEL_TOOLS_ZOOM_PATH    ACCEL_TOOLS "/Zoom Tool"
+#define ACCEL_TOOLS_ZOOM_KEY     GDK_3
+#define ACCEL_TOOLS_ZOOM_MOD     (GdkModifierType)0
+#define ACCEL_TOOLS_MEASURE_PATH ACCEL_TOOLS "/Measure Tool"
+#define ACCEL_TOOLS_MEASURE_KEY  GDK_4
+#define ACCEL_TOOLS_MEASURE_MOD  (GdkModifierType)0
+
+#define ACCEL_HELP ACCEL_ROOT "help"
+
+void interface_create_gui(int req_width, int req_height);
+
+void interface_set_render_type(int);
+
+void rename_main_window(const char* filename, GtkWidget* main_win);
+
+void set_window_icon(GtkWidget* this_window);
+
+gboolean interface_get_alert_dialog_response(
+    const gchar* primaryText, const gchar* secondaryText, gboolean show_checkbox, gboolean* ask_to_show_again,
+    const gchar* true_button_label, const gchar* false_button_label
+);
+
+int interface_reopen_question(GSList* filename, GSList* is_modified, GSList* files_counter, GSList* layer_number);
+
+void interface_show_alert_dialog(
+    gchar* primaryText, gchar* secondaryText, gboolean show_checkbox, gboolean* ask_to_show_again
+);
 
 /* transforms[0] is selected layer transformation, other is visible layers,
  * array must be terminated with NULL */
-void
-interface_show_layer_edit_dialog (gerbv_user_transformation_t *transforms[],
-				  gerbv_unit_t screenUnit);
+void interface_show_layer_edit_dialog(gerbv_user_transformation_t* transforms[], gerbv_unit_t screenUnit);
diff --git a/src/lrealpath.c b/src/lrealpath.c
index 223dccc..1d5911b 100644
--- a/src/lrealpath.c
+++ b/src/lrealpath.c
@@ -50,112 +50,106 @@ components will be simplified.  The returned value will be allocated using
 #endif
 
 /* On GNU libc systems the declaration is only visible with _GNU_SOURCE.  */
-#if defined(HAVE_CANONICALIZE_FILE_NAME) \
-    && defined(NEED_DECLARATION_CANONICALIZE_FILE_NAME)
-extern char *canonicalize_file_name (const char *);
+#if defined(HAVE_CANONICALIZE_FILE_NAME) && defined(NEED_DECLARATION_CANONICALIZE_FILE_NAME)
+extern char* canonicalize_file_name(const char*);
 #endif
 
 #if defined(HAVE_REALPATH)
-# if defined (PATH_MAX)
-#  define REALPATH_LIMIT PATH_MAX
-# else
-#  if defined (MAXPATHLEN)
-#   define REALPATH_LIMIT MAXPATHLEN
-#  endif
-# endif
+#if defined(PATH_MAX)
+#define REALPATH_LIMIT PATH_MAX
 #else
-  /* cygwin has realpath, so it won't get here.  */ 
-# if defined (_WIN32)
-#  define WIN32_LEAN_AND_MEAN
-#  include <windows.h> /* for GetFullPathName */
-# endif
+#if defined(MAXPATHLEN)
+#define REALPATH_LIMIT MAXPATHLEN
+#endif
+#endif
+#else
+/* cygwin has realpath, so it won't get here.  */
+#if defined(_WIN32)
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h> /* for GetFullPathName */
+#endif
 #endif
 
-char *
-lrealpath (const char *filename)
-{
-  /* Method 1: The system has a compile time upper bound on a filename
-     path.  Use that and realpath() to canonicalize the name.  This is
-     the most common case.  Note that, if there isn't a compile time
-     upper bound, you want to avoid realpath() at all costs.  */
+char*
+lrealpath(const char* filename) {
+    /* Method 1: The system has a compile time upper bound on a filename
+       path.  Use that and realpath() to canonicalize the name.  This is
+       the most common case.  Note that, if there isn't a compile time
+       upper bound, you want to avoid realpath() at all costs.  */
 #if defined(REALPATH_LIMIT)
-  {
-    char buf[REALPATH_LIMIT];
-    const char *rp = realpath (filename, buf);
-    if (rp == NULL)
-      rp = filename;
-    return strdup (rp);
-  }
-  /* REALPATH_LIMIT */
-
-  /* Method 2: The host system (i.e., GNU) has the function
-     canonicalize_file_name() which malloc's a chunk of memory and
-     returns that, use that.  */
+    {
+        char        buf[REALPATH_LIMIT];
+        const char* rp = realpath(filename, buf);
+        if (rp == NULL)
+            rp = filename;
+        return strdup(rp);
+    }
+    /* REALPATH_LIMIT */
+
+    /* Method 2: The host system (i.e., GNU) has the function
+       canonicalize_file_name() which malloc's a chunk of memory and
+       returns that, use that.  */
 #elif defined(HAVE_CANONICALIZE_FILE_NAME)
-  {
-    char *rp = canonicalize_file_name (filename);
-    if (rp == NULL)
-      return strdup (filename);
-    else
-      return rp;
-  }
-  /* HAVE_CANONICALIZE_FILE_NAME */
-
-  /* Method 3: Now we're getting desperate!  The system doesn't have a
-     compile time buffer size and no alternative function.  Query the
-     OS, using pathconf(), for the buffer limit.  Care is needed
-     though, some systems do not limit PATH_MAX (return -1 for
-     pathconf()) making it impossible to pass a correctly sized buffer
-     to realpath() (it could always overflow).  On those systems, we
-     skip this.  */
-#elif defined (HAVE_REALPATH) && defined (HAVE_UNISTD_H)
-  {
-    /* Find out the max path size.  */
-    long path_max = pathconf ("/", _PC_PATH_MAX);
-    if (path_max > 0)
-      {
-	/* PATH_MAX is bounded.  */
-	char *buf, *rp, *ret;
-	buf = (char *) malloc (path_max);
-	if (buf == NULL)
-	  return NULL;
-	rp = realpath (filename, buf);
-	ret = strdup (rp ? rp : filename);
-	free (buf);
-	return ret;
-      }
-    else
-      {
-	return NULL;
-      }
-  }
-  /* HAVE_REALPATH && HAVE_UNISTD_H */
-
-  /* The MS Windows method.  If we don't have realpath, we assume we
-     don't have symlinks and just canonicalize to a Windows absolute
-     path.  GetFullPath converts ../ and ./ in relative paths to
-     absolute paths, filling in current drive if one is not given
-     or using the current directory of a specified drive (eg, "E:foo").
-     It also converts all forward slashes to back slashes.  */
-#elif defined (_WIN32)
-  {
-    char buf[MAX_PATH];
-    char* basename;
-    DWORD len = GetFullPathName (filename, MAX_PATH, buf, &basename);
-    if (len == 0 || len > MAX_PATH - 1)
-      return strdup (filename);
-    else
-      {
-	/* The file system is case-preserving but case-insensitive,
-	   Canonicalize to lowercase, using the codepage associated
-	   with the process locale.  */
-        CharLowerBuff (buf, len);
-        return strdup (buf);
-      }
-  }
+    {
+        char* rp = canonicalize_file_name(filename);
+        if (rp == NULL)
+            return strdup(filename);
+        else
+            return rp;
+    }
+    /* HAVE_CANONICALIZE_FILE_NAME */
+
+    /* Method 3: Now we're getting desperate!  The system doesn't have a
+       compile time buffer size and no alternative function.  Query the
+       OS, using pathconf(), for the buffer limit.  Care is needed
+       though, some systems do not limit PATH_MAX (return -1 for
+       pathconf()) making it impossible to pass a correctly sized buffer
+       to realpath() (it could always overflow).  On those systems, we
+       skip this.  */
+#elif defined(HAVE_REALPATH) && defined(HAVE_UNISTD_H)
+    {
+        /* Find out the max path size.  */
+        long path_max = pathconf("/", _PC_PATH_MAX);
+        if (path_max > 0) {
+            /* PATH_MAX is bounded.  */
+            char *buf, *rp, *ret;
+            buf = (char*)malloc(path_max);
+            if (buf == NULL)
+                return NULL;
+            rp  = realpath(filename, buf);
+            ret = strdup(rp ? rp : filename);
+            free(buf);
+            return ret;
+        } else {
+            return NULL;
+        }
+    }
+    /* HAVE_REALPATH && HAVE_UNISTD_H */
+
+    /* The MS Windows method.  If we don't have realpath, we assume we
+       don't have symlinks and just canonicalize to a Windows absolute
+       path.  GetFullPath converts ../ and ./ in relative paths to
+       absolute paths, filling in current drive if one is not given
+       or using the current directory of a specified drive (eg, "E:foo").
+       It also converts all forward slashes to back slashes.  */
+#elif defined(_WIN32)
+    {
+        char  buf[MAX_PATH];
+        char* basename;
+        DWORD len = GetFullPathName(filename, MAX_PATH, buf, &basename);
+        if (len == 0 || len > MAX_PATH - 1)
+            return strdup(filename);
+        else {
+            /* The file system is case-preserving but case-insensitive,
+               Canonicalize to lowercase, using the codepage associated
+               with the process locale.  */
+            CharLowerBuff(buf, len);
+            return strdup(buf);
+        }
+    }
 #else
 
-  /* This system is a lost cause, just duplicate the filename.  */
-  return strdup (filename);
+    /* This system is a lost cause, just duplicate the filename.  */
+    return strdup(filename);
 #endif
 }
diff --git a/src/lrealpath.h b/src/lrealpath.h
index a4f7081..84b5a66 100644
--- a/src/lrealpath.h
+++ b/src/lrealpath.h
@@ -2,8 +2,6 @@
 #define __LREALPATH_H__
 
 /* A well-defined realpath () that is always compiled in.  */
-char *lrealpath (const char *);
+char* lrealpath(const char*);
 
 #endif /* __LREALPATH_H__ */
-
-
diff --git a/src/main.c b/src/main.c
index 96784da..9d4bed0 100644
--- a/src/main.c
+++ b/src/main.c
@@ -35,19 +35,19 @@
 #include <math.h>
 
 #ifdef WIN32
-# include <windows.h>
+#include <windows.h>
 #endif
 
 #ifdef HAVE_STRING_H
-# include <string.h>
+#include <string.h>
 #endif
 
 #ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
 #endif
 
 #ifdef HAVE_GETOPT_H
-# include <getopt.h>
+#include <getopt.h>
 #endif
 
 #include "common.h"
@@ -58,337 +58,324 @@
 #include "project.h"
 
 #if (DEBUG)
-# define dprintf printf("%s():  ", __FUNCTION__); printf
+#define dprintf                      \
+    printf("%s():  ", __FUNCTION__); \
+    printf
 #else
-# define dprintf if(0) printf
+#define dprintf \
+    if (0)      \
+    printf
 #endif
 
-#define NUMBER_OF_DEFAULT_COLORS 18
+#define NUMBER_OF_DEFAULT_COLORS          18
 #define NUMBER_OF_DEFAULT_TRANSFORMATIONS 20
 
-static void
-gerbv_print_help(void);
+static void gerbv_print_help(void);
 
 static int
-getopt_configured(int argc, char * const argv[], const char *optstring,
-		const struct option *longopts, int *longindex);
-static int
-getopt_lengh_unit(const char *optarg, double *input_div,
-		gerbv_screen_t *screen);
+getopt_configured(int argc, char* const argv[], const char* optstring, const struct option* longopts, int* longindex);
+static int getopt_lengh_unit(const char* optarg, double* input_div, gerbv_screen_t* screen);
 
 static gerbv_layer_color mainDefaultColors[NUMBER_OF_DEFAULT_COLORS] = {
-	{115,115,222,177},
-	{255,127,115,177},
-	{193,0,224,177},
-	{117,242,103,177},
-	{0,195,195,177},
-	{213,253,51,177},
-	{209,27,104,177},
-	{255,197,51,177},
-	{186,186,186,177},
-	{211,211,255,177},
-	{253,210,206,177},
-	{236,194,242,177},
-	{208,249,204,177},
-	{183,255,255,177},
-	{241,255,183,177},
-	{255,202,225,177},
-	{253,238,197,177},
-	{226,226,226,177}
+    {115, 115, 222, 177},
+    {255, 127, 115, 177},
+    {193,   0, 224, 177},
+    {117, 242, 103, 177},
+    {  0, 195, 195, 177},
+    {213, 253,  51, 177},
+    {209,  27, 104, 177},
+    {255, 197,  51, 177},
+    {186, 186, 186, 177},
+    {211, 211, 255, 177},
+    {253, 210, 206, 177},
+    {236, 194, 242, 177},
+    {208, 249, 204, 177},
+    {183, 255, 255, 177},
+    {241, 255, 183, 177},
+    {255, 202, 225, 177},
+    {253, 238, 197, 177},
+    {226, 226, 226, 177}
 };
 
 static gerbv_user_transformation_t mainDefaultTransformations[NUMBER_OF_DEFAULT_TRANSFORMATIONS] = {
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},	
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},		
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},	
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
-	{0,0,1,1,0,FALSE,FALSE,FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
+    {0, 0, 1, 1, 0, FALSE, FALSE, FALSE},
 };
 
 #ifdef HAVE_GETOPT_LONG
-int longopt_val = 0;
-int longopt_idx = 0;
-const struct option longopts[] = {
-    /* name              has_arg            flag  val */
-    {"border",		required_argument,  NULL,    'B'},
-    {"dpi",		required_argument,  NULL,    'D'},
-    {"version",         no_argument,	    NULL,    'V'},
-    {"origin",          required_argument,  NULL,    'O'},
-    {"window_inch",	required_argument,  NULL,    'W'},
-    {"antialias",	no_argument,	    NULL,    'a'},
-    {"background",      required_argument,  NULL,    'b'},
-    {"dump",            no_argument,	    NULL,    'd'},
-    {"foreground",      required_argument,  NULL,    'f'},
-    {"rotate",          required_argument,  NULL,    'r'},
-    {"mirror",          required_argument,  NULL,    'm'},
-    {"help",            no_argument,	    NULL,    'h'},
-    {"log",             required_argument,  NULL,    'l'},
-    {"output",          required_argument,  NULL,    'o'},
-    {"project",         required_argument,  NULL,    'p'},
-    {"tools",           required_argument,  NULL,    't'},
-    {"translate",       required_argument,  NULL,    'T'},
-    {"units",           required_argument,  NULL,    'u'},
-    {"window",		required_argument,  NULL,    'w'},
-    {"export",          required_argument,  NULL,    'x'},
-    {"geometry",        required_argument,  &longopt_val, 1},
-    /* GDK/GDK debug flags to be "let through" */
-    {"gtk-module",      required_argument,  &longopt_val, 2},
-    {"g-fatal-warnings",no_argument,	    &longopt_val, 2},
-    {"gtk-debug",       required_argument,  &longopt_val, 2},
-    {"gtk-no-debug",    required_argument,  &longopt_val, 2},
-    {"gdk-debug",       required_argument,  &longopt_val, 2},
-    {"gdk-no-debug",    required_argument,  &longopt_val, 2},
-    {"display",         required_argument,  &longopt_val, 2},
-    {"sync",            no_argument,	    &longopt_val, 2},
-    {"no-xshm",         no_argument,	    &longopt_val, 2},
-    {"name",            required_argument,  &longopt_val, 2},
-    {"class",           required_argument,  &longopt_val, 2},
-    {0, 0, 0, 0},
+int                 longopt_val = 0;
+int                 longopt_idx = 0;
+const struct option longopts[]  = {
+  /* name              has_arg            flag  val */
+    {          "border", required_argument,         NULL, 'B'},
+    {             "dpi", required_argument,         NULL, 'D'},
+    {         "version",       no_argument,         NULL, 'V'},
+    {          "origin", required_argument,         NULL, 'O'},
+    {     "window_inch", required_argument,         NULL, 'W'},
+    {       "antialias",       no_argument,         NULL, 'a'},
+    {      "background", required_argument,         NULL, 'b'},
+    {            "dump",       no_argument,         NULL, 'd'},
+    {      "foreground", required_argument,         NULL, 'f'},
+    {          "rotate", required_argument,         NULL, 'r'},
+    {          "mirror", required_argument,         NULL, 'm'},
+    {            "help",       no_argument,         NULL, 'h'},
+    {             "log", required_argument,         NULL, 'l'},
+    {          "output", required_argument,         NULL, 'o'},
+    {         "project", required_argument,         NULL, 'p'},
+    {           "tools", required_argument,         NULL, 't'},
+    {       "translate", required_argument,         NULL, 'T'},
+    {           "units", required_argument,         NULL, 'u'},
+    {          "window", required_argument,         NULL, 'w'},
+    {          "export", required_argument,         NULL, 'x'},
+    {        "geometry", required_argument, &longopt_val,   1},
+ /* GDK/GDK debug flags to be "let through" */
+    {      "gtk-module", required_argument, &longopt_val,   2},
+    {"g-fatal-warnings",       no_argument, &longopt_val,   2},
+    {       "gtk-debug", required_argument, &longopt_val,   2},
+    {    "gtk-no-debug", required_argument, &longopt_val,   2},
+    {       "gdk-debug", required_argument, &longopt_val,   2},
+    {    "gdk-no-debug", required_argument, &longopt_val,   2},
+    {         "display", required_argument, &longopt_val,   2},
+    {            "sync",       no_argument, &longopt_val,   2},
+    {         "no-xshm",       no_argument, &longopt_val,   2},
+    {            "name", required_argument, &longopt_val,   2},
+    {           "class", required_argument, &longopt_val,   2},
+    {                 0,                 0,            0,   0},
 };
 #endif /* HAVE_GETOPT_LONG*/
-const char *opt_options = "VadhB:D:O:W:b:f:r:m:l:o:p:t:T:u:w:x:";
+const char* opt_options = "VadhB:D:O:W:b:f:r:m:l:o:p:t:T:u:w:x:";
 
 /**Global state variable to keep track of what's happening on the screen.
    Declared extern in main.h
  */
-gerbv_project_t *mainProject;
-gerbv_screen_t screen;
+gerbv_project_t* mainProject;
+gerbv_screen_t   screen;
 
 gboolean logToFileOption;
-gchar *logToFileFilename;
+gchar*   logToFileFilename;
 
 /* Coords like "0x2" parsed by "%fx%f" will result in first number = 2 and
    second number 0. Replace 'x' in coordinate string with ';'*/
 static void
-care_for_x_in_cords(char *string)
-{
-	char *found;
-	found = strchr(string, 'x');
-	if (!found)
-		found = strchr(string, 'X');
-	if (found)
-		*found = ';';
+care_for_x_in_cords(char* string) {
+    char* found;
+    found = strchr(string, 'x');
+    if (!found)
+        found = strchr(string, 'X');
+    if (found)
+        *found = ';';
 }
 
 /* ------------------------------------------------------------------ */
-void 
-main_open_project_from_filename(gerbv_project_t *gerbvProject, gchar *filename) 
-{
-	project_list_t *list, *plist;
-	gint i, max_layer_num = -1;
-	gerbv_fileinfo_t *file_info;
-
-	dprintf("Opening project = %s\n", (gchar *) filename);
-	list = read_project_file(filename);
-
-	if (!list) {
-		GERB_COMPILE_WARNING(_("Could not read \"%s\" (loaded %d)"),
-				(gchar *) filename, gerbvProject->last_loaded);
-
-		return;
-	}
-
-	/* Get the max layer number in the project list */
-	plist = list;
-	while (plist) {
-		if (plist->layerno > max_layer_num)
-			max_layer_num = plist->layerno;
-
-		plist = plist->next;
-	}
-
-	/* Increase the layer count each time and find (if any) the
-	 * corresponding entry */
-	for (i = -1; i <= max_layer_num; i++) {
-		plist = list;
-		while (plist) {
-			if (plist->layerno != i) {
-				plist = plist->next;
-				continue;
-			}
-
-			GdkColor colorTemplate = {0,
-				plist->rgb[0], plist->rgb[1], plist->rgb[2]};
-			if (i == -1) {
-				screen.background_is_from_project= TRUE;
-				gerbvProject->background = colorTemplate;
-				plist = plist->next;
-				continue;
-			}
-
-			gchar *fullName = NULL;
-			gchar *dirName = NULL;
-			gint fileIndex = gerbvProject->last_loaded + 1;
-
-			if (!g_path_is_absolute (plist->filename)) {
-				/* Build the full pathname to the layer */
-				dirName = g_path_get_dirname (filename);
-				fullName = g_build_filename (dirName,
-					plist->filename, NULL);
-			} else {
-				fullName = g_strdup (plist->filename);
-			}
-
-			if (gerbv_open_image(gerbvProject, fullName,
-					fileIndex, FALSE,
-					plist->attr_list,
-					plist->n_attr, TRUE) == -1) {
-				GERB_MESSAGE(_("could not read file: %s"),
-						fullName);
-				plist = plist->next;
-				continue;
-			}
-
-			g_free (dirName);
-			g_free (fullName);
-
-			/* Change color from default to from the project list */
-			file_info = gerbvProject->file[fileIndex];
-			file_info->color = colorTemplate;
-			file_info->alpha = plist->alpha;
-			file_info->transform.inverted =	plist->inverted;
-			file_info->transform.translateX = plist->translate_x;
-			file_info->transform.translateY = plist->translate_y;
-			file_info->transform.rotation = plist->rotation;
-			file_info->transform.scaleX = plist->scale_x;
-			file_info->transform.scaleY = plist->scale_y;
-			file_info->transform.mirrorAroundX = plist->mirror_x;
-			file_info->transform.mirrorAroundY = plist->mirror_y;
-			file_info->isVisible = plist->visible;
-
-			plist = plist->next;
-		}
-	}
-
-	project_destroy_project_list(list);
-
-	/* Save project filename for later use */
-	if (gerbvProject->project) {
-		g_free(gerbvProject->project);
-		gerbvProject->project = NULL;
-	}
-	gerbvProject->project = g_strdup(filename);
-	if (gerbvProject->project == NULL)
-		GERB_FATAL_ERROR("malloc gerbvProject->project failed in %s()",
-				__FUNCTION__);
+void
+main_open_project_from_filename(gerbv_project_t* gerbvProject, gchar* filename) {
+    project_list_t *  list, *plist;
+    gint              i, max_layer_num = -1;
+    gerbv_fileinfo_t* file_info;
+
+    dprintf("Opening project = %s\n", (gchar*)filename);
+    list = read_project_file(filename);
+
+    if (!list) {
+        GERB_COMPILE_WARNING(_("Could not read \"%s\" (loaded %d)"), (gchar*)filename, gerbvProject->last_loaded);
+
+        return;
+    }
+
+    /* Get the max layer number in the project list */
+    plist = list;
+    while (plist) {
+        if (plist->layerno > max_layer_num)
+            max_layer_num = plist->layerno;
+
+        plist = plist->next;
+    }
+
+    /* Increase the layer count each time and find (if any) the
+     * corresponding entry */
+    for (i = -1; i <= max_layer_num; i++) {
+        plist = list;
+        while (plist) {
+            if (plist->layerno != i) {
+                plist = plist->next;
+                continue;
+            }
+
+            GdkColor colorTemplate = { 0, plist->rgb[0], plist->rgb[1], plist->rgb[2] };
+            if (i == -1) {
+                screen.background_is_from_project = TRUE;
+                gerbvProject->background          = colorTemplate;
+                plist                             = plist->next;
+                continue;
+            }
+
+            gchar* fullName  = NULL;
+            gchar* dirName   = NULL;
+            gint   fileIndex = gerbvProject->last_loaded + 1;
+
+            if (!g_path_is_absolute(plist->filename)) {
+                /* Build the full pathname to the layer */
+                dirName  = g_path_get_dirname(filename);
+                fullName = g_build_filename(dirName, plist->filename, NULL);
+            } else {
+                fullName = g_strdup(plist->filename);
+            }
+
+            if (gerbv_open_image(gerbvProject, fullName, fileIndex, FALSE, plist->attr_list, plist->n_attr, TRUE)
+                == -1) {
+                GERB_MESSAGE(_("could not read file: %s"), fullName);
+                plist = plist->next;
+                continue;
+            }
+
+            g_free(dirName);
+            g_free(fullName);
+
+            /* Change color from default to from the project list */
+            file_info                          = gerbvProject->file[fileIndex];
+            file_info->color                   = colorTemplate;
+            file_info->alpha                   = plist->alpha;
+            file_info->transform.inverted      = plist->inverted;
+            file_info->transform.translateX    = plist->translate_x;
+            file_info->transform.translateY    = plist->translate_y;
+            file_info->transform.rotation      = plist->rotation;
+            file_info->transform.scaleX        = plist->scale_x;
+            file_info->transform.scaleY        = plist->scale_y;
+            file_info->transform.mirrorAroundX = plist->mirror_x;
+            file_info->transform.mirrorAroundY = plist->mirror_y;
+            file_info->isVisible               = plist->visible;
+
+            plist = plist->next;
+        }
+    }
+
+    project_destroy_project_list(list);
+
+    /* Save project filename for later use */
+    if (gerbvProject->project) {
+        g_free(gerbvProject->project);
+        gerbvProject->project = NULL;
+    }
+    gerbvProject->project = g_strdup(filename);
+    if (gerbvProject->project == NULL)
+        GERB_FATAL_ERROR("malloc gerbvProject->project failed in %s()", __FUNCTION__);
 } /* gerbv_open_project_from_filename */
 
 /* ------------------------------------------------------------------ */
-void 
-main_save_project_from_filename(gerbv_project_t *gerbvProject, gchar *filename) 
-{
-    project_list_t *list, *plist;
-    gchar *dirName = g_path_get_dirname (filename);
-    gerbv_fileinfo_t *file_info;
-    int idx;
-    
-    list = g_new0 (project_list_t, 1);
-    list->next = NULL;
-    list->layerno = -1;
+void
+main_save_project_from_filename(gerbv_project_t* gerbvProject, gchar* filename) {
+    project_list_t *  list, *plist;
+    gchar*            dirName = g_path_get_dirname(filename);
+    gerbv_fileinfo_t* file_info;
+    int               idx;
+
+    list           = g_new0(project_list_t, 1);
+    list->next     = NULL;
+    list->layerno  = -1;
     list->filename = g_strdup(gerbvProject->path);
-    list->rgb[0] = gerbvProject->background.red;
-    list->rgb[1] = gerbvProject->background.green;
-    list->rgb[2] = gerbvProject->background.blue;
-    
+    list->rgb[0]   = gerbvProject->background.red;
+    list->rgb[1]   = gerbvProject->background.green;
+    list->rgb[2]   = gerbvProject->background.blue;
+
     /* loop over all layer files */
     for (idx = 0; idx <= gerbvProject->last_loaded; idx++) {
-	if (gerbvProject->file[idx]) {
-	    plist = g_new0 (project_list_t, 1);
-	    plist->next = list;
-	    plist->layerno = idx;
-	    
-	    /* figure out the relative path to the layer from the project
-	       directory */
-	    if (strncmp (dirName, gerbvProject->file[idx]->fullPathname, strlen(dirName)) == 0) {
-		/* skip over the common dirname and the separator */
-		plist->filename = g_strdup(gerbvProject->file[idx]->fullPathname + strlen(dirName) + 1);
-	    } else {
-		/* if we can't figure out a relative path, just save the 
-		 * absolute one */
-		plist->filename = g_strdup(gerbvProject->file[idx]->fullPathname);
-	    }
-	    file_info = gerbvProject->file[idx];
-	    plist->rgb[0] =		file_info->color.red;
-	    plist->rgb[1] =		file_info->color.green;
-	    plist->rgb[2] =		file_info->color.blue;
-	    plist->alpha =		file_info->alpha;
-	    plist->inverted =		file_info->transform.inverted;
-	    plist->visible =		file_info->isVisible;
-	    plist->translate_x =	file_info->transform.translateX;
-	    plist->translate_y =	file_info->transform.translateY;
-	    plist->rotation =		file_info->transform.rotation;
-	    plist->scale_x =		file_info->transform.scaleX;
-	    plist->scale_y =		file_info->transform.scaleY;
-	    plist->mirror_x =		file_info->transform.mirrorAroundX;
-	    plist->mirror_y =		file_info->transform.mirrorAroundY;
-	    list= plist;
-	}
+        if (gerbvProject->file[idx]) {
+            plist          = g_new0(project_list_t, 1);
+            plist->next    = list;
+            plist->layerno = idx;
+
+            /* figure out the relative path to the layer from the project
+               directory */
+            if (strncmp(dirName, gerbvProject->file[idx]->fullPathname, strlen(dirName)) == 0) {
+                /* skip over the common dirname and the separator */
+                plist->filename = g_strdup(gerbvProject->file[idx]->fullPathname + strlen(dirName) + 1);
+            } else {
+                /* if we can't figure out a relative path, just save the
+                 * absolute one */
+                plist->filename = g_strdup(gerbvProject->file[idx]->fullPathname);
+            }
+            file_info          = gerbvProject->file[idx];
+            plist->rgb[0]      = file_info->color.red;
+            plist->rgb[1]      = file_info->color.green;
+            plist->rgb[2]      = file_info->color.blue;
+            plist->alpha       = file_info->alpha;
+            plist->inverted    = file_info->transform.inverted;
+            plist->visible     = file_info->isVisible;
+            plist->translate_x = file_info->transform.translateX;
+            plist->translate_y = file_info->transform.translateY;
+            plist->rotation    = file_info->transform.rotation;
+            plist->scale_x     = file_info->transform.scaleX;
+            plist->scale_y     = file_info->transform.scaleY;
+            plist->mirror_x    = file_info->transform.mirrorAroundX;
+            plist->mirror_y    = file_info->transform.mirrorAroundY;
+            list               = plist;
+        }
     }
-    
+
     if (write_project_file(gerbvProject, gerbvProject->project, list)) {
-	GERB_MESSAGE(_("Failed to write project"));
+        GERB_MESSAGE(_("Failed to write project"));
     }
     project_destroy_project_list(list);
-    g_free (dirName);
+    g_free(dirName);
 } /* gerbv_save_project_from_filename */
 
 /* ------------------------------------------------------------------ */
-void 
-main_save_as_project_from_filename(gerbv_project_t *gerbvProject, gchar *filename) 
-{
-	
+void
+main_save_as_project_from_filename(gerbv_project_t* gerbvProject, gchar* filename) {
+
     /*
      * Save project filename for later use
      */
     if (gerbvProject->project) {
-	g_free(gerbvProject->project);
-	gerbvProject->project = NULL;
+        g_free(gerbvProject->project);
+        gerbvProject->project = NULL;
     }
     gerbvProject->project = g_strdup(filename);
     if (gerbvProject->project == NULL)
-	GERB_FATAL_ERROR("malloc gerbvProject->project failed in %s()",
-			__FUNCTION__);
-    main_save_project_from_filename (gerbvProject, filename);
+        GERB_FATAL_ERROR("malloc gerbvProject->project failed in %s()", __FUNCTION__);
+    main_save_project_from_filename(gerbvProject, filename);
 } /* gerbv_save_as_project_from_filename */
 
-GArray *log_array_tmp = NULL;
+GArray* log_array_tmp = NULL;
 
 /* Temporary log messages handler. It will store log messages before GUI
  * initialization. */
 void
-callbacks_temporary_handle_log_messages(const gchar *log_domain,
-		GLogLevelFlags log_level,
-		const gchar *message, gpointer user_data) {
+callbacks_temporary_handle_log_messages(
+    const gchar* log_domain, GLogLevelFlags log_level, const gchar* message, gpointer user_data
+) {
     struct log_struct item;
 
-    item.domain = g_strdup (log_domain);
-    item.level = log_level;
-    item.message = g_strdup (message);
-    g_array_append_val (log_array_tmp, item);
+    item.domain  = g_strdup(log_domain);
+    item.level   = log_level;
+    item.message = g_strdup(message);
+    g_array_append_val(log_array_tmp, item);
 
-    g_log_default_handler (log_domain, log_level, message, user_data);
+    g_log_default_handler(log_domain, log_level, message, user_data);
 }
 
 #ifdef WIN32
 static void
-wait_console_for_win(void)
-{
-    FILE *console = fopen("CONOUT$", "w");
+wait_console_for_win(void) {
+    FILE* console = fopen("CONOUT$", "w");
 
     fprintf(console, _("\n*** Press Enter to continue ***"));
     fflush(console);
@@ -396,19 +383,18 @@ wait_console_for_win(void)
 
 /* Attach console in application which is build with -mwindows flag */
 static void
-attach_console_for_win(void)
-{
+attach_console_for_win(void) {
     if (((HANDLE)_get_osfhandle(fileno(stdout)) == INVALID_HANDLE_VALUE
-      || (HANDLE)_get_osfhandle(fileno(stderr)) == INVALID_HANDLE_VALUE)
-    && AttachConsole(ATTACH_PARENT_PROCESS)) {
+         || (HANDLE)_get_osfhandle(fileno(stderr)) == INVALID_HANDLE_VALUE)
+        && AttachConsole(ATTACH_PARENT_PROCESS)) {
 
-	if ((HANDLE)_get_osfhandle(fileno (stdout)) == INVALID_HANDLE_VALUE)
-	    freopen("CONOUT$", "w", stdout);
+        if ((HANDLE)_get_osfhandle(fileno(stdout)) == INVALID_HANDLE_VALUE)
+            freopen("CONOUT$", "w", stdout);
 
-	if ((HANDLE)_get_osfhandle(fileno (stderr)) == INVALID_HANDLE_VALUE)
-	    freopen("CONOUT$", "w", stderr);
+        if ((HANDLE)_get_osfhandle(fileno(stderr)) == INVALID_HANDLE_VALUE)
+            freopen("CONOUT$", "w", stderr);
 
-	atexit(wait_console_for_win);
+        atexit(wait_console_for_win);
     }
 }
 #else
@@ -418,79 +404,59 @@ attach_console_for_win(void) {}
 
 /* ------------------------------------------------------------------ */
 int
-main(int argc, char *argv[])
-{
-    int       read_opt;
-    int       i,r,g,b,a;
-    int       req_width = -1, req_height = -1;
+main(int argc, char* argv[]) {
+    int read_opt;
+    int i, r, g, b, a;
+    int req_width = -1, req_height = -1;
 #ifdef HAVE_GETOPT_LONG
-    char      *rest;
+    char* rest;
 #endif
-    char      *project_filename = NULL;
-    gboolean userSuppliedOrigin=FALSE, userSuppliedWindow=FALSE, 
-	     userSuppliedAntiAlias=FALSE, userSuppliedWindowInPixels=FALSE, userSuppliedDpi=FALSE;
-    gint  layerctr =0, transformCount = 0;
-    gdouble initial_rotation = 0.0;
-    gdouble input_divisor = 1.0; /* 1.0 for inch */
-    int unit_flag_counter;
-    gboolean initial_mirror_x = FALSE;
-    gboolean initial_mirror_y = FALSE;
-    const gchar *exportFilename = NULL;
-    gfloat userSuppliedOriginX=0.0,userSuppliedOriginY=0.0,userSuppliedDpiX=72.0, userSuppliedDpiY=72.0, 
-	   userSuppliedWidth=0, userSuppliedHeight=0,
-	   userSuppliedBorder = GERBV_DEFAULT_BORDER_COEFF;
-
-    gerbv_image_t *exportImage;
+    char*    project_filename   = NULL;
+    gboolean userSuppliedOrigin = FALSE, userSuppliedWindow = FALSE, userSuppliedAntiAlias = FALSE,
+             userSuppliedWindowInPixels = FALSE, userSuppliedDpi = FALSE;
+    gint         layerctr = 0, transformCount = 0;
+    gdouble      initial_rotation = 0.0;
+    gdouble      input_divisor    = 1.0; /* 1.0 for inch */
+    int          unit_flag_counter;
+    gboolean     initial_mirror_x    = FALSE;
+    gboolean     initial_mirror_y    = FALSE;
+    const gchar* exportFilename      = NULL;
+    gfloat       userSuppliedOriginX = 0.0, userSuppliedOriginY = 0.0, userSuppliedDpiX = 72.0, userSuppliedDpiY = 72.0,
+           userSuppliedWidth = 0, userSuppliedHeight = 0, userSuppliedBorder = GERBV_DEFAULT_BORDER_COEFF;
+
+    gerbv_image_t* exportImage;
 
     enum exp_type {
-	EXP_TYPE_NONE = -1,
-	EXP_TYPE_PNG,
-	EXP_TYPE_PDF,
-	EXP_TYPE_SVG,
-	EXP_TYPE_PS,
-	EXP_TYPE_RS274X,
-	EXP_TYPE_DRILL,
-	EXP_TYPE_IDRILL,
-    };
-    enum exp_type exportType = EXP_TYPE_NONE;
-    const char *export_type_names[] = {
-	"png",
-	"pdf",
-	"svg",
-	"ps",
-	"rs274x",
-	"drill",
-	"idrill",
-	NULL
-    };
-    const gchar *export_def_file_names[] = {
-	"output.png",
-	"output.pdf",
-	"output.svg",
-	"output.ps",
-	"output.gbx",
-	"output.cnc",
-	"output.ncp",
-	NULL
+        EXP_TYPE_NONE = -1,
+        EXP_TYPE_PNG,
+        EXP_TYPE_PDF,
+        EXP_TYPE_SVG,
+        EXP_TYPE_PS,
+        EXP_TYPE_RS274X,
+        EXP_TYPE_DRILL,
+        EXP_TYPE_IDRILL,
     };
+    enum exp_type exportType              = EXP_TYPE_NONE;
+    const char*   export_type_names[]     = { "png", "pdf", "svg", "ps", "rs274x", "drill", "idrill", NULL };
+    const gchar*  export_def_file_names[] = { "output.png", "output.pdf", "output.svg", "output.ps",
+                                              "output.gbx", "output.cnc", "output.ncp", NULL };
 
-    const gchar *settings_schema_env = "GSETTINGS_SCHEMA_DIR";
+    const gchar* settings_schema_env = "GSETTINGS_SCHEMA_DIR";
 #ifdef WIN32
     /* On Windows executable can be not in bin/ dir */
-    const gchar *settings_schema_fallback_dir =
-	    "share/glib-2.0/schemas" G_SEARCHPATH_SEPARATOR_S
-	    "../share/glib-2.0/schemas";
+    const gchar* settings_schema_fallback_dir =
+        "share/glib-2.0/schemas" G_SEARCHPATH_SEPARATOR_S "../share/glib-2.0/schemas";
 #else
-    const gchar *settings_schema_fallback_dir = "../share/glib-2.0/schemas";
+    const gchar* settings_schema_fallback_dir = "../share/glib-2.0/schemas";
 #endif
-    gchar *env_val;
+    gchar* env_val;
 
 #if ENABLE_NLS
     setlocale(LC_ALL, "");
     bindtextdomain(PACKAGE, LOCALEDIR);
-# ifdef WIN32
+#ifdef WIN32
     bind_textdomain_codeset(PACKAGE, "UTF-8");
-# endif
+#endif
     textdomain(PACKAGE);
 #endif
 
@@ -500,412 +466,408 @@ main(int argc, char *argv[])
      * Setup the screen info. Must do this before getopt, since getopt
      * eventually will set some variables in screen.
      */
-    memset((void *)&screen, 0, sizeof(gerbv_screen_t));
+    memset((void*)&screen, 0, sizeof(gerbv_screen_t));
     screen.state = NORMAL;
-    screen.unit = GERBV_DEFAULT_UNIT;
-    
-    mainProject = gerbv_create_project();
+    screen.unit  = GERBV_DEFAULT_UNIT;
+
+    mainProject           = gerbv_create_project();
     mainProject->execname = g_strdup(argv[0]);
     mainProject->execpath = g_path_get_dirname(argv[0]);
 
     /* Add "fallback" directory with settings schema file from this
      * executable path */
     if (NULL == g_getenv(settings_schema_env))
-	    /* Empty env var */
-	    env_val = g_strconcat(
-		    mainProject->execpath, G_DIR_SEPARATOR_S,
-				settings_schema_fallback_dir,
-		    NULL);
+        /* Empty env var */
+        env_val = g_strconcat(mainProject->execpath, G_DIR_SEPARATOR_S, settings_schema_fallback_dir, NULL);
     else
-	    /* Not empty env var */
-	    env_val = g_strconcat(g_getenv(settings_schema_env),
-		    G_SEARCHPATH_SEPARATOR_S,
-		    mainProject->execpath, G_DIR_SEPARATOR_S,
-				settings_schema_fallback_dir,
-		    NULL);
+        /* Not empty env var */
+        env_val = g_strconcat(
+            g_getenv(settings_schema_env), G_SEARCHPATH_SEPARATOR_S, mainProject->execpath, G_DIR_SEPARATOR_S,
+            settings_schema_fallback_dir, NULL
+        );
     g_setenv(settings_schema_env, env_val, TRUE);
     g_free(env_val);
-    
+
     /* set default rendering mode */
 #ifdef WIN32
     /* Cairo seems to render faster on Windows, so use it for default */
     screenRenderInfo.renderType = GERBV_RENDER_TYPE_CAIRO_NORMAL;
 #else
-    screenRenderInfo.renderType = GERBV_RENDER_TYPE_GDK;
+    screenRenderInfo.renderType               = GERBV_RENDER_TYPE_GDK;
 #endif
 
-    logToFileOption = FALSE;
+    logToFileOption   = FALSE;
     logToFileFilename = NULL;
 
-    log_array_tmp = g_array_new (TRUE, FALSE, sizeof (struct log_struct));
-    g_log_set_handler (NULL,
-		    G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION | G_LOG_LEVEL_MASK,
-		    callbacks_temporary_handle_log_messages, NULL);
-
+    log_array_tmp = g_array_new(TRUE, FALSE, sizeof(struct log_struct));
+    g_log_set_handler(
+        NULL, G_LOG_FLAG_FATAL | G_LOG_FLAG_RECURSION | G_LOG_LEVEL_MASK, callbacks_temporary_handle_log_messages, NULL
+    );
 
     /* 1. Process "length unit" command line flag */
     unit_flag_counter = 0;
-    opterr = 0; /* Disable getopt() error messages */
-    while (-1 != (read_opt = getopt_configured(argc, argv, opt_options,
-				    longopts, &longopt_idx))) {
-	switch (read_opt) {
-	case 'u':
-	    unit_flag_counter++;
-
-	    if (!getopt_lengh_unit(optarg, &input_divisor, &screen))
-		GERB_COMPILE_WARNING(
-			_("Unrecognized length unit \"%s\" in command line"),
-			optarg);
-
-	    break;
-	}
+    opterr            = 0; /* Disable getopt() error messages */
+    while (-1 != (read_opt = getopt_configured(argc, argv, opt_options, longopts, &longopt_idx))) {
+        switch (read_opt) {
+            case 'u':
+                unit_flag_counter++;
+
+                if (!getopt_lengh_unit(optarg, &input_divisor, &screen))
+                    GERB_COMPILE_WARNING(_("Unrecognized length unit \"%s\" in command line"), optarg);
+
+                break;
+        }
     }
 
     /* 2. Process all other command line flags */
     optind = 0; /* Reset getopt() index */
     opterr = 1; /* Enable getopt() error messages */
-    while (-1 != (read_opt = getopt_configured(argc, argv, opt_options,
-				    longopts, &longopt_idx))) {
-	switch (read_opt) {
+    while (-1 != (read_opt = getopt_configured(argc, argv, opt_options, longopts, &longopt_idx))) {
+        switch (read_opt) {
 #ifdef HAVE_GETOPT_LONG
-	case 0:
-	    /* Only long options like GDK/GTK debug */
-	    switch (longopt_val) {
-	    case 0: /* default value if nothing is set */
-		GERB_COMPILE_WARNING(
-			_("Not handled option \"%s\" in command line"),
-			longopts[longopt_idx].name);
-		break;
-	    case 1: /* geometry */
-		errno = 0;
-		req_width = (int)strtol(optarg, &rest, 10);
-		if (errno) {
-		    perror(_("Width"));
-		    break;
-		}
-		if (rest[0] != 'x'){
-		    fprintf(stderr, _("Split X and Y parameters with an x\n"));
-		    break;
-		}
-		rest++;
-		errno = 0;
-		req_height = (int)strtol(rest, &rest, 10);
-		if (errno) {
-		    perror(_("Height"));
-		    break;
-		}
-		/*
-		if ((rest[0] == 0) || ((rest[0] != '-') && (rest[0] != '+')))
-		    break;
-		errno = 0;
-		req_x = (int)strtol(rest, &rest, 10);
-		if (errno) {
-		    perror("X");
-		    break;
-		}
-		if ((rest[0] == 0) || ((rest[0] != '-') && (rest[0] != '+')))
-		    break;
-		errno = 0;
-		req_y = (int)strtol(rest, &rest, 10);
-		if (errno) {
-		    perror("Y");
-		    break;
-		}
-		*/
-		break;
-	    default:
-		break;
-	    }
-	    break;
+            case 0:
+                /* Only long options like GDK/GTK debug */
+                switch (longopt_val) {
+                    case 0: /* default value if nothing is set */
+                        GERB_COMPILE_WARNING(
+                            _("Not handled option \"%s\" in command line"), longopts[longopt_idx].name
+                        );
+                        break;
+                    case 1: /* geometry */
+                        errno     = 0;
+                        req_width = (int)strtol(optarg, &rest, 10);
+                        if (errno) {
+                            perror(_("Width"));
+                            break;
+                        }
+                        if (rest[0] != 'x') {
+                            fprintf(stderr, _("Split X and Y parameters with an x\n"));
+                            break;
+                        }
+                        rest++;
+                        errno      = 0;
+                        req_height = (int)strtol(rest, &rest, 10);
+                        if (errno) {
+                            perror(_("Height"));
+                            break;
+                        }
+                        /*
+                        if ((rest[0] == 0) || ((rest[0] != '-') && (rest[0] != '+')))
+                            break;
+                        errno = 0;
+                        req_x = (int)strtol(rest, &rest, 10);
+                        if (errno) {
+                            perror("X");
+                            break;
+                        }
+                        if ((rest[0] == 0) || ((rest[0] != '-') && (rest[0] != '+')))
+                            break;
+                        errno = 0;
+                        req_y = (int)strtol(rest, &rest, 10);
+                        if (errno) {
+                            perror("Y");
+                            break;
+                        }
+                        */
+                        break;
+                    default: break;
+                }
+                break;
 #endif /* HAVE_GETOPT_LONG */
-    	case 'B' :
-	    if (optarg == NULL) {
-		fprintf(stderr, _("You must specify the border in the format <alpha>.\n"));
-		exit(1);
-	    }
-	    if (strlen (optarg) > 10) {
-		fprintf(stderr, _("Specified border is not recognized.\n"));
-		exit(1);
-	    }
-	    sscanf (optarg,"%f",&userSuppliedBorder);
-	    if (userSuppliedBorder <  0) {
-		fprintf(stderr, _("Specified border is smaller than zero!\n"));
-		exit(1);
-	    }
-	    userSuppliedBorder/=100.0;
-	    break;
-	case 'D' :
-	    if (optarg == NULL) {
-		fprintf(stderr, _("You must give an resolution in the format <DPI_XxDPI_Y> or <DPI_X_and_Y>.\n"));
-		exit(1);
-	    }
-	    if (strlen (optarg) > 20) {
-		fprintf(stderr, _("Specified resolution is not recognized.\n"));
-		exit(1);
-	    }
-	    if(strchr(optarg, 'x')!=NULL){
-		sscanf (optarg,"%fx%f",&userSuppliedDpiX,&userSuppliedDpiY);
-	    }else{
-		sscanf (optarg,"%f",&userSuppliedDpiX);
-		userSuppliedDpiY = userSuppliedDpiX;
-	    }
-	    if ((userSuppliedDpiX <= 0) || (userSuppliedDpiY <= 0)) {
-		fprintf(stderr, _("Specified resolution should be greater than 0.\n"));
-		exit(1);
-	    }
-	    userSuppliedDpi=TRUE;
-	    break;
-    	case 'O' :
-	    if (optarg == NULL) {
-		fprintf(stderr, _("You must give an origin in the format "
-					"<XxY> or <X;Y>.\n"));
-		exit(1);
-	    }
-	    if (strlen (optarg) > 20) {
-		fprintf(stderr, _("Specified origin is not recognized.\n"));
-		exit(1);
-	    }
-
-	    care_for_x_in_cords(optarg);
-	    sscanf(optarg,"%f;%f", &userSuppliedOriginX, &userSuppliedOriginY);
-	    userSuppliedOriginX /= input_divisor;
-	    userSuppliedOriginY /= input_divisor;
-	    userSuppliedOrigin=TRUE;
-	    break;
-    	case 'V' :
-	    printf(_("gerbv version %s\n"), VERSION);
-	    printf(_("Copyright (C) 2001-2008 by Stefan Petersen\n"
-		"and the respective original authors listed in the source files.\n"));
-	    exit(0);	
-	case 'a' :
-	    userSuppliedAntiAlias = TRUE;
-	    break;
-    	case 'b' :	// Set background to this color
-	    if (optarg == NULL) {
-		fprintf(stderr, _("You must give an background color "
-					"in the hex-format <#RRGGBB>.\n"));
-		exit(1);
-	    }
-	    if ((strlen (optarg) != 7)||(optarg[0]!='#')) {
-		fprintf(stderr, _("Specified color format "
-					"is not recognized.\n"));
-		exit(1);
-	    }
-    	    r=g=b=-1;
-	    sscanf (optarg,"#%2x%2x%2x",&r,&g,&b);
-	    if ( (r<0)||(r>255)||(g<0)||(g>255)||(b<0)||(b>255)) {
-
-		fprintf(stderr, _("Specified color values should be "
-					"between 00 and FF.\n"));
-		exit(1);
-	    }
-
-	    screen.background_is_from_cmdline = TRUE;
-	    mainProject->background.red = r*257;
-    	    mainProject->background.green = g*257;
-    	    mainProject->background.blue = b*257;
-
-	    break;
-	case 'f' :	// Set layer colors to this color (foreground color)
-	    if (optarg == NULL) {
-		fprintf(stderr, _("You must give an foreground color in the hex-format <#RRGGBB> or <#RRGGBBAA>.\n"));
-		exit(1);
-	    }
-	    if (((strlen (optarg) != 7)&&(strlen (optarg) != 9))||(optarg[0]!='#')) {
-		fprintf(stderr, _("Specified color format is not recognized.\n"));
-		exit(1);
-	    }
-	    r=g=b=a=-1;
-	    if(strlen(optarg)==7){
-		sscanf (optarg,"#%2x%2x%2x",&r,&g,&b);
-		a=177;
-	    }
-	    else{
-		sscanf (optarg,"#%2x%2x%2x%2x",&r,&g,&b,&a);
-	    }
-
-	    if ( (r<0)||(r>255)||(g<0)||(g>255)||(b<0)||(b>255)||(a<0)||(a>255) ) {
-
-		fprintf(stderr, _("Specified color values should be between 0x00 (0) and 0xFF (255).\n"));
-		exit(1);
-	    }
-	    mainDefaultColors[layerctr].red   = r;
-	    mainDefaultColors[layerctr].green = g;
-	    mainDefaultColors[layerctr].blue  = b;
-	    mainDefaultColors[layerctr].alpha = a;
-	    layerctr++;
-	    /* just reset the counter back to 0 if we read too many */
-	    if (layerctr == NUMBER_OF_DEFAULT_COLORS)
-	    	layerctr = 0;
-	    break;
-	case 'r' :	// Set initial orientation for all layers (rotation)
-	    if (optarg == NULL) {
-		fprintf(stderr, _("You must give the initial rotation angle\n"));
-		exit(1);
-	    }
-	    errno = 0;
-	    initial_rotation = (gdouble)strtod(optarg, &rest);
-	    if (errno) {
-		perror(_("Rotate"));
-		exit(1);
-	    }
-	    if (*rest) {
-		fprintf(stderr, _("Failed parsing rotate value\n"));
-		exit(1);
-	    }
-	    break;
-	case 'm' :	// Set initial mirroring state for all layers
-	    if (optarg == NULL) {
-		fprintf(stderr, _("You must give the axis to mirror about\n"));
-		exit(1);
-	    }
-	    if (strchr(optarg, 'x') != NULL || strchr(optarg, 'X') != NULL) {
-		initial_mirror_x = TRUE;
-	    }
-	    if (strchr(optarg, 'y') != NULL || strchr(optarg, 'Y') != NULL) {
-		initial_mirror_y = TRUE;
-	    }
-	    if (!(initial_mirror_x || initial_mirror_y)) {
-		fprintf(stderr, _("Failed parsing mirror axis\n"));
-		exit(1);
-	    }
-	    break;
-	case 'l' :
-	    if (optarg == NULL) {
-		fprintf(stderr, _("You must give a filename to send log to\n"));
-		exit(1);
-	    }
-	    logToFileOption = TRUE;
-	    logToFileFilename = optarg;
-	    break;
-    	case 'o' :
-	    if (optarg == NULL) {
-		fprintf(stderr, _("You must give a filename to export to.\n"));
-		exit(1);
-	    }
-	    exportFilename = optarg;
-	    break;
-	case 'p' :
-	    if (optarg == NULL) {
-		fprintf(stderr, _("You must give a project filename\n"));
-		exit(1);
-	    }
-	    project_filename = optarg;
-	    break;
-	case 't' :
-	    if (optarg == NULL) {
-		fprintf(stderr, _("You must give a filename to read the tools from.\n"));
-		exit(1);
-	    }
-	    if (!gerbv_process_tools_file(optarg)) {
-		fprintf(stderr, _("*** ERROR processing tools file \"%s\".\n"), optarg);
-		fprintf(stderr, _("Make sure all lines of the file are formatted like this:\n"
-			"T01 0.024\nT02 0.032\nT03 0.040\n...\n"
-			"*** EXITING to prevent erroneous display.\n"));
-		exit(1);
-	    }
-	    break;
-	case 'T' :	// Translate the layer
-	    if (optarg == NULL) {
-		fprintf(stderr, _("You must give a translation in the format "
-					"<XxY> or <X;Y>.\n"));
-		exit(1);
-	    }
-	    if (strlen (optarg) > 30) {
-		fprintf(stderr, _("The translation format is not recognized.\n"));
-		exit(1);
-	    }
-
-	    float transX = 0, transY = 0, rotate = 0;
-
-	    care_for_x_in_cords(optarg);
-	    sscanf(optarg, "%f;%fr%f", &transX, &transY, &rotate);
-	    transX /= input_divisor;
-	    transY /= input_divisor;
-	    mainDefaultTransformations[transformCount].translateX = transX;
-	    mainDefaultTransformations[transformCount].translateY = transY;
-	    mainDefaultTransformations[transformCount].rotation   = DEG2RAD(rotate);
-	    transformCount++;
-	    /* just reset the counter back to 0 if we read too many */
-	    if (transformCount == NUMBER_OF_DEFAULT_TRANSFORMATIONS)
-	    	transformCount = 0;
-	    break;
-	case 'u':
-	    if (unit_flag_counter == 1)
-		    /* Length unit flag occurred only once and processed */
-		    break;
-
-	    /* Length unit flag occurred more than once, process each one */
-	    if (!getopt_lengh_unit(optarg, &input_divisor, &screen))
-		GERB_COMPILE_WARNING(
-			_("Unrecognized length unit \"%s\" in command line"),
-			optarg);
-
-	    break;
-
-	case 'w':
-	    userSuppliedWindowInPixels = TRUE;
-    	case 'W' :
-	    if (optarg == NULL) {
-		fprintf(stderr, _("You must give a window size in the format <width x height>.\n"));
-		exit(1);
-	    }
-	    if (strlen (optarg) > 20) {
-		fprintf(stderr, _("Specified window size is not recognized.\n"));
-		exit(1);
-	    }
-	    sscanf (optarg, "%fx%f", &userSuppliedWidth, &userSuppliedHeight);
-	    if (((userSuppliedWidth < 0.001) || (userSuppliedHeight < 0.001)) ||
-		((userSuppliedWidth > 2000) || (userSuppliedHeight > 2000))) {
-		fprintf(stderr, _("Specified window size is out of bounds.\n"));
-		exit(1);
-	    }
-	    userSuppliedWindow = TRUE;
-	    break;
-	case 'x' :
-	    if (optarg == NULL) {
-		fprintf(stderr, _("You must supply an export type.\n"));
-		exit(1);
-	    }
-
-	    for (i = 0; export_type_names[i] != NULL; i++) {
-		if (strcmp (optarg, export_type_names[i]) == 0) {
-		    exportType = i;
-		    break;
-		}
-	    }
-
-	    if (exportType == EXP_TYPE_NONE) {
-		fprintf(stderr, _("Unrecognized \"%s\" export type.\n"),
-				optarg);
-		exit(1);				
-	    }
-	    break;
-	case 'd':
-	    screen.dump_parsed_image = 1;
-	    break;
-	case '?':
-	case 'h':
-	    gerbv_print_help();
-
-	    exit(1);
-	    break;
-	default :
-	    /* This should not be reached */
-	    GERB_COMPILE_WARNING(_("Not handled option '%c' in command line"),
-			    read_opt);
-	}
+            case 'B':
+                if (optarg == NULL) {
+                    fprintf(stderr, _("You must specify the border in the format <alpha>.\n"));
+                    exit(1);
+                }
+                if (strlen(optarg) > 10) {
+                    fprintf(stderr, _("Specified border is not recognized.\n"));
+                    exit(1);
+                }
+                sscanf(optarg, "%f", &userSuppliedBorder);
+                if (userSuppliedBorder < 0) {
+                    fprintf(stderr, _("Specified border is smaller than zero!\n"));
+                    exit(1);
+                }
+                userSuppliedBorder /= 100.0;
+                break;
+            case 'D':
+                if (optarg == NULL) {
+                    fprintf(stderr, _("You must give an resolution in the format <DPI_XxDPI_Y> or <DPI_X_and_Y>.\n"));
+                    exit(1);
+                }
+                if (strlen(optarg) > 20) {
+                    fprintf(stderr, _("Specified resolution is not recognized.\n"));
+                    exit(1);
+                }
+                if (strchr(optarg, 'x') != NULL) {
+                    sscanf(optarg, "%fx%f", &userSuppliedDpiX, &userSuppliedDpiY);
+                } else {
+                    sscanf(optarg, "%f", &userSuppliedDpiX);
+                    userSuppliedDpiY = userSuppliedDpiX;
+                }
+                if ((userSuppliedDpiX <= 0) || (userSuppliedDpiY <= 0)) {
+                    fprintf(stderr, _("Specified resolution should be greater than 0.\n"));
+                    exit(1);
+                }
+                userSuppliedDpi = TRUE;
+                break;
+            case 'O':
+                if (optarg == NULL) {
+                    fprintf(
+                        stderr, _("You must give an origin in the format "
+                                  "<XxY> or <X;Y>.\n")
+                    );
+                    exit(1);
+                }
+                if (strlen(optarg) > 20) {
+                    fprintf(stderr, _("Specified origin is not recognized.\n"));
+                    exit(1);
+                }
+
+                care_for_x_in_cords(optarg);
+                sscanf(optarg, "%f;%f", &userSuppliedOriginX, &userSuppliedOriginY);
+                userSuppliedOriginX /= input_divisor;
+                userSuppliedOriginY /= input_divisor;
+                userSuppliedOrigin = TRUE;
+                break;
+            case 'V':
+                printf(_("gerbv version %s\n"), VERSION);
+                printf(
+                    _("Copyright (C) 2001-2008 by Stefan Petersen\n"
+                      "and the respective original authors listed in the source files.\n")
+                );
+                exit(0);
+            case 'a': userSuppliedAntiAlias = TRUE; break;
+            case 'b':  // Set background to this color
+                if (optarg == NULL) {
+                    fprintf(
+                        stderr, _("You must give an background color "
+                                  "in the hex-format <#RRGGBB>.\n")
+                    );
+                    exit(1);
+                }
+                if ((strlen(optarg) != 7) || (optarg[0] != '#')) {
+                    fprintf(
+                        stderr, _("Specified color format "
+                                  "is not recognized.\n")
+                    );
+                    exit(1);
+                }
+                r = g = b = -1;
+                sscanf(optarg, "#%2x%2x%2x", &r, &g, &b);
+                if ((r < 0) || (r > 255) || (g < 0) || (g > 255) || (b < 0) || (b > 255)) {
+
+                    fprintf(
+                        stderr, _("Specified color values should be "
+                                  "between 00 and FF.\n")
+                    );
+                    exit(1);
+                }
+
+                screen.background_is_from_cmdline = TRUE;
+                mainProject->background.red       = r * 257;
+                mainProject->background.green     = g * 257;
+                mainProject->background.blue      = b * 257;
+
+                break;
+            case 'f':  // Set layer colors to this color (foreground color)
+                if (optarg == NULL) {
+                    fprintf(
+                        stderr, _("You must give an foreground color in the hex-format <#RRGGBB> or <#RRGGBBAA>.\n")
+                    );
+                    exit(1);
+                }
+                if (((strlen(optarg) != 7) && (strlen(optarg) != 9)) || (optarg[0] != '#')) {
+                    fprintf(stderr, _("Specified color format is not recognized.\n"));
+                    exit(1);
+                }
+                r = g = b = a = -1;
+                if (strlen(optarg) == 7) {
+                    sscanf(optarg, "#%2x%2x%2x", &r, &g, &b);
+                    a = 177;
+                } else {
+                    sscanf(optarg, "#%2x%2x%2x%2x", &r, &g, &b, &a);
+                }
+
+                if ((r < 0) || (r > 255) || (g < 0) || (g > 255) || (b < 0) || (b > 255) || (a < 0) || (a > 255)) {
+
+                    fprintf(stderr, _("Specified color values should be between 0x00 (0) and 0xFF (255).\n"));
+                    exit(1);
+                }
+                mainDefaultColors[layerctr].red   = r;
+                mainDefaultColors[layerctr].green = g;
+                mainDefaultColors[layerctr].blue  = b;
+                mainDefaultColors[layerctr].alpha = a;
+                layerctr++;
+                /* just reset the counter back to 0 if we read too many */
+                if (layerctr == NUMBER_OF_DEFAULT_COLORS)
+                    layerctr = 0;
+                break;
+            case 'r':  // Set initial orientation for all layers (rotation)
+                if (optarg == NULL) {
+                    fprintf(stderr, _("You must give the initial rotation angle\n"));
+                    exit(1);
+                }
+                errno            = 0;
+                initial_rotation = (gdouble)strtod(optarg, &rest);
+                if (errno) {
+                    perror(_("Rotate"));
+                    exit(1);
+                }
+                if (*rest) {
+                    fprintf(stderr, _("Failed parsing rotate value\n"));
+                    exit(1);
+                }
+                break;
+            case 'm':  // Set initial mirroring state for all layers
+                if (optarg == NULL) {
+                    fprintf(stderr, _("You must give the axis to mirror about\n"));
+                    exit(1);
+                }
+                if (strchr(optarg, 'x') != NULL || strchr(optarg, 'X') != NULL) {
+                    initial_mirror_x = TRUE;
+                }
+                if (strchr(optarg, 'y') != NULL || strchr(optarg, 'Y') != NULL) {
+                    initial_mirror_y = TRUE;
+                }
+                if (!(initial_mirror_x || initial_mirror_y)) {
+                    fprintf(stderr, _("Failed parsing mirror axis\n"));
+                    exit(1);
+                }
+                break;
+            case 'l':
+                if (optarg == NULL) {
+                    fprintf(stderr, _("You must give a filename to send log to\n"));
+                    exit(1);
+                }
+                logToFileOption   = TRUE;
+                logToFileFilename = optarg;
+                break;
+            case 'o':
+                if (optarg == NULL) {
+                    fprintf(stderr, _("You must give a filename to export to.\n"));
+                    exit(1);
+                }
+                exportFilename = optarg;
+                break;
+            case 'p':
+                if (optarg == NULL) {
+                    fprintf(stderr, _("You must give a project filename\n"));
+                    exit(1);
+                }
+                project_filename = optarg;
+                break;
+            case 't':
+                if (optarg == NULL) {
+                    fprintf(stderr, _("You must give a filename to read the tools from.\n"));
+                    exit(1);
+                }
+                if (!gerbv_process_tools_file(optarg)) {
+                    fprintf(stderr, _("*** ERROR processing tools file \"%s\".\n"), optarg);
+                    fprintf(
+                        stderr, _("Make sure all lines of the file are formatted like this:\n"
+                                  "T01 0.024\nT02 0.032\nT03 0.040\n...\n"
+                                  "*** EXITING to prevent erroneous display.\n")
+                    );
+                    exit(1);
+                }
+                break;
+            case 'T':  // Translate the layer
+                if (optarg == NULL) {
+                    fprintf(
+                        stderr, _("You must give a translation in the format "
+                                  "<XxY> or <X;Y>.\n")
+                    );
+                    exit(1);
+                }
+                if (strlen(optarg) > 30) {
+                    fprintf(stderr, _("The translation format is not recognized.\n"));
+                    exit(1);
+                }
+
+                float transX = 0, transY = 0, rotate = 0;
+
+                care_for_x_in_cords(optarg);
+                sscanf(optarg, "%f;%fr%f", &transX, &transY, &rotate);
+                transX /= input_divisor;
+                transY /= input_divisor;
+                mainDefaultTransformations[transformCount].translateX = transX;
+                mainDefaultTransformations[transformCount].translateY = transY;
+                mainDefaultTransformations[transformCount].rotation   = DEG2RAD(rotate);
+                transformCount++;
+                /* just reset the counter back to 0 if we read too many */
+                if (transformCount == NUMBER_OF_DEFAULT_TRANSFORMATIONS)
+                    transformCount = 0;
+                break;
+            case 'u':
+                if (unit_flag_counter == 1)
+                    /* Length unit flag occurred only once and processed */
+                    break;
+
+                /* Length unit flag occurred more than once, process each one */
+                if (!getopt_lengh_unit(optarg, &input_divisor, &screen))
+                    GERB_COMPILE_WARNING(_("Unrecognized length unit \"%s\" in command line"), optarg);
+
+                break;
+
+            case 'w': userSuppliedWindowInPixels = TRUE;
+            case 'W':
+                if (optarg == NULL) {
+                    fprintf(stderr, _("You must give a window size in the format <width x height>.\n"));
+                    exit(1);
+                }
+                if (strlen(optarg) > 20) {
+                    fprintf(stderr, _("Specified window size is not recognized.\n"));
+                    exit(1);
+                }
+                sscanf(optarg, "%fx%f", &userSuppliedWidth, &userSuppliedHeight);
+                if (((userSuppliedWidth < 0.001) || (userSuppliedHeight < 0.001))
+                    || ((userSuppliedWidth > 2000) || (userSuppliedHeight > 2000))) {
+                    fprintf(stderr, _("Specified window size is out of bounds.\n"));
+                    exit(1);
+                }
+                userSuppliedWindow = TRUE;
+                break;
+            case 'x':
+                if (optarg == NULL) {
+                    fprintf(stderr, _("You must supply an export type.\n"));
+                    exit(1);
+                }
+
+                for (i = 0; export_type_names[i] != NULL; i++) {
+                    if (strcmp(optarg, export_type_names[i]) == 0) {
+                        exportType = i;
+                        break;
+                    }
+                }
+
+                if (exportType == EXP_TYPE_NONE) {
+                    fprintf(stderr, _("Unrecognized \"%s\" export type.\n"), optarg);
+                    exit(1);
+                }
+                break;
+            case 'd': screen.dump_parsed_image = 1; break;
+            case '?':
+            case 'h':
+                gerbv_print_help();
+
+                exit(1);
+                break;
+            default:
+                /* This should not be reached */
+                GERB_COMPILE_WARNING(_("Not handled option '%c' in command line"), read_opt);
+        }
     }
 
     /*
      * If no project_filename and only file ends in .gvp, use as project file. -erco 02/20/2020
      */
-    if ( !project_filename &&                       // project not set?
-         optind == (argc-1) &&                      // only one file specified?
-         gerbv_endswith(argv[optind], ".gvp") ) {   // only file ends in .gvp?
+    if (!project_filename &&                     // project not set?
+        optind == (argc - 1) &&                  // only one file specified?
+        gerbv_endswith(argv[optind], ".gvp")) {  // only file ends in .gvp?
         project_filename = argv[optind];
     }
-    
+
     /*
      * If project is given, load that one and use it for files and colors.
      * Else load files (eventually) given on the command line.
@@ -914,447 +876,428 @@ main(int argc, char *argv[])
      */
 
     if (project_filename) {
-	dprintf(_("Loading project %s...\n"), project_filename);
-	/* calculate the absolute pathname to the project if the user
-	   used a relative path */
-	g_free (mainProject->path);
-	if (!g_path_is_absolute(project_filename)) {
-	    gchar *currentDir = g_get_current_dir ();
-	    gchar *fullName = g_build_filename (currentDir,
-						project_filename, NULL);
-	    main_open_project_from_filename (mainProject, fullName);
-	    mainProject->path = g_path_get_dirname (fullName);
-	    g_free (fullName);
-	    g_free (currentDir);
-	} else {
-	    main_open_project_from_filename (mainProject, project_filename);
-	    mainProject->path = g_path_get_dirname (project_filename);
-	}
+        dprintf(_("Loading project %s...\n"), project_filename);
+        /* calculate the absolute pathname to the project if the user
+           used a relative path */
+        g_free(mainProject->path);
+        if (!g_path_is_absolute(project_filename)) {
+            gchar* currentDir = g_get_current_dir();
+            gchar* fullName   = g_build_filename(currentDir, project_filename, NULL);
+            main_open_project_from_filename(mainProject, fullName);
+            mainProject->path = g_path_get_dirname(fullName);
+            g_free(fullName);
+            g_free(currentDir);
+        } else {
+            main_open_project_from_filename(mainProject, project_filename);
+            mainProject->path = g_path_get_dirname(project_filename);
+        }
     } else {
-    	gint loadedIndex = 0;
-	for(i = optind ; i < argc; i++) {
-	    g_free (mainProject->path);
-	    if (!g_path_is_absolute(argv[i])) {
-		gchar *currentDir = g_get_current_dir ();
-		gchar *fullName = g_build_filename (currentDir,
-						    argv[i], NULL);
-		gerbv_open_layer_from_filename_with_color (mainProject, fullName,
-			mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].red*257,
-			mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].green*257,
-			mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].blue*257,
-			mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].alpha*257);
-		mainProject->path = g_path_get_dirname (fullName);
-		g_free (fullName);
-		g_free (currentDir);
-	    } else {
-		gerbv_open_layer_from_filename_with_color (mainProject, argv[i],
-			mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].red*257,
-			mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].green*257,
-			mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].blue*257,
-			mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].alpha*257);
-		mainProject->path = g_path_get_dirname (argv[i]);
-	    }
-	    loadedIndex++;
-	}
+        gint loadedIndex = 0;
+        for (i = optind; i < argc; i++) {
+            g_free(mainProject->path);
+            if (!g_path_is_absolute(argv[i])) {
+                gchar* currentDir = g_get_current_dir();
+                gchar* fullName   = g_build_filename(currentDir, argv[i], NULL);
+                gerbv_open_layer_from_filename_with_color(
+                    mainProject, fullName, mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].red * 257,
+                    mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].green * 257,
+                    mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].blue * 257,
+                    mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].alpha * 257
+                );
+                mainProject->path = g_path_get_dirname(fullName);
+                g_free(fullName);
+                g_free(currentDir);
+            } else {
+                gerbv_open_layer_from_filename_with_color(
+                    mainProject, argv[i], mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].red * 257,
+                    mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].green * 257,
+                    mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].blue * 257,
+                    mainDefaultColors[loadedIndex % NUMBER_OF_DEFAULT_COLORS].alpha * 257
+                );
+                mainProject->path = g_path_get_dirname(argv[i]);
+            }
+            loadedIndex++;
+        }
     }
 
     if (initial_rotation != 0.0) {
-	/* Set initial layer orientation */
+        /* Set initial layer orientation */
 
-	gdouble initial_radians = DEG2RAD(initial_rotation);
+        gdouble initial_radians = DEG2RAD(initial_rotation);
 
-	dprintf("Rotating all layers by %.0f degrees\n", (float) initial_rotation);
-	for(i = 0; i < mainProject->max_files; i++) {
-	    if (mainProject->file[i])
-		mainProject->file[i]->transform.rotation = initial_radians;
-	}
+        dprintf("Rotating all layers by %.0f degrees\n", (float)initial_rotation);
+        for (i = 0; i < mainProject->max_files; i++) {
+            if (mainProject->file[i])
+                mainProject->file[i]->transform.rotation = initial_radians;
+        }
     }
 
     if (initial_mirror_x || initial_mirror_y) {
-	/* Set initial mirroring of all layers */
-
-	if (initial_mirror_x) {
-	    dprintf("Mirroring all layers about x axis\n");
-	}
-	if (initial_mirror_y) {
-	    dprintf("Mirroring all layers about y axis\n");
-	}
-
-	for (i = 0; i < mainProject->max_files; i++) {
-	    if (mainProject->file[i]) {
-		mainProject->file[i]->transform.mirrorAroundX = initial_mirror_x;
-		mainProject->file[i]->transform.mirrorAroundY = initial_mirror_y;
-	    }
-	}
+        /* Set initial mirroring of all layers */
+
+        if (initial_mirror_x) {
+            dprintf("Mirroring all layers about x axis\n");
+        }
+        if (initial_mirror_y) {
+            dprintf("Mirroring all layers about y axis\n");
+        }
+
+        for (i = 0; i < mainProject->max_files; i++) {
+            if (mainProject->file[i]) {
+                mainProject->file[i]->transform.mirrorAroundX = initial_mirror_x;
+                mainProject->file[i]->transform.mirrorAroundY = initial_mirror_y;
+            }
+        }
     }
 
     if (exportType != EXP_TYPE_NONE) {
-	/* load the info struct with the default values */
-
-	if (!exportFilename)
-		exportFilename = export_def_file_names[exportType];
-
-	gerbv_render_size_t bb;
-	gerbv_render_get_boundingbox(mainProject, &bb);
-	// Set origin to the left-bottom corner if it is not specified
-	if(!userSuppliedOrigin){
-	    userSuppliedOriginX = bb.left;
-	    userSuppliedOriginY = bb.top;
-	}
-
-	float width  = bb.right  - userSuppliedOriginX + 0.001;	// Plus a little extra to prevent from 
-	float height = bb.bottom - userSuppliedOriginY + 0.001; // missing items due to round-off errors
-	// If the user did not specify a height and width, autoscale w&h till full size from origin.
-	if(!userSuppliedWindow){
-	    userSuppliedWidth  = width;
-	    userSuppliedHeight = height;
-	}else{
-	    // If size was specified in pixels, and no resolution was specified, autoscale resolution till fit
-	    if( (!userSuppliedDpi)&& userSuppliedWindowInPixels){
-		userSuppliedDpiX = MIN((userSuppliedWidth-0.5)/width,
-			(userSuppliedHeight-0.5)/height);
-		userSuppliedDpiY = userSuppliedDpiX;
-		userSuppliedOriginX -= 0.5/userSuppliedDpiX;
-		userSuppliedOriginY -= 0.5/userSuppliedDpiY;
-	    }
-	}
-
-	// Add the border size (if there is one)
-	if(userSuppliedBorder!=0){
-	    // If supplied in inches, add a border around the image
-	    if(!userSuppliedWindowInPixels){
-	      userSuppliedOriginX -= (userSuppliedWidth*userSuppliedBorder)/2.0;
-		userSuppliedOriginY -= (userSuppliedHeight*userSuppliedBorder)/2.0;
-		userSuppliedWidth  += userSuppliedWidth*userSuppliedBorder;
-		userSuppliedHeight  += userSuppliedHeight*userSuppliedBorder;
-	    }
-	    // If supplied in pixels, shrink image content for border_size
-	    else{
-	      userSuppliedOriginX -= ((userSuppliedWidth/userSuppliedDpiX)*userSuppliedBorder)/2.0;
-		userSuppliedOriginY -= ((userSuppliedHeight/userSuppliedDpiX)*userSuppliedBorder)/2.0;
-		userSuppliedDpiX -= (userSuppliedDpiX*userSuppliedBorder);
-		userSuppliedDpiY -= (userSuppliedDpiY*userSuppliedBorder);
-	    }
-	}
-	
-	if(!userSuppliedWindowInPixels){
-	    userSuppliedWidth  *= userSuppliedDpiX;
-	    userSuppliedHeight *= userSuppliedDpiY;
-	}
-	
-	// Make sure there is something valid in it. It could become negative if 
-	// the userSuppliedOrigin is further than the bb.right or bb.top.
-	if(userSuppliedWidth <=0)
-	    userSuppliedWidth  = 1;
-	if(userSuppliedHeight <=0)
-	    userSuppliedHeight = 1;
-
-
-	gerbv_render_info_t renderInfo = {userSuppliedDpiX, userSuppliedDpiY, 
-	    userSuppliedOriginX, userSuppliedOriginY,
-	    userSuppliedAntiAlias? GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY: GERBV_RENDER_TYPE_CAIRO_NORMAL,
-	    userSuppliedWidth,userSuppliedHeight };
-	
-	switch (exportType) {
-	case EXP_TYPE_PNG:
-	    gerbv_export_png_file_from_project(mainProject,
-			    &renderInfo, exportFilename);
-	    break;
-	case EXP_TYPE_PDF:
-	    gerbv_export_pdf_file_from_project(mainProject,
-			    &renderInfo, exportFilename);
-	    break;
-	case EXP_TYPE_SVG:
-	    gerbv_export_svg_file_from_project(mainProject,
-			    &renderInfo, exportFilename);
-	    break;
-	case EXP_TYPE_PS:
-	    gerbv_export_postscript_file_from_project(mainProject,
-			    &renderInfo, exportFilename);
-	    break;
-	case EXP_TYPE_RS274X:
-	case EXP_TYPE_DRILL:
-	case EXP_TYPE_IDRILL:
-	    if (!mainProject->file[0]->image) {
-		fprintf(stderr, _("A valid file was not loaded.\n"));
-		exit(1);
-	    }
-
-	    exportImage = gerbv_image_duplicate_image(
-			    mainProject->file[0]->image,
-			    &mainDefaultTransformations[0]);
-
-	    /* If more than one file, merge them before exporting */
-	    for (i = mainProject->last_loaded; i > 0; i--) {
-		if (mainProject->file[i])
-			gerbv_image_copy_image(mainProject->file[i]->image,
-				&mainDefaultTransformations[i], exportImage);
-	    }
-
-	    switch (exportType) {
-	    case EXP_TYPE_RS274X:
-		gerbv_export_rs274x_file_from_image(exportFilename,
-			exportImage, &mainProject->file[0]->transform);
-		break;
-	    case EXP_TYPE_DRILL:
-		gerbv_export_drill_file_from_image(exportFilename,
-			exportImage, &mainProject->file[0]->transform);
-		break;
-	    case EXP_TYPE_IDRILL:
-		gerbv_export_isel_drill_file_from_image (exportFilename,
-			exportImage, &mainProject->file[0]->transform);
-		break;
-	    default:
-		break;
-	    }
-
-	    gerbv_destroy_image (exportImage);
-	    break;
-	default:
-	    fprintf(stderr, _("A valid file was not loaded.\n"));
-	    exit(1);
-	}
-
-	/* exit now and don't start up gtk if this is a command line export */
-	exit(0);
+        /* load the info struct with the default values */
+
+        if (!exportFilename)
+            exportFilename = export_def_file_names[exportType];
+
+        gerbv_render_size_t bb;
+        gerbv_render_get_boundingbox(mainProject, &bb);
+        // Set origin to the left-bottom corner if it is not specified
+        if (!userSuppliedOrigin) {
+            userSuppliedOriginX = bb.left;
+            userSuppliedOriginY = bb.top;
+        }
+
+        float width  = bb.right - userSuppliedOriginX + 0.001;   // Plus a little extra to prevent from
+        float height = bb.bottom - userSuppliedOriginY + 0.001;  // missing items due to round-off errors
+        // If the user did not specify a height and width, autoscale w&h till full size from origin.
+        if (!userSuppliedWindow) {
+            userSuppliedWidth  = width;
+            userSuppliedHeight = height;
+        } else {
+            // If size was specified in pixels, and no resolution was specified, autoscale resolution till fit
+            if ((!userSuppliedDpi) && userSuppliedWindowInPixels) {
+                userSuppliedDpiX = MIN((userSuppliedWidth - 0.5) / width, (userSuppliedHeight - 0.5) / height);
+                userSuppliedDpiY = userSuppliedDpiX;
+                userSuppliedOriginX -= 0.5 / userSuppliedDpiX;
+                userSuppliedOriginY -= 0.5 / userSuppliedDpiY;
+            }
+        }
+
+        // Add the border size (if there is one)
+        if (userSuppliedBorder != 0) {
+            // If supplied in inches, add a border around the image
+            if (!userSuppliedWindowInPixels) {
+                userSuppliedOriginX -= (userSuppliedWidth * userSuppliedBorder) / 2.0;
+                userSuppliedOriginY -= (userSuppliedHeight * userSuppliedBorder) / 2.0;
+                userSuppliedWidth += userSuppliedWidth * userSuppliedBorder;
+                userSuppliedHeight += userSuppliedHeight * userSuppliedBorder;
+            }
+            // If supplied in pixels, shrink image content for border_size
+            else {
+                userSuppliedOriginX -= ((userSuppliedWidth / userSuppliedDpiX) * userSuppliedBorder) / 2.0;
+                userSuppliedOriginY -= ((userSuppliedHeight / userSuppliedDpiX) * userSuppliedBorder) / 2.0;
+                userSuppliedDpiX -= (userSuppliedDpiX * userSuppliedBorder);
+                userSuppliedDpiY -= (userSuppliedDpiY * userSuppliedBorder);
+            }
+        }
+
+        if (!userSuppliedWindowInPixels) {
+            userSuppliedWidth *= userSuppliedDpiX;
+            userSuppliedHeight *= userSuppliedDpiY;
+        }
+
+        // Make sure there is something valid in it. It could become negative if
+        // the userSuppliedOrigin is further than the bb.right or bb.top.
+        if (userSuppliedWidth <= 0)
+            userSuppliedWidth = 1;
+        if (userSuppliedHeight <= 0)
+            userSuppliedHeight = 1;
+
+        gerbv_render_info_t renderInfo = { userSuppliedDpiX,
+                                           userSuppliedDpiY,
+                                           userSuppliedOriginX,
+                                           userSuppliedOriginY,
+                                           userSuppliedAntiAlias ? GERBV_RENDER_TYPE_CAIRO_HIGH_QUALITY
+                                                                 : GERBV_RENDER_TYPE_CAIRO_NORMAL,
+                                           userSuppliedWidth,
+                                           userSuppliedHeight };
+
+        switch (exportType) {
+            case EXP_TYPE_PNG: gerbv_export_png_file_from_project(mainProject, &renderInfo, exportFilename); break;
+            case EXP_TYPE_PDF: gerbv_export_pdf_file_from_project(mainProject, &renderInfo, exportFilename); break;
+            case EXP_TYPE_SVG: gerbv_export_svg_file_from_project(mainProject, &renderInfo, exportFilename); break;
+            case EXP_TYPE_PS:
+                gerbv_export_postscript_file_from_project(mainProject, &renderInfo, exportFilename);
+                break;
+            case EXP_TYPE_RS274X:
+            case EXP_TYPE_DRILL:
+            case EXP_TYPE_IDRILL:
+                if (!mainProject->file[0]->image) {
+                    fprintf(stderr, _("A valid file was not loaded.\n"));
+                    exit(1);
+                }
+
+                exportImage = gerbv_image_duplicate_image(mainProject->file[0]->image, &mainDefaultTransformations[0]);
+
+                /* If more than one file, merge them before exporting */
+                for (i = mainProject->last_loaded; i > 0; i--) {
+                    if (mainProject->file[i])
+                        gerbv_image_copy_image(
+                            mainProject->file[i]->image, &mainDefaultTransformations[i], exportImage
+                        );
+                }
+
+                switch (exportType) {
+                    case EXP_TYPE_RS274X:
+                        gerbv_export_rs274x_file_from_image(
+                            exportFilename, exportImage, &mainProject->file[0]->transform
+                        );
+                        break;
+                    case EXP_TYPE_DRILL:
+                        gerbv_export_drill_file_from_image(
+                            exportFilename, exportImage, &mainProject->file[0]->transform
+                        );
+                        break;
+                    case EXP_TYPE_IDRILL:
+                        gerbv_export_isel_drill_file_from_image(
+                            exportFilename, exportImage, &mainProject->file[0]->transform
+                        );
+                        break;
+                    default: break;
+                }
+
+                gerbv_destroy_image(exportImage);
+                break;
+            default: fprintf(stderr, _("A valid file was not loaded.\n")); exit(1);
+        }
+
+        /* exit now and don't start up gtk if this is a command line export */
+        exit(0);
     }
-    gtk_init (&argc, &argv);
-    interface_create_gui (req_width, req_height);
-    
+    gtk_init(&argc, &argv);
+    interface_create_gui(req_width, req_height);
+
     /* we've exited the GTK loop, so free all resources */
     render_free_screen_resources();
-    gerbv_destroy_project (mainProject);
+    gerbv_destroy_project(mainProject);
     return 0;
 } /* main */
 
 static int
-getopt_configured(int argc, char * const argv[], const char *optstring,
-		const struct option *longopts, int *longindex)
-{
+getopt_configured(int argc, char* const argv[], const char* optstring, const struct option* longopts, int* longindex) {
 #ifdef HAVE_GETOPT_LONG
-	return getopt_long(argc, argv, optstring, longopts, longindex);
+    return getopt_long(argc, argv, optstring, longopts, longindex);
 #else
-	return getopt(argc, argv, optstring);
+    return getopt(argc, argv, optstring);
 #endif
 }
 
 static int
-getopt_lengh_unit(const char *optarg, double *input_div, gerbv_screen_t *screen)
-{
-	if (strncasecmp(optarg, "mm", 2) == 0) {
-		*input_div = 25.4;
-		screen->unit = GERBV_MMS;
-		screen->unit_is_from_cmdline = TRUE;
-	} else if (strncasecmp(optarg, "mil", 3) == 0) {
-		*input_div = 1000.0;
-		screen->unit = GERBV_MILS;
-		screen->unit_is_from_cmdline = TRUE;
-	} else if (strncasecmp(optarg, "inch", 4) == 0) {
-		*input_div = 1.0;
-		screen->unit = GERBV_INS;
-		screen->unit_is_from_cmdline = TRUE;
-	} else {
-		return 0;
-	}
-
-	return 1;
+getopt_lengh_unit(const char* optarg, double* input_div, gerbv_screen_t* screen) {
+    if (strncasecmp(optarg, "mm", 2) == 0) {
+        *input_div                   = 25.4;
+        screen->unit                 = GERBV_MMS;
+        screen->unit_is_from_cmdline = TRUE;
+    } else if (strncasecmp(optarg, "mil", 3) == 0) {
+        *input_div                   = 1000.0;
+        screen->unit                 = GERBV_MILS;
+        screen->unit_is_from_cmdline = TRUE;
+    } else if (strncasecmp(optarg, "inch", 4) == 0) {
+        *input_div                   = 1.0;
+        screen->unit                 = GERBV_INS;
+        screen->unit_is_from_cmdline = TRUE;
+    } else {
+        return 0;
+    }
+
+    return 1;
 }
 
 static void
-gerbv_print_help(void)
-{
-	printf(_(
-"Usage: gerbv [OPTIONS...] [FILE...]\n"
-"\n"
-"Available options:\n"));
+gerbv_print_help(void) {
+    printf(
+        _("Usage: gerbv [OPTIONS...] [FILE...]\n"
+          "\n"
+          "Available options:\n")
+    );
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -B, --border=<b>        Border around the image in percent of the\n"
-"                          width/height. Defaults to %d%%.\n"),
-			(int)(100*GERBV_DEFAULT_BORDER_COEFF));
+    printf(
+        _("  -B, --border=<b>        Border around the image in percent of the\n"
+          "                          width/height. Defaults to %d%%.\n"),
+        (int)(100 * GERBV_DEFAULT_BORDER_COEFF)
+    );
 #else
-	printf(_(
-"  -B<b>                   Border around the image in percent of the\n"
-"                          width/height. Defaults to %d%%.\n"),
-			(int)(100*GERBV_DEFAULT_BORDER_COEFF));
+    printf(
+        _("  -B<b>                   Border around the image in percent of the\n"
+          "                          width/height. Defaults to %d%%.\n"),
+        (int)(100 * GERBV_DEFAULT_BORDER_COEFF)
+    );
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -D, --dpi=<XxY|R>       Resolution (Dots per inch) for the output\n"
-"                          bitmap. With the format <XxY>, different\n"
-"                          resolutions for X- and Y-direction are used.\n"
-"                          With the format <R>, both are the same.\n"));
+    printf(
+        _("  -D, --dpi=<XxY|R>       Resolution (Dots per inch) for the output\n"
+          "                          bitmap. With the format <XxY>, different\n"
+          "                          resolutions for X- and Y-direction are used.\n"
+          "                          With the format <R>, both are the same.\n")
+    );
 #else
-	printf(_(
-"  -D<XxY|R>               Resolution (Dots per inch) for the output\n"
-"                          bitmap. With the format <XxY>, different\n"
-"                          resolutions for X- and Y-direction are used.\n"
-"                          With the format <R>, both are the same.\n"));
+    printf(
+        _("  -D<XxY|R>               Resolution (Dots per inch) for the output\n"
+          "                          bitmap. With the format <XxY>, different\n"
+          "                          resolutions for X- and Y-direction are used.\n"
+          "                          With the format <R>, both are the same.\n")
+    );
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -O, --origin=<XxY|X;Y>  Use the specified coordinates (in inches)\n"
-"                          for the lower left corner.\n"));
+    printf(
+        _("  -O, --origin=<XxY|X;Y>  Use the specified coordinates (in inches)\n"
+          "                          for the lower left corner.\n")
+    );
 #else
-	printf(_(
-"  -O<XxY|X;Y>             Use the specified coordinates (in inches)\n"
-"                          for the lower left corner.\n"));
+    printf(
+        _("  -O<XxY|X;Y>             Use the specified coordinates (in inches)\n"
+          "                          for the lower left corner.\n")
+    );
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -V, --version           Print version of Gerbv.\n"));
+    printf(_("  -V, --version           Print version of Gerbv.\n"));
 #else
-	printf(_(
-"  -V                      Print version of Gerbv.\n"));
+    printf(_("  -V                      Print version of Gerbv.\n"));
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -a, --antialias         Use antialiasing for generated bitmap output.\n"));
+    printf(_("  -a, --antialias         Use antialiasing for generated bitmap output.\n"));
 #else
-	printf(_(
-"  -a                      Use antialiasing for generated bitmap output.\n"));
+    printf(_("  -a                      Use antialiasing for generated bitmap output.\n"));
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -b, --background=<hex>  Use background color <hex> (like #RRGGBB).\n"));
+    printf(_("  -b, --background=<hex>  Use background color <hex> (like #RRGGBB).\n"));
 #else
-	printf(_(
-"  -b<hexcolor>            Use background color <hexcolor> (like #RRGGBB).\n"));
+    printf(_("  -b<hexcolor>            Use background color <hexcolor> (like #RRGGBB).\n"));
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -f, --foreground=<hex>  Use foreground color <hex> (like #RRGGBB or\n"
-"                          #RRGGBBAA for setting the alpha).\n"
-"                          Use multiple -f flags to set the color for\n"
-"                          multiple layers.\n"));
+    printf(
+        _("  -f, --foreground=<hex>  Use foreground color <hex> (like #RRGGBB or\n"
+          "                          #RRGGBBAA for setting the alpha).\n"
+          "                          Use multiple -f flags to set the color for\n"
+          "                          multiple layers.\n")
+    );
 #else
-	printf(_(
-"  -f<hexcolor>            Use foreground color <hexcolor> (like #RRGGBB or\n"
-"                          #RRGGBBAA for setting the alpha).\n"
-"                          Use multiple -f flags to set the color for\n"
-"                          multiple layers.\n"));
+    printf(
+        _("  -f<hexcolor>            Use foreground color <hexcolor> (like #RRGGBB or\n"
+          "                          #RRGGBBAA for setting the alpha).\n"
+          "                          Use multiple -f flags to set the color for\n"
+          "                          multiple layers.\n")
+    );
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -r, --rotate=<degree>   Set initial orientation for all layers.\n"));
+    printf(_("  -r, --rotate=<degree>   Set initial orientation for all layers.\n"));
 #else
-	printf(_(
-"  -r<degree>              Set initial orientation for all layers.\n"));
+    printf(_("  -r<degree>              Set initial orientation for all layers.\n"));
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -m, --mirror=<axis>     Set initial mirroring axis (X or Y).\n"));
+    printf(_("  -m, --mirror=<axis>     Set initial mirroring axis (X or Y).\n"));
 #else
-	printf(_(
-"  -m<axis>                Set initial mirroring axis (X or Y).\n"));
+    printf(_("  -m<axis>                Set initial mirroring axis (X or Y).\n"));
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -h, --help              Print this help message.\n"));
+    printf(_("  -h, --help              Print this help message.\n"));
 #else
-	printf(_(
-"  -h                      Print this help message.\n"));
+    printf(_("  -h                      Print this help message.\n"));
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -l, --log=<logfile>     Send error messages to <logfile>.\n"));
+    printf(_("  -l, --log=<logfile>     Send error messages to <logfile>.\n"));
 #else
-	printf(_(
-"  -l<logfile>             Send error messages to <logfile>.\n"));
+    printf(_("  -l<logfile>             Send error messages to <logfile>.\n"));
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -o, --output=<filename> Export to <filename>.\n"));
+    printf(_("  -o, --output=<filename> Export to <filename>.\n"));
 #else
-	printf(_(
-"  -o<filename>            Export to <filename>.\n"));
+    printf(_("  -o<filename>            Export to <filename>.\n"));
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -p, --project=<prjfile> Load project file <prjfile>.\n"));
+    printf(_("  -p, --project=<prjfile> Load project file <prjfile>.\n"));
 #else
-	printf(_(
-"  -p<prjfile>             Load project file <prjfile>.\n"));
+    printf(_("  -p<prjfile>             Load project file <prjfile>.\n"));
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -u, --units=<inch|mm|mil>\n"
-"                          Use given unit for coordinates.\n"
-"                          Default to inch.\n"));
+    printf(
+        _("  -u, --units=<inch|mm|mil>\n"
+          "                          Use given unit for coordinates.\n"
+          "                          Default to inch.\n")
+    );
 #else
-	printf(_(
-"  -u<inch|mm|mil>         Use given unit for coordinates.\n"
-"                          Default to inch.\n"));
+    printf(
+        _("  -u<inch|mm|mil>         Use given unit for coordinates.\n"
+          "                          Default to inch.\n")
+    );
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -W, --window_inch=<WxH> Window size in inches <WxH> for the exported image.\n"));
+    printf(_("  -W, --window_inch=<WxH> Window size in inches <WxH> for the exported image.\n"));
 #else
-	printf(_(
-"  -W<WxH>                 Window size in inches <WxH> for the exported image.\n"));
+    printf(_("  -W<WxH>                 Window size in inches <WxH> for the exported image.\n"));
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -w, --window=<WxH>      Window size in pixels <WxH> for the exported image.\n"
-"                          Autoscales to fit if no resolution is specified.\n"
-"                          If a resolution is specified, it will clip\n"
-"                          exported image.\n"));
+    printf(
+        _("  -w, --window=<WxH>      Window size in pixels <WxH> for the exported image.\n"
+          "                          Autoscales to fit if no resolution is specified.\n"
+          "                          If a resolution is specified, it will clip\n"
+          "                          exported image.\n")
+    );
 #else
-	printf(_(
-"  -w<WxH>                 Window size in pixels <WxH> for the exported image.\n"
-"                          Autoscales to fit if no resolution is specified.\n"
-"                          If a resolution is specified, it will clip\n"
-"                          exported image.\n"));
+    printf(
+        _("  -w<WxH>                 Window size in pixels <WxH> for the exported image.\n"
+          "                          Autoscales to fit if no resolution is specified.\n"
+          "                          If a resolution is specified, it will clip\n"
+          "                          exported image.\n")
+    );
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -t, --tools=<toolfile>  Read Excellon tools from file <toolfile>.\n"));
+    printf(_("  -t, --tools=<toolfile>  Read Excellon tools from file <toolfile>.\n"));
 #else
-	printf(_(
-"  -t<toolfile>            Read Excellon tools from file <toolfile>\n"));
+    printf(_("  -t<toolfile>            Read Excellon tools from file <toolfile>\n"));
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -T, --translate=<XxYrR| Translate image by X and Y and rotate by R degree.\n"
-"                   X;YrR> Useful for arranging panels.\n"
-"                          Use multiple -T flags for multiple layers.\n"
-"                          Only evaluated when exporting as RS274X or drill.\n"));
+    printf(
+        _("  -T, --translate=<XxYrR| Translate image by X and Y and rotate by R degree.\n"
+          "                   X;YrR> Useful for arranging panels.\n"
+          "                          Use multiple -T flags for multiple layers.\n"
+          "                          Only evaluated when exporting as RS274X or drill.\n")
+    );
 #else
-	printf(_(
-"  -T<XxYrR|X;YrR>         Translate image by X and Y and rotate by R degree.\n"
-"                          Useful for arranging panels.\n"
-"                          Use multiple -T flags for multiple files.\n"
-"                          Only evaluated when exporting as RS274X or drill.\n"));
+    printf(
+        _("  -T<XxYrR|X;YrR>         Translate image by X and Y and rotate by R degree.\n"
+          "                          Useful for arranging panels.\n"
+          "                          Use multiple -T flags for multiple files.\n"
+          "                          Only evaluated when exporting as RS274X or drill.\n")
+    );
 #endif
 
 #ifdef HAVE_GETOPT_LONG
-	printf(_(
-"  -x, --export=<png|pdf|ps|svg|rs274x|drill|idrill>\n"
-"                          Export a rendered picture to a file with\n"
-"                          the specified format.\n"));
+    printf(
+        _("  -x, --export=<png|pdf|ps|svg|rs274x|drill|idrill>\n"
+          "                          Export a rendered picture to a file with\n"
+          "                          the specified format.\n")
+    );
 #else
-	printf(_(
-"  -x<png|pdf|ps|svg|      Export a rendered picture to a file with\n"
-"     rs274x|drill|        the specified format.\n"
-"     idrill>\n"));
+    printf(
+        _("  -x<png|pdf|ps|svg|      Export a rendered picture to a file with\n"
+          "     rs274x|drill|        the specified format.\n"
+          "     idrill>\n")
+    );
 #endif
-
 }
diff --git a/src/main.h b/src/main.h
index 5967b3f..f930905 100644
--- a/src/main.h
+++ b/src/main.h
@@ -33,91 +33,118 @@
 extern "C" {
 #endif
 
-typedef enum {GERBV_MILS, GERBV_MMS, GERBV_INS} gerbv_gui_unit_t;
-typedef enum {ZOOM_IN, ZOOM_OUT, ZOOM_FIT, ZOOM_IN_CMOUSE, ZOOM_OUT_CMOUSE, ZOOM_SET } gerbv_zoom_dir_t;
-typedef enum {NORMAL, IN_MOVE, IN_ZOOM_OUTLINE, IN_MEASURE, ALT_PRESSED,
-		IN_SELECTION_DRAG, SCROLLBAR} gerbv_state_t;
-typedef enum {POINTER, PAN, ZOOM, MEASURE} gerbv_tool_t;
+typedef enum {
+    GERBV_MILS,
+    GERBV_MMS,
+    GERBV_INS
+} gerbv_gui_unit_t;
+
+typedef enum {
+    ZOOM_IN,
+    ZOOM_OUT,
+    ZOOM_FIT,
+    ZOOM_IN_CMOUSE,
+    ZOOM_OUT_CMOUSE,
+    ZOOM_SET
+} gerbv_zoom_dir_t;
+
+typedef enum {
+    NORMAL,
+    IN_MOVE,
+    IN_ZOOM_OUTLINE,
+    IN_MEASURE,
+    ALT_PRESSED,
+    IN_SELECTION_DRAG,
+    SCROLLBAR
+} gerbv_state_t;
+
+typedef enum {
+    POINTER,
+    PAN,
+    ZOOM,
+    MEASURE
+} gerbv_tool_t;
 
 typedef struct {
-    GtkWidget *drawing_area;
-    GdkPixmap *pixmap;
-    GdkColor  zoom_outline_color;
-    GdkColor  dist_measure_color;
-    GdkColor  selection_color;
+    GtkWidget* drawing_area;
+    GdkPixmap* pixmap;
+    GdkColor   zoom_outline_color;
+    GdkColor   dist_measure_color;
+    GdkColor   selection_color;
 
     struct {
-	GtkWidget *log;
-	GtkWidget *topLevelWindow;
-	GtkWidget *messageTextView;
-	GtkWidget *statusMessageLeft;
-	GtkWidget *statusMessageRight;
-	GtkWidget *statusUnitComboBox;
-	GtkCheckMenuItem **menu_view_unit_group;
-	GtkWidget *layerTree;
-	gboolean treeIsUpdating;
-	GtkWidget *colorSelectionDialog;
-	gint colorSelectionIndex;
-	GtkWidget *hAdjustment;
-	GtkWidget *vAdjustment;
-	GtkWidget *hRuler;
-	GtkWidget *vRuler;
-	GtkWidget *sidepane_notebook;
-	GtkComboBox *sidepaneRenderComboBox;
-	GtkCheckMenuItem **menu_view_render_group;
-	GtkWidget *project;
-	GtkWidget *gerber;
-	GtkWidget *about_dialog;
-	GtkWidget *toolButtonPointer;
-	GtkWidget *toolButtonPan;
-	GtkWidget *toolButtonZoom;
-	GtkWidget *toolButtonMeasure;
-	gboolean updatingTools;
-	GtkWidget *layerTreePopupMenu;
-	GtkWidget *drawWindowPopupMenu;
-	GtkWidget *curLayerMenuItem;
-	GtkWidget *curAnalyzeMenuItem;
-	GtkWidget *curEditMenuItem;
-	GtkWidget *curEditAlingMenuItem, *curEditAlingItem[2];
-	GtkWidget *curFileMenuItem[7];
+        GtkWidget*         log;
+        GtkWidget*         topLevelWindow;
+        GtkWidget*         messageTextView;
+        GtkWidget*         statusMessageLeft;
+        GtkWidget*         statusMessageRight;
+        GtkWidget*         statusUnitComboBox;
+        GtkCheckMenuItem** menu_view_unit_group;
+        GtkWidget*         layerTree;
+        gboolean           treeIsUpdating;
+        GtkWidget*         colorSelectionDialog;
+        gint               colorSelectionIndex;
+        GtkWidget*         hAdjustment;
+        GtkWidget*         vAdjustment;
+        GtkWidget*         hRuler;
+        GtkWidget*         vRuler;
+        GtkWidget*         sidepane_notebook;
+        GtkComboBox*       sidepaneRenderComboBox;
+        GtkCheckMenuItem** menu_view_render_group;
+        GtkWidget*         project;
+        GtkWidget*         gerber;
+        GtkWidget*         about_dialog;
+        GtkWidget*         toolButtonPointer;
+        GtkWidget*         toolButtonPan;
+        GtkWidget*         toolButtonZoom;
+        GtkWidget*         toolButtonMeasure;
+        gboolean           updatingTools;
+        GtkWidget*         layerTreePopupMenu;
+        GtkWidget*         drawWindowPopupMenu;
+        GtkWidget*         curLayerMenuItem;
+        GtkWidget*         curAnalyzeMenuItem;
+        GtkWidget*         curEditMenuItem;
+        GtkWidget *        curEditAlingMenuItem, *curEditAlingItem[2];
+        GtkWidget*         curFileMenuItem[7];
     } win;
 
     gpointer windowSurface;
     gpointer bufferSurface;
     gpointer selectionRenderData;
 
-    GtkTooltips *tooltips;
-    GtkWidget *popup_menu;
+    GtkTooltips* tooltips;
+    GtkWidget*   popup_menu;
+
     struct {
-	GtkWidget *msg;
-	char msgstr[MAX_STATUSMSGLEN];
-	char coordstr[MAX_COORDLEN];
-	char diststr[MAX_DISTLEN];
+        GtkWidget* msg;
+        char       msgstr[MAX_STATUSMSGLEN];
+        char       coordstr[MAX_COORDLEN];
+        char       diststr[MAX_DISTLEN];
     } statusbar;
 
     gboolean centered_outline_zoom;
 
-    int selected_layer;		/* Selected layer by Alt+keypad */
+    int                    selected_layer; /* Selected layer by Alt+keypad */
     gerbv_selection_info_t selectionInfo;
-    gerbv_state_t state;
-    gerbv_tool_t tool;
-    gerbv_gui_unit_t unit;
-    gboolean unit_is_from_cmdline;
-    gboolean background_is_from_cmdline;
-    gboolean background_is_from_project;
-    GSettings *settings;
+    gerbv_state_t          state;
+    gerbv_tool_t           tool;
+    gerbv_gui_unit_t       unit;
+    gboolean               unit_is_from_cmdline;
+    gboolean               background_is_from_cmdline;
+    gboolean               background_is_from_project;
+    GSettings*             settings;
 
     gint last_x;
     gint last_y;
-    gint start_x;		/* Zoom box start screen coordinates */
+    gint start_x; /* Zoom box start screen coordinates */
     gint start_y;
 
-    gint off_x;			/* Offset current pixmap when panning */
+    gint off_x; /* Offset current pixmap when panning */
     gint off_y;
 
-    gdouble measure_start_x;	/* Measure start board coordinates */
+    gdouble measure_start_x; /* Measure start board coordinates */
     gdouble measure_start_y;
-    gdouble measure_stop_x;	/* Measure end board coordinates */
+    gdouble measure_stop_x; /* Measure end board coordinates */
     gdouble measure_stop_y;
 
     gdouble measure_last_x;
@@ -129,21 +156,17 @@ typedef struct {
 } gerbv_screen_t;
 
 struct log_struct {
-    gchar *domain;
+    gchar*         domain;
     GLogLevelFlags level;
-    gchar *message;
+    gchar*         message;
 };
 
-extern gerbv_screen_t screen;
-extern gerbv_project_t *mainProject;
+extern gerbv_screen_t   screen;
+extern gerbv_project_t* mainProject;
 
-void
-main_save_as_project_from_filename(gerbv_project_t *gerbvProject, gchar *filename);
+void main_save_as_project_from_filename(gerbv_project_t* gerbvProject, gchar* filename);
 
-void
-main_save_project_from_filename(gerbv_project_t *gerbvProject, gchar *filename);
+void main_save_project_from_filename(gerbv_project_t* gerbvProject, gchar* filename);
 
-void
-main_open_project_from_filename(gerbv_project_t *gerbvProject, gchar *filename);
+void main_open_project_from_filename(gerbv_project_t* gerbvProject, gchar* filename);
 #endif /* GERBV_H */
-
diff --git a/src/opdefines.h b/src/opdefines.h
index 74797fa..5d5774b 100644
--- a/src/opdefines.h
+++ b/src/opdefines.h
@@ -3,194 +3,194 @@
     \ingroup gerbv
 */
 
-    _OP_DEF(opexe_0, "load",                           1,  1,       TST_STRING,                      OP_LOAD             )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_T0LVL            )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_T1LVL            )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_READ_INTERNAL    )
-    _OP_DEF(opexe_0, "gensym",                         0,  0,       0,                               OP_GENSYM           )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_VALUEPRINT       )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_EVAL             )
+_OP_DEF(opexe_0, "load", 1, 1, TST_STRING, OP_LOAD)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_T0LVL)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_T1LVL)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_READ_INTERNAL)
+_OP_DEF(opexe_0, "gensym", 0, 0, 0, OP_GENSYM)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_VALUEPRINT)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_EVAL)
 #if USE_TRACING
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_REAL_EVAL        )
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_REAL_EVAL)
 #endif
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_E0ARGS           )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_E1ARGS           )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_APPLY            )
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_E0ARGS)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_E1ARGS)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_APPLY)
 #if USE_TRACING
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_REAL_APPLY       )
-    _OP_DEF(opexe_0, "tracing",                        1,  1,       TST_NATURAL,                     OP_TRACING          )
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_REAL_APPLY)
+_OP_DEF(opexe_0, "tracing", 1, 1, TST_NATURAL, OP_TRACING)
 #endif
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_DOMACRO          )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_LAMBDA           )
-    _OP_DEF(opexe_0, "make-closure",                   1,  2,       TST_PAIR TST_ENVIRONMENT,        OP_MKCLOSURE        )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_QUOTE            )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_DEF0             )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_DEF1             )
-    _OP_DEF(opexe_0, "defined?",                       1,  2,       TST_SYMBOL TST_ENVIRONMENT,      OP_DEFP             )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_BEGIN            )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_IF0              )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_IF1              )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_SET0             )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_SET1             )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_LET0             )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_LET1             )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_LET2             )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_LET0AST          )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_LET1AST          )
-    _OP_DEF(opexe_0, 0,                                0,  0,       0,                               OP_LET2AST          )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_LET0REC          )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_LET1REC          )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_LET2REC          )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_COND0            )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_COND1            )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_DELAY            )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_AND0             )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_AND1             )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_OR0              )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_OR1              )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_C0STREAM         )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_C1STREAM         )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_MACRO0           )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_MACRO1           )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_CASE0            )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_CASE1            )
-    _OP_DEF(opexe_1, 0,                                0,  0,       0,                               OP_CASE2            )
-    _OP_DEF(opexe_1, "eval",                           1,  2,       TST_ANY TST_ENVIRONMENT,         OP_PEVAL            )
-    _OP_DEF(opexe_1, "apply",                          1,  INF_ARG, TST_NONE,                        OP_PAPPLY           )
-    _OP_DEF(opexe_1, "call-with-current-continuation", 1,  1,       TST_NONE,                        OP_CONTINUATION     )
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_DOMACRO)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_LAMBDA)
+_OP_DEF(opexe_0, "make-closure", 1, 2, TST_PAIR TST_ENVIRONMENT, OP_MKCLOSURE)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_QUOTE)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_DEF0)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_DEF1)
+_OP_DEF(opexe_0, "defined?", 1, 2, TST_SYMBOL TST_ENVIRONMENT, OP_DEFP)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_BEGIN)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_IF0)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_IF1)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_SET0)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_SET1)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_LET0)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_LET1)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_LET2)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_LET0AST)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_LET1AST)
+_OP_DEF(opexe_0, 0, 0, 0, 0, OP_LET2AST)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_LET0REC)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_LET1REC)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_LET2REC)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_COND0)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_COND1)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_DELAY)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_AND0)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_AND1)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_OR0)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_OR1)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_C0STREAM)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_C1STREAM)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_MACRO0)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_MACRO1)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_CASE0)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_CASE1)
+_OP_DEF(opexe_1, 0, 0, 0, 0, OP_CASE2)
+_OP_DEF(opexe_1, "eval", 1, 2, TST_ANY TST_ENVIRONMENT, OP_PEVAL)
+_OP_DEF(opexe_1, "apply", 1, INF_ARG, TST_NONE, OP_PAPPLY)
+_OP_DEF(opexe_1, "call-with-current-continuation", 1, 1, TST_NONE, OP_CONTINUATION)
 #if USE_MATH
-    _OP_DEF(opexe_2, "inexact->exact",                 1,  1,       TST_NUMBER,                      OP_INEX2EX          )
-    _OP_DEF(opexe_2, "exp",                            1,  1,       TST_NUMBER,                      OP_EXP              )
-    _OP_DEF(opexe_2, "log",                            1,  1,       TST_NUMBER,                      OP_LOG              )
-    _OP_DEF(opexe_2, "sin",                            1,  1,       TST_NUMBER,                      OP_SIN              )
-    _OP_DEF(opexe_2, "cos",                            1,  1,       TST_NUMBER,                      OP_COS              )
-    _OP_DEF(opexe_2, "tan",                            1,  1,       TST_NUMBER,                      OP_TAN              )
-    _OP_DEF(opexe_2, "asin",                           1,  1,       TST_NUMBER,                      OP_ASIN             )
-    _OP_DEF(opexe_2, "acos",                           1,  1,       TST_NUMBER,                      OP_ACOS             )
-    _OP_DEF(opexe_2, "atan",                           1,  2,       TST_NUMBER,                      OP_ATAN             )
-    _OP_DEF(opexe_2, "sqrt",                           1,  1,       TST_NUMBER,                      OP_SQRT             )
-    _OP_DEF(opexe_2, "expt",                           2,  2,       TST_NUMBER,                      OP_EXPT             )
-    _OP_DEF(opexe_2, "floor",                          1,  1,       TST_NUMBER,                      OP_FLOOR            )
-    _OP_DEF(opexe_2, "ceiling",                        1,  1,       TST_NUMBER,                      OP_CEILING          )
-    _OP_DEF(opexe_2, "truncate",                       1,  1,       TST_NUMBER,                      OP_TRUNCATE         )
-    _OP_DEF(opexe_2, "round",                          1,  1,       TST_NUMBER,                      OP_ROUND            )
+_OP_DEF(opexe_2, "inexact->exact", 1, 1, TST_NUMBER, OP_INEX2EX)
+_OP_DEF(opexe_2, "exp", 1, 1, TST_NUMBER, OP_EXP)
+_OP_DEF(opexe_2, "log", 1, 1, TST_NUMBER, OP_LOG)
+_OP_DEF(opexe_2, "sin", 1, 1, TST_NUMBER, OP_SIN)
+_OP_DEF(opexe_2, "cos", 1, 1, TST_NUMBER, OP_COS)
+_OP_DEF(opexe_2, "tan", 1, 1, TST_NUMBER, OP_TAN)
+_OP_DEF(opexe_2, "asin", 1, 1, TST_NUMBER, OP_ASIN)
+_OP_DEF(opexe_2, "acos", 1, 1, TST_NUMBER, OP_ACOS)
+_OP_DEF(opexe_2, "atan", 1, 2, TST_NUMBER, OP_ATAN)
+_OP_DEF(opexe_2, "sqrt", 1, 1, TST_NUMBER, OP_SQRT)
+_OP_DEF(opexe_2, "expt", 2, 2, TST_NUMBER, OP_EXPT)
+_OP_DEF(opexe_2, "floor", 1, 1, TST_NUMBER, OP_FLOOR)
+_OP_DEF(opexe_2, "ceiling", 1, 1, TST_NUMBER, OP_CEILING)
+_OP_DEF(opexe_2, "truncate", 1, 1, TST_NUMBER, OP_TRUNCATE)
+_OP_DEF(opexe_2, "round", 1, 1, TST_NUMBER, OP_ROUND)
 #endif
-    _OP_DEF(opexe_2, "+",                              0,  INF_ARG, TST_NUMBER,                      OP_ADD              )
-    _OP_DEF(opexe_2, "-",                              1,  INF_ARG, TST_NUMBER,                      OP_SUB              )
-    _OP_DEF(opexe_2, "*",                              0,  INF_ARG, TST_NUMBER,                      OP_MUL              )
-    _OP_DEF(opexe_2, "/",                              1,  INF_ARG, TST_NUMBER,                      OP_DIV              )
-    _OP_DEF(opexe_2, "quotient",                       1,  INF_ARG, TST_INTEGER,                     OP_INTDIV           )
-    _OP_DEF(opexe_2, "remainder",                      2,  2,       TST_INTEGER,                     OP_REM              )
-    _OP_DEF(opexe_2, "modulo",                         2,  2,       TST_INTEGER,                     OP_MOD              )
-    _OP_DEF(opexe_2, "car",                            1,  1,       TST_PAIR,                        OP_CAR              )
-    _OP_DEF(opexe_2, "cdr",                            1,  1,       TST_PAIR,                        OP_CDR              )
-    _OP_DEF(opexe_2, "cons",                           2,  2,       TST_NONE,                        OP_CONS             )
-    _OP_DEF(opexe_2, "set-car!",                       2,  2,       TST_PAIR TST_ANY,                OP_SETCAR           )
-    _OP_DEF(opexe_2, "set-cdr!",                       2,  2,       TST_PAIR TST_ANY,                OP_SETCDR           )
-    _OP_DEF(opexe_2, "char->integer",                  1,  1,       TST_CHAR,                        OP_CHAR2INT         )
-    _OP_DEF(opexe_2, "integer->char",                  1,  1,       TST_NATURAL,                     OP_INT2CHAR         )
-    _OP_DEF(opexe_2, "char-upcase",                    1,  1,       TST_CHAR,                        OP_CHARUPCASE       )
-    _OP_DEF(opexe_2, "char-downcase",                  1,  1,       TST_CHAR,                        OP_CHARDNCASE       )
-    _OP_DEF(opexe_2, "symbol->string",                 1,  1,       TST_SYMBOL,                      OP_SYM2STR          )
-    _OP_DEF(opexe_2, "atom->string",                   1,  1,       TST_ANY,                         OP_ATOM2STR         )
-    _OP_DEF(opexe_2, "string->symbol",                 1,  1,       TST_STRING,                      OP_STR2SYM          )
-    _OP_DEF(opexe_2, "string->atom",                   1,  1,       TST_STRING,                      OP_STR2ATOM         )
-    _OP_DEF(opexe_2, "make-string",                    1,  2,       TST_NATURAL TST_CHAR,            OP_MKSTRING         )
-    _OP_DEF(opexe_2, "string-length",                  1,  1,       TST_STRING,                      OP_STRLEN           )
-    _OP_DEF(opexe_2, "string-ref",                     2,  2,       TST_STRING TST_NATURAL,          OP_STRREF           )
-    _OP_DEF(opexe_2, "string-set!",                    3,  3,       TST_STRING TST_NATURAL TST_CHAR, OP_STRSET           )
-    _OP_DEF(opexe_2, "string-append",                  0,  INF_ARG, TST_STRING,                      OP_STRAPPEND        )
-    _OP_DEF(opexe_2, "substring",                      2,  3,       TST_STRING TST_NATURAL,          OP_SUBSTR           )
-    _OP_DEF(opexe_2, "vector",                         0,  INF_ARG, TST_NONE,                        OP_VECTOR           )
-    _OP_DEF(opexe_2, "make-vector",                    1,  2,       TST_NATURAL TST_ANY,             OP_MKVECTOR         )
-    _OP_DEF(opexe_2, "vector-length",                  1,  1,       TST_VECTOR,                      OP_VECLEN           )
-    _OP_DEF(opexe_2, "vector-ref",                     2,  2,       TST_VECTOR TST_NATURAL,          OP_VECREF           )
-    _OP_DEF(opexe_2, "vector-set!",                    3,  3,       TST_VECTOR TST_NATURAL TST_ANY,        OP_VECSET     )
-    _OP_DEF(opexe_3, "not",                            1,  1,       TST_NONE,                        OP_NOT              )
-    _OP_DEF(opexe_3, "boolean?",                       1,  1,       TST_NONE,                        OP_BOOLP            )
-    _OP_DEF(opexe_3, "eof-object?",                    1,  1,       TST_NONE,                        OP_EOFOBJP          )
-    _OP_DEF(opexe_3, "null?",                          1,  1,       TST_NONE,                        OP_NULLP            )
-    _OP_DEF(opexe_3, "=",                              2,  INF_ARG, TST_NUMBER,                      OP_NUMEQ            )
-    _OP_DEF(opexe_3, "<",                              2,  INF_ARG, TST_NUMBER,                      OP_LESS             )
-    _OP_DEF(opexe_3, ">",                              2,  INF_ARG, TST_NUMBER,                      OP_GRE              )
-    _OP_DEF(opexe_3, "<=",                             2,  INF_ARG, TST_NUMBER,                      OP_LEQ              )
-    _OP_DEF(opexe_3, ">=",                             2,  INF_ARG, TST_NUMBER,                      OP_GEQ              )
-    _OP_DEF(opexe_3, "symbol?",                        1,  1,       TST_ANY,                         OP_SYMBOLP          )
-    _OP_DEF(opexe_3, "number?",                        1,  1,       TST_ANY,                         OP_NUMBERP          )
-    _OP_DEF(opexe_3, "string?",                        1,  1,       TST_ANY,                         OP_STRINGP          )
-    _OP_DEF(opexe_3, "integer?",                       1,  1,       TST_ANY,                         OP_INTEGERP         )
-    _OP_DEF(opexe_3, "real?",                          1,  1,       TST_ANY,                         OP_REALP            )
-    _OP_DEF(opexe_3, "char?",                          1,  1,       TST_ANY,                         OP_CHARP            )
+_OP_DEF(opexe_2, "+", 0, INF_ARG, TST_NUMBER, OP_ADD)
+_OP_DEF(opexe_2, "-", 1, INF_ARG, TST_NUMBER, OP_SUB)
+_OP_DEF(opexe_2, "*", 0, INF_ARG, TST_NUMBER, OP_MUL)
+_OP_DEF(opexe_2, "/", 1, INF_ARG, TST_NUMBER, OP_DIV)
+_OP_DEF(opexe_2, "quotient", 1, INF_ARG, TST_INTEGER, OP_INTDIV)
+_OP_DEF(opexe_2, "remainder", 2, 2, TST_INTEGER, OP_REM)
+_OP_DEF(opexe_2, "modulo", 2, 2, TST_INTEGER, OP_MOD)
+_OP_DEF(opexe_2, "car", 1, 1, TST_PAIR, OP_CAR)
+_OP_DEF(opexe_2, "cdr", 1, 1, TST_PAIR, OP_CDR)
+_OP_DEF(opexe_2, "cons", 2, 2, TST_NONE, OP_CONS)
+_OP_DEF(opexe_2, "set-car!", 2, 2, TST_PAIR TST_ANY, OP_SETCAR)
+_OP_DEF(opexe_2, "set-cdr!", 2, 2, TST_PAIR TST_ANY, OP_SETCDR)
+_OP_DEF(opexe_2, "char->integer", 1, 1, TST_CHAR, OP_CHAR2INT)
+_OP_DEF(opexe_2, "integer->char", 1, 1, TST_NATURAL, OP_INT2CHAR)
+_OP_DEF(opexe_2, "char-upcase", 1, 1, TST_CHAR, OP_CHARUPCASE)
+_OP_DEF(opexe_2, "char-downcase", 1, 1, TST_CHAR, OP_CHARDNCASE)
+_OP_DEF(opexe_2, "symbol->string", 1, 1, TST_SYMBOL, OP_SYM2STR)
+_OP_DEF(opexe_2, "atom->string", 1, 1, TST_ANY, OP_ATOM2STR)
+_OP_DEF(opexe_2, "string->symbol", 1, 1, TST_STRING, OP_STR2SYM)
+_OP_DEF(opexe_2, "string->atom", 1, 1, TST_STRING, OP_STR2ATOM)
+_OP_DEF(opexe_2, "make-string", 1, 2, TST_NATURAL TST_CHAR, OP_MKSTRING)
+_OP_DEF(opexe_2, "string-length", 1, 1, TST_STRING, OP_STRLEN)
+_OP_DEF(opexe_2, "string-ref", 2, 2, TST_STRING TST_NATURAL, OP_STRREF)
+_OP_DEF(opexe_2, "string-set!", 3, 3, TST_STRING TST_NATURAL TST_CHAR, OP_STRSET)
+_OP_DEF(opexe_2, "string-append", 0, INF_ARG, TST_STRING, OP_STRAPPEND)
+_OP_DEF(opexe_2, "substring", 2, 3, TST_STRING TST_NATURAL, OP_SUBSTR)
+_OP_DEF(opexe_2, "vector", 0, INF_ARG, TST_NONE, OP_VECTOR)
+_OP_DEF(opexe_2, "make-vector", 1, 2, TST_NATURAL TST_ANY, OP_MKVECTOR)
+_OP_DEF(opexe_2, "vector-length", 1, 1, TST_VECTOR, OP_VECLEN)
+_OP_DEF(opexe_2, "vector-ref", 2, 2, TST_VECTOR TST_NATURAL, OP_VECREF)
+_OP_DEF(opexe_2, "vector-set!", 3, 3, TST_VECTOR TST_NATURAL TST_ANY, OP_VECSET)
+_OP_DEF(opexe_3, "not", 1, 1, TST_NONE, OP_NOT)
+_OP_DEF(opexe_3, "boolean?", 1, 1, TST_NONE, OP_BOOLP)
+_OP_DEF(opexe_3, "eof-object?", 1, 1, TST_NONE, OP_EOFOBJP)
+_OP_DEF(opexe_3, "null?", 1, 1, TST_NONE, OP_NULLP)
+_OP_DEF(opexe_3, "=", 2, INF_ARG, TST_NUMBER, OP_NUMEQ)
+_OP_DEF(opexe_3, "<", 2, INF_ARG, TST_NUMBER, OP_LESS)
+_OP_DEF(opexe_3, ">", 2, INF_ARG, TST_NUMBER, OP_GRE)
+_OP_DEF(opexe_3, "<=", 2, INF_ARG, TST_NUMBER, OP_LEQ)
+_OP_DEF(opexe_3, ">=", 2, INF_ARG, TST_NUMBER, OP_GEQ)
+_OP_DEF(opexe_3, "symbol?", 1, 1, TST_ANY, OP_SYMBOLP)
+_OP_DEF(opexe_3, "number?", 1, 1, TST_ANY, OP_NUMBERP)
+_OP_DEF(opexe_3, "string?", 1, 1, TST_ANY, OP_STRINGP)
+_OP_DEF(opexe_3, "integer?", 1, 1, TST_ANY, OP_INTEGERP)
+_OP_DEF(opexe_3, "real?", 1, 1, TST_ANY, OP_REALP)
+_OP_DEF(opexe_3, "char?", 1, 1, TST_ANY, OP_CHARP)
 #if USE_CHAR_CLASSIFIERS
-    _OP_DEF(opexe_3, "char-alphabetic?",               1,  1,       TST_CHAR,                        OP_CHARAP           )
-    _OP_DEF(opexe_3, "char-numeric?",                  1,  1,       TST_CHAR,                        OP_CHARNP           )
-    _OP_DEF(opexe_3, "char-whitespace?",               1,  1,       TST_CHAR,                        OP_CHARWP           )
-    _OP_DEF(opexe_3, "char-upper-case?",               1,  1,       TST_CHAR,                        OP_CHARUP           )
-    _OP_DEF(opexe_3, "char-lower-case?",               1,  1,       TST_CHAR,                        OP_CHARLP           )
+_OP_DEF(opexe_3, "char-alphabetic?", 1, 1, TST_CHAR, OP_CHARAP)
+_OP_DEF(opexe_3, "char-numeric?", 1, 1, TST_CHAR, OP_CHARNP)
+_OP_DEF(opexe_3, "char-whitespace?", 1, 1, TST_CHAR, OP_CHARWP)
+_OP_DEF(opexe_3, "char-upper-case?", 1, 1, TST_CHAR, OP_CHARUP)
+_OP_DEF(opexe_3, "char-lower-case?", 1, 1, TST_CHAR, OP_CHARLP)
 #endif
-    _OP_DEF(opexe_3, "port?",                          1,  1,       TST_ANY,                         OP_PORTP            )
-    _OP_DEF(opexe_3, "input-port?",                    1,  1,       TST_ANY,                         OP_INPORTP          )
-    _OP_DEF(opexe_3, "output-port?",                   1,  1,       TST_ANY,                         OP_OUTPORTP         )
-    _OP_DEF(opexe_3, "procedure?",                     1,  1,       TST_ANY,                         OP_PROCP            )
-    _OP_DEF(opexe_3, "pair?",                          1,  1,       TST_ANY,                         OP_PAIRP            )
-    _OP_DEF(opexe_3, "list?",                          1,  1,       TST_ANY,                         OP_LISTP            )
-    _OP_DEF(opexe_3, "environment?",                   1,  1,       TST_ANY,                         OP_ENVP             )
-    _OP_DEF(opexe_3, "vector?",                        1,  1,       TST_ANY,                         OP_VECTORP          )
-    _OP_DEF(opexe_3, "eq?",                            2,  2,       TST_ANY,                         OP_EQ               )
-    _OP_DEF(opexe_3, "eqv?",                           2,  2,       TST_ANY,                         OP_EQV              )
-    _OP_DEF(opexe_4, "force",                          1,  1,       TST_ANY,                         OP_FORCE            )
-    _OP_DEF(opexe_4, 0,                                0,  0,       0,                               OP_SAVE_FORCED      )
-    _OP_DEF(opexe_4, "write",                          1,  2,       TST_ANY TST_OUTPORT,             OP_WRITE            )
-    _OP_DEF(opexe_4, "write-char",                     1,  2,       TST_CHAR TST_OUTPORT,            OP_WRITE_CHAR       )
-    _OP_DEF(opexe_4, "display",                        1,  2,       TST_ANY TST_OUTPORT,             OP_DISPLAY          )
-    _OP_DEF(opexe_4, "newline",                        0,  1,       TST_OUTPORT,                     OP_NEWLINE          )
-    _OP_DEF(opexe_4, "error",                          1,  INF_ARG, TST_NONE,                        OP_ERR0             )
-    _OP_DEF(opexe_4, 0,                                0,  0,       0,                               OP_ERR1             )
-    _OP_DEF(opexe_4, "reverse",                        1,  1,       TST_PAIR,                        OP_REVERSE          )
-    _OP_DEF(opexe_4, "list*",                          1,  INF_ARG, TST_NONE,                        OP_LIST_STAR        )
-    _OP_DEF(opexe_4, "append",                         0,  INF_ARG, TST_NONE,                        OP_APPEND           )
-    _OP_DEF(opexe_4, "put",                            3,  3,       TST_NONE,                        OP_PUT              )
-    _OP_DEF(opexe_4, "get",                            2,  2,       TST_NONE,                        OP_GET              )
-    _OP_DEF(opexe_4, "quit",                           0,  1,       TST_NUMBER,                      OP_QUIT             )
-    _OP_DEF(opexe_4, "gc",                             0,  0,       0,                               OP_GC               )
-    _OP_DEF(opexe_4, "gc-verbose",                     0,  1,       TST_NONE,                        OP_GCVERB           )
-    _OP_DEF(opexe_4, "new-segment",                    0,  1,       TST_NUMBER,                      OP_NEWSEGMENT       )
-    _OP_DEF(opexe_4, "oblist",                         0,  0,       0,                               OP_OBLIST           )
-    _OP_DEF(opexe_4, "current-input-port",             0,  0,       0,                               OP_CURR_INPORT      )
-    _OP_DEF(opexe_4, "current-output-port",            0,  0,       0,                               OP_CURR_OUTPORT     )
-    _OP_DEF(opexe_4, "open-input-file",                1,  1,       TST_STRING,                      OP_OPEN_INFILE      )
-    _OP_DEF(opexe_4, "open-output-file",               1,  1,       TST_STRING,                      OP_OPEN_OUTFILE     )
-    _OP_DEF(opexe_4, "open-input-output-file",         1,  1,       TST_STRING,                      OP_OPEN_INOUTFILE   )
+_OP_DEF(opexe_3, "port?", 1, 1, TST_ANY, OP_PORTP)
+_OP_DEF(opexe_3, "input-port?", 1, 1, TST_ANY, OP_INPORTP)
+_OP_DEF(opexe_3, "output-port?", 1, 1, TST_ANY, OP_OUTPORTP)
+_OP_DEF(opexe_3, "procedure?", 1, 1, TST_ANY, OP_PROCP)
+_OP_DEF(opexe_3, "pair?", 1, 1, TST_ANY, OP_PAIRP)
+_OP_DEF(opexe_3, "list?", 1, 1, TST_ANY, OP_LISTP)
+_OP_DEF(opexe_3, "environment?", 1, 1, TST_ANY, OP_ENVP)
+_OP_DEF(opexe_3, "vector?", 1, 1, TST_ANY, OP_VECTORP)
+_OP_DEF(opexe_3, "eq?", 2, 2, TST_ANY, OP_EQ)
+_OP_DEF(opexe_3, "eqv?", 2, 2, TST_ANY, OP_EQV)
+_OP_DEF(opexe_4, "force", 1, 1, TST_ANY, OP_FORCE)
+_OP_DEF(opexe_4, 0, 0, 0, 0, OP_SAVE_FORCED)
+_OP_DEF(opexe_4, "write", 1, 2, TST_ANY TST_OUTPORT, OP_WRITE)
+_OP_DEF(opexe_4, "write-char", 1, 2, TST_CHAR TST_OUTPORT, OP_WRITE_CHAR)
+_OP_DEF(opexe_4, "display", 1, 2, TST_ANY TST_OUTPORT, OP_DISPLAY)
+_OP_DEF(opexe_4, "newline", 0, 1, TST_OUTPORT, OP_NEWLINE)
+_OP_DEF(opexe_4, "error", 1, INF_ARG, TST_NONE, OP_ERR0)
+_OP_DEF(opexe_4, 0, 0, 0, 0, OP_ERR1)
+_OP_DEF(opexe_4, "reverse", 1, 1, TST_PAIR, OP_REVERSE)
+_OP_DEF(opexe_4, "list*", 1, INF_ARG, TST_NONE, OP_LIST_STAR)
+_OP_DEF(opexe_4, "append", 0, INF_ARG, TST_NONE, OP_APPEND)
+_OP_DEF(opexe_4, "put", 3, 3, TST_NONE, OP_PUT)
+_OP_DEF(opexe_4, "get", 2, 2, TST_NONE, OP_GET)
+_OP_DEF(opexe_4, "quit", 0, 1, TST_NUMBER, OP_QUIT)
+_OP_DEF(opexe_4, "gc", 0, 0, 0, OP_GC)
+_OP_DEF(opexe_4, "gc-verbose", 0, 1, TST_NONE, OP_GCVERB)
+_OP_DEF(opexe_4, "new-segment", 0, 1, TST_NUMBER, OP_NEWSEGMENT)
+_OP_DEF(opexe_4, "oblist", 0, 0, 0, OP_OBLIST)
+_OP_DEF(opexe_4, "current-input-port", 0, 0, 0, OP_CURR_INPORT)
+_OP_DEF(opexe_4, "current-output-port", 0, 0, 0, OP_CURR_OUTPORT)
+_OP_DEF(opexe_4, "open-input-file", 1, 1, TST_STRING, OP_OPEN_INFILE)
+_OP_DEF(opexe_4, "open-output-file", 1, 1, TST_STRING, OP_OPEN_OUTFILE)
+_OP_DEF(opexe_4, "open-input-output-file", 1, 1, TST_STRING, OP_OPEN_INOUTFILE)
 #if USE_STRING_PORTS
-    _OP_DEF(opexe_4, "open-input-string",              1,  1,       TST_STRING,                      OP_OPEN_INSTRING    )
-    _OP_DEF(opexe_4, "open-output-string",             1,  1,       TST_STRING,                      OP_OPEN_OUTSTRING   )
-    _OP_DEF(opexe_4, "open-input-output-string",       1,  1,       TST_STRING,                      OP_OPEN_INOUTSTRING )
+_OP_DEF(opexe_4, "open-input-string", 1, 1, TST_STRING, OP_OPEN_INSTRING)
+_OP_DEF(opexe_4, "open-output-string", 1, 1, TST_STRING, OP_OPEN_OUTSTRING)
+_OP_DEF(opexe_4, "open-input-output-string", 1, 1, TST_STRING, OP_OPEN_INOUTSTRING)
 #endif
-    _OP_DEF(opexe_4, "close-input-port",               1,  1,       TST_INPORT,                      OP_CLOSE_INPORT     )
-    _OP_DEF(opexe_4, "close-output-port",              1,  1,       TST_OUTPORT,                     OP_CLOSE_OUTPORT    )
-    _OP_DEF(opexe_4, "interaction-environment",        0,  0,       0,                               OP_INT_ENV          )
-    _OP_DEF(opexe_4, "current-environment",            0,  0,       0,                               OP_CURR_ENV         )
-    _OP_DEF(opexe_5, "read",                           0,  1,       TST_INPORT,                      OP_READ             )
-    _OP_DEF(opexe_5, "read-char",                      0,  1,       TST_INPORT,                      OP_READ_CHAR        )
-    _OP_DEF(opexe_5, "peek-char",                      0,  1,       TST_INPORT,                      OP_PEEK_CHAR        )
-    _OP_DEF(opexe_5, "char-ready?",                    0,  1,       TST_INPORT,                      OP_CHAR_READY       )
-    _OP_DEF(opexe_5, "set-input-port",                 1,  1,       TST_INPORT,                      OP_SET_INPORT       )
-    _OP_DEF(opexe_5, "set-output-port",                1,  1,       TST_OUTPORT,                     OP_SET_OUTPORT      )
-    _OP_DEF(opexe_5, 0,                                0,  0,       0,                               OP_RDSEXPR          )
-    _OP_DEF(opexe_5, 0,                                0,  0,       0,                               OP_RDLIST           )
-    _OP_DEF(opexe_5, 0,                                0,  0,       0,                               OP_RDDOT            )
-    _OP_DEF(opexe_5, 0,                                0,  0,       0,                               OP_RDQUOTE          )
-    _OP_DEF(opexe_5, 0,                                0,  0,       0,                               OP_RDQQUOTE         )
-    _OP_DEF(opexe_5, 0,                                0,  0,       0,                               OP_RDQQUOTEVEC      )
-    _OP_DEF(opexe_5, 0,                                0,  0,       0,                               OP_RDUNQUOTE        )
-    _OP_DEF(opexe_5, 0,                                0,  0,       0,                               OP_RDUQTSP          )
-    _OP_DEF(opexe_5, 0,                                0,  0,       0,                               OP_RDVEC            )
-    _OP_DEF(opexe_5, 0,                                0,  0,       0,                               OP_P0LIST           )
-    _OP_DEF(opexe_5, 0,                                0,  0,       0,                               OP_P1LIST           )
-    _OP_DEF(opexe_5, 0,                                0,  0,       0,                               OP_PVECFROM         )
-    _OP_DEF(opexe_6, "length",                         1,  1,       TST_LIST,                        OP_LIST_LENGTH      )
-    _OP_DEF(opexe_6, "assq",                           2,  2,       TST_NONE,                        OP_ASSQ             )
-    _OP_DEF(opexe_6, "get-closure-code",               1,  1,       TST_NONE,                        OP_GET_CLOSURE      )
-    _OP_DEF(opexe_6, "closure?",                       1,  1,       TST_NONE,                        OP_CLOSUREP         )
-    _OP_DEF(opexe_6, "macro?",                         1,  1,       TST_NONE,                        OP_MACROP           )
+_OP_DEF(opexe_4, "close-input-port", 1, 1, TST_INPORT, OP_CLOSE_INPORT)
+_OP_DEF(opexe_4, "close-output-port", 1, 1, TST_OUTPORT, OP_CLOSE_OUTPORT)
+_OP_DEF(opexe_4, "interaction-environment", 0, 0, 0, OP_INT_ENV)
+_OP_DEF(opexe_4, "current-environment", 0, 0, 0, OP_CURR_ENV)
+_OP_DEF(opexe_5, "read", 0, 1, TST_INPORT, OP_READ)
+_OP_DEF(opexe_5, "read-char", 0, 1, TST_INPORT, OP_READ_CHAR)
+_OP_DEF(opexe_5, "peek-char", 0, 1, TST_INPORT, OP_PEEK_CHAR)
+_OP_DEF(opexe_5, "char-ready?", 0, 1, TST_INPORT, OP_CHAR_READY)
+_OP_DEF(opexe_5, "set-input-port", 1, 1, TST_INPORT, OP_SET_INPORT)
+_OP_DEF(opexe_5, "set-output-port", 1, 1, TST_OUTPORT, OP_SET_OUTPORT)
+_OP_DEF(opexe_5, 0, 0, 0, 0, OP_RDSEXPR)
+_OP_DEF(opexe_5, 0, 0, 0, 0, OP_RDLIST)
+_OP_DEF(opexe_5, 0, 0, 0, 0, OP_RDDOT)
+_OP_DEF(opexe_5, 0, 0, 0, 0, OP_RDQUOTE)
+_OP_DEF(opexe_5, 0, 0, 0, 0, OP_RDQQUOTE)
+_OP_DEF(opexe_5, 0, 0, 0, 0, OP_RDQQUOTEVEC)
+_OP_DEF(opexe_5, 0, 0, 0, 0, OP_RDUNQUOTE)
+_OP_DEF(opexe_5, 0, 0, 0, 0, OP_RDUQTSP)
+_OP_DEF(opexe_5, 0, 0, 0, 0, OP_RDVEC)
+_OP_DEF(opexe_5, 0, 0, 0, 0, OP_P0LIST)
+_OP_DEF(opexe_5, 0, 0, 0, 0, OP_P1LIST)
+_OP_DEF(opexe_5, 0, 0, 0, 0, OP_PVECFROM)
+_OP_DEF(opexe_6, "length", 1, 1, TST_LIST, OP_LIST_LENGTH)
+_OP_DEF(opexe_6, "assq", 2, 2, TST_NONE, OP_ASSQ)
+_OP_DEF(opexe_6, "get-closure-code", 1, 1, TST_NONE, OP_GET_CLOSURE)
+_OP_DEF(opexe_6, "closure?", 1, 1, TST_NONE, OP_CLOSUREP)
+_OP_DEF(opexe_6, "macro?", 1, 1, TST_NONE, OP_MACROP)
 #undef _OP_DEF
diff --git a/src/pick-and-place.c b/src/pick-and-place.c
index 7260ba7..0139755 100644
--- a/src/pick-and-place.c
+++ b/src/pick-and-place.c
@@ -37,34 +37,32 @@
 #include "csv.h"
 #include "pick-and-place.h"
 
-static gerbv_net_t *pnp_new_net(gerbv_net_t *net); 
-static void pnp_reset_bbox (gerbv_net_t *net);
-static void pnp_init_net(gerbv_net_t *net, gerbv_image_t *image,
-		const char *label,
-		gerbv_aperture_state_t apert_state,
-		gerbv_interpolation_t interpol);
-
-void gerb_transf_free(gerbv_transf_t *transf)
-{
+static gerbv_net_t* pnp_new_net(gerbv_net_t* net);
+static void         pnp_reset_bbox(gerbv_net_t* net);
+static void         pnp_init_net(
+            gerbv_net_t* net, gerbv_image_t* image, const char* label, gerbv_aperture_state_t apert_state,
+            gerbv_interpolation_t interpol
+        );
+
+void
+gerb_transf_free(gerbv_transf_t* transf) {
     g_free(transf);
 }
 
+void
+gerb_transf_reset(gerbv_transf_t* transf) {
+    memset(transf, 0, sizeof(gerbv_transf_t));
 
-void gerb_transf_reset(gerbv_transf_t* transf)
-{
-    memset(transf,0,sizeof(gerbv_transf_t));
-    
     transf->r_mat[0][0] = transf->r_mat[1][1] = 1.0; /*off-diagonals 0 diagonals 1 */
-    //transf->r_mat[1][0] = transf->r_mat[0][1] = 0.0;
+    // transf->r_mat[1][0] = transf->r_mat[0][1] = 0.0;
     transf->scale = 1.0;
-    //transf->offset[0] = transf->offset[1] = 0.0;
-    
-} /* gerb_transf_reset */
+    // transf->offset[0] = transf->offset[1] = 0.0;
 
+} /* gerb_transf_reset */
 
-gerbv_transf_t* gerb_transf_new(void)
-{
-    gerbv_transf_t *transf;
+gerbv_transf_t*
+gerb_transf_new(void) {
+    gerbv_transf_t* transf;
 
     transf = g_new(gerbv_transf_t, 1);
     gerb_transf_reset(transf);
@@ -72,478 +70,461 @@ gerbv_transf_t* gerb_transf_new(void)
     return transf;
 } /* gerb_transf_new */
 
-
-//!Rotation
+//! Rotation
 /*! append rotation to transformation.
 @param transf transformation to be modified
 @param angle in rad (counterclockwise rotation) */
 
-void gerb_transf_rotate(gerbv_transf_t* transf, double angle)
-{
-    double m[2][2]; 
+void
+gerb_transf_rotate(gerbv_transf_t* transf, double angle) {
+    double m[2][2];
     double s = sin(angle), c = cos(angle);
-      
-    memcpy(m, transf->r_mat, sizeof(m));    
+
+    memcpy(m, transf->r_mat, sizeof(m));
     transf->r_mat[0][0] = c * m[0][0] - s * m[1][0];
     transf->r_mat[0][1] = c * m[0][1] - s * m[1][1];
     transf->r_mat[1][0] = s * m[0][0] + c * m[1][0];
     transf->r_mat[1][1] = s * m[0][1] + c * m[1][1];
-//    transf->offset[0] = transf->offset[1] = 0.0; CHECK ME
-    
+    //    transf->offset[0] = transf->offset[1] = 0.0; CHECK ME
+
 } /* gerb_transf_rotate */
 
-//!Translation
+//! Translation
 /*! append translation to transformation.
 @param transf transformation to be modified
 @param shift_x translation in x direction
 @param shift_y translation in y direction */
 
-void gerb_transf_shift(gerbv_transf_t* transf, double shift_x, double shift_y)
-{
-      
+void
+gerb_transf_shift(gerbv_transf_t* transf, double shift_x, double shift_y) {
+
     transf->offset[0] += shift_x;
     transf->offset[1] += shift_y;
-            
+
 } /* gerb_transf_shift */
 
-void gerb_transf_apply(double x, double y, gerbv_transf_t* transf, double *out_x, double *out_y)
-{
+void
+gerb_transf_apply(double x, double y, gerbv_transf_t* transf, double* out_x, double* out_y) {
 
-//    x += transf->offset[0];
-//    y += transf->offset[1];
+    //    x += transf->offset[0];
+    //    y += transf->offset[1];
     *out_x = (x * transf->r_mat[0][0] + y * transf->r_mat[0][1]) * transf->scale;
     *out_y = (x * transf->r_mat[1][0] + y * transf->r_mat[1][1]) * transf->scale;
     *out_x += transf->offset[0];
     *out_y += transf->offset[1];
-    
-    
+
 } /* gerb_transf_apply */
 
 void
-pick_and_place_reset_bounding_box (gerbv_net_t *net) {
-	net->boundingBox.left = -HUGE_VAL;
-	net->boundingBox.right = HUGE_VAL;
-	net->boundingBox.bottom = -HUGE_VAL;
-	net->boundingBox.top = HUGE_VAL;
+pick_and_place_reset_bounding_box(gerbv_net_t* net) {
+    net->boundingBox.left   = -HUGE_VAL;
+    net->boundingBox.right  = HUGE_VAL;
+    net->boundingBox.bottom = -HUGE_VAL;
+    net->boundingBox.top    = HUGE_VAL;
 }
 
 /* Parses a string representing float number with a unit.
  * Default unit can be specified with def_unit. */
 static double
-pick_and_place_get_float_unit(const char *str, const char *def_unit)
-{
-    double x = 0.0;
-    char unit_str[41] = {0,};
-    const char *unit = unit_str;
+pick_and_place_get_float_unit(const char* str, const char* def_unit) {
+    double x            = 0.0;
+    char   unit_str[41] = {
+          0,
+    };
+    const char* unit = unit_str;
 
     /* float, optional space, optional unit mm,cm,in,mil */
     sscanf(str, "%lf %40s", &x, unit_str);
 
     if (unit_str[0] == '\0')
-	unit = def_unit;
+        unit = def_unit;
 
     /* NOTE: in order of comparability,
      * i.e. "mm" before "m", as "m" will match "mm" */
     if (strstr(unit, "mm")) {
-	x /= 25.4;
+        x /= 25.4;
     } else if (strstr(unit, "in")) {
-	/* NOTE: "in" is without scaling. */
+        /* NOTE: "in" is without scaling. */
     } else if (strstr(unit, "cmil")) {
-	x /= 1e5;
+        x /= 1e5;
     } else if (strstr(unit, "dmil")) {
-	x /= 1e4;
+        x /= 1e4;
     } else if (strstr(unit, "mil")) {
-	x /= 1e3;
+        x /= 1e3;
     } else if (strstr(unit, "km")) {
-	x /= 25.4/1e6;
+        x /= 25.4 / 1e6;
     } else if (strstr(unit, "dm")) {
-	x /= 25.4/100;
+        x /= 25.4 / 100;
     } else if (strstr(unit, "cm")) {
-	x /= 25.4/10;
+        x /= 25.4 / 10;
     } else if (strstr(unit, "um")) {
-	x /= 25.4*1e3;
+        x /= 25.4 * 1e3;
     } else if (strstr(unit, "nm")) {
-	x /= 25.4*1e6;
-    } else if (strstr(unit,  "m")) {
-	x /= 25.4/1e3;
+        x /= 25.4 * 1e6;
+    } else if (strstr(unit, "m")) {
+        x /= 25.4 / 1e3;
     } else { /* default to "mil" */
-	x /= 1e3;
+        x /= 1e3;
     }
 
     return x;
 } /* pick_and_place_get_float_unit */
 
-
 /** search a string for a delimiter.
  Must occur at least n times. */
-int 
-pick_and_place_screen_for_delimiter(char *str, int n)
-{
-    char *ptr;
-    char delimiter[4] = "|,;:";
-    int counter[4];
-    int idx, idx_max = 0;
+int
+pick_and_place_screen_for_delimiter(char* str, int n) {
+    char* ptr;
+    char  delimiter[4] = "|,;:";
+    int   counter[4];
+    int   idx, idx_max = 0;
 
     memset(counter, 0, sizeof(counter));
-    for(ptr = str; *ptr; ptr++) {
-	switch(*ptr) {
-	case '|':
-	    idx = 0;
-	    break;
-	case ',':
-	    idx = 1;
-	    break;
-	case ';':
-	    idx = 2;
-	    break;
-	case ':':
-	    idx = 3;
-	    break;
-	default:
-	    continue;
-	    break;
-	}
-	counter[idx]++;
-	if(counter[idx] > counter[idx_max]) {
-	    idx_max = idx;
-	}
+    for (ptr = str; *ptr; ptr++) {
+        switch (*ptr) {
+            case '|': idx = 0; break;
+            case ',': idx = 1; break;
+            case ';': idx = 2; break;
+            case ':': idx = 3; break;
+            default: continue; break;
+        }
+        counter[idx]++;
+        if (counter[idx] > counter[idx_max]) {
+            idx_max = idx;
+        }
     }
-    
+
     if (counter[idx_max] > n) {
-	return (unsigned char) delimiter[idx_max];
+        return (unsigned char)delimiter[idx_max];
     } else {
-	return -1;
+        return -1;
     }
 } /* pick_and_place_screen_for_delimiter */
 
-
 /**Parses the PNP data.
-   two lists are filled with the row data.\n One for the scrollable list in the search and select parts interface, the other one a mere two columned list, which drives the autocompletion when entering a search.\n
-   It also tries to determine the shape of a part and sets  pnp_state->shape accordingly which will be used when drawing the selections as an overlay on screen.
+   two lists are filled with the row data.\n One for the scrollable list in the search and select parts interface, the
+   other one a mere two columned list, which drives the autocompletion when entering a search.\n It also tries to
+   determine the shape of a part and sets  pnp_state->shape accordingly which will be used when drawing the selections
+   as an overlay on screen.
    @return the initial node of the pnp_state netlist
  */
 
-GArray *
-pick_and_place_parse_file(gerb_file_t *fd)
-{
-    PnpPartData   pnpPartData;
+GArray*
+pick_and_place_parse_file(gerb_file_t* fd) {
+    PnpPartData pnpPartData;
     memset(&pnpPartData, 0, sizeof(PnpPartData));
-    int           lineCounter = 0, parsedLines = 0;
-    int           ret;
-    char          *row[12];
-    char          buf[MAXL+2], buf0[MAXL+2];
-    char          def_unit[41] = {0,};
-    double        tmp_x, tmp_y;
-    gerbv_transf_t *tr_rot = gerb_transf_new();
-    GArray 	*pnpParseDataArray = g_array_new (FALSE, FALSE, sizeof(PnpPartData));
-    gboolean foundValidDataRow = FALSE;
+    int   lineCounter = 0, parsedLines = 0;
+    int   ret;
+    char* row[12];
+    char  buf[MAXL + 2], buf0[MAXL + 2];
+    char  def_unit[41] = {
+         0,
+    };
+    double          tmp_x, tmp_y;
+    gerbv_transf_t* tr_rot            = gerb_transf_new();
+    GArray*         pnpParseDataArray = g_array_new(FALSE, FALSE, sizeof(PnpPartData));
+    gboolean        foundValidDataRow = FALSE;
     /* Unit declaration for "PcbXY Version 1.0" files as exported by pcb */
-    const char *def_unit_prefix = "# X,Y in ";
-    
+    const char* def_unit_prefix = "# X,Y in ";
+
     /*
      * many locales redefine "." as "," and so on, so sscanf has problems when
-     * reading Pick and Place files using %f format 
+     * reading Pick and Place files using %f format
      */
-    setlocale(LC_NUMERIC, "C" );
-
-    while ( fgets(buf, MAXL, fd->fd) != NULL ) {
-	int len = strlen(buf)-1;
-	int i_length = 0, i_width = 0;
-	
-	lineCounter += 1; /*next line*/
-	if(lineCounter < 2) {
-	    /* 
-	     * TODO in principle column names could be read and interpreted
-	     * but we skip the first line with names of columns for this time
-	     */
-	    continue;
-	}
-	if(len >= 0 && buf[len] == '\n') {
-	    buf[len--] = 0;
-	}
-	if(len >= 0 && buf[len] == '\r') {
-	    buf[len--] = 0;
-	}
-	if (0 == strncmp(buf, def_unit_prefix, strlen(def_unit_prefix))) {
-	    sscanf(&buf[strlen(def_unit_prefix)], "%40s.", def_unit);
-	}
-	if (len <= 11)  {  //lets check a minimum length of 11
-	    continue;
-	}
-
-	if ((len > 0) && (buf[0] == '%')) {
-	    continue;
-	}
-
-	/* Abort if we see a G54 */
-	if ((len > 4) && (strncmp(buf,"G54 ", 4) == 0)) {
-	    g_array_free (pnpParseDataArray, TRUE);
-	    return NULL;  
-	}
-
-	/* abort if we see a G04 code */
-	if ((len > 4) && (strncmp(buf,"G04 ", 4) == 0)) {
-	    g_array_free (pnpParseDataArray, TRUE);
-	    return NULL;  
-	}
-
-	/* this accepts file both with and without quotes */
-/* 	if (!pnp_state) { /\* we are in first line *\/ */
-/* 	   if ((delimiter = pnp_screen_for_delimiter(buf, 8)) < 0) { */
-/* 	   continue; */
-/* 	   } */
-/* 	} */
-
-	ret = csv_row_parse(buf, MAXL,  buf0, MAXL, row, 11, ',',   CSV_QUOTES);
-
-	if (ret > 0) {
-	    foundValidDataRow = TRUE;
-	} else {
-	    continue;
-	}
-/* 	printf("direct:%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,  %s, ret %d\n", row[0], row[1], row[2],row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], ret);        */
-/* 	g_warning ("FFF %s %s\n",row[8],row[6]); */
-
-	if (row[0] && row[8]) { // here could be some better check for the syntax
-	    snprintf (pnpPartData.designator, sizeof(pnpPartData.designator)-1, "%s", row[0]);
-	    snprintf (pnpPartData.footprint, sizeof(pnpPartData.footprint)-1, "%s", row[1]);
-	    snprintf (pnpPartData.layer, sizeof(pnpPartData.layer)-1, "%s", row[8]);
-	    if (row[10] != NULL) {
-		if ( ! g_utf8_validate(row[10], -1, NULL)) {
-		    gchar * str = g_convert(row[10], strlen(row[10]), "UTF-8", "ISO-8859-1",
-					    NULL, NULL, NULL);
-		    // I have not decided yet whether it is better to use always
-		    // "ISO-8859-1" or current locale.
-		    // str = g_locale_to_utf8(row[10], -1, NULL, NULL, NULL);
-		    snprintf (pnpPartData.comment, sizeof(pnpPartData.comment)-1, "%s", str);
-		    g_free(str);
-		} else {
-		    snprintf (pnpPartData.comment, sizeof(pnpPartData.comment)-1, "%s", row[10]);
-		}
-	    }
-	    /*
-	      gchar* g_convert(const gchar *str, gssize len, const gchar *to_codeset, const gchar *from_codeset, gsize *bytes_read, gsize *bytes_written, GError **error);
-	    */
-	    pnpPartData.mid_x = pick_and_place_get_float_unit(row[2], def_unit);
-	    pnpPartData.mid_y = pick_and_place_get_float_unit(row[3], def_unit);
-	    pnpPartData.ref_x = pick_and_place_get_float_unit(row[4], def_unit);
-	    pnpPartData.ref_y = pick_and_place_get_float_unit(row[5], def_unit);
-	    pnpPartData.pad_x = pick_and_place_get_float_unit(row[6], def_unit);
-	    pnpPartData.pad_y = pick_and_place_get_float_unit(row[7], def_unit);
-	    /* This line causes segfault if we accidently starts parsing 
-	     * a gerber file. It is crap crap crap */
-	    if (row[9]) {
-		int const rc = sscanf(row[9], "%lf", &pnpPartData.rotation); // no units, always deg
-
-		/* CVE-2021-40403
-		 */
-		if (1 != rc) {
-			g_array_free (pnpParseDataArray, TRUE);
-			return NULL;  
-		}
-	    }
-	}
-	/* for now, default back to PCB program format
-	 * TODO: implement better checking for format
-	 */
-	else if (row[0] && row[1] && row[2] && row[3] && row[4] && row[5] && row[6]) {
-	    snprintf (pnpPartData.designator, sizeof(pnpPartData.designator)-1, "%s", row[0]);
-	    snprintf (pnpPartData.footprint, sizeof(pnpPartData.footprint)-1, "%s", row[1]);		
-	    snprintf (pnpPartData.layer, sizeof(pnpPartData.layer)-1, "%s", row[6]);	
-	    pnpPartData.mid_x = pick_and_place_get_float_unit(row[3], def_unit);
-	    pnpPartData.mid_y = pick_and_place_get_float_unit(row[4], def_unit);
-	    pnpPartData.pad_x = pnpPartData.mid_x + 0.03;
-	    pnpPartData.pad_y = pnpPartData.mid_y + 0.03;
-
-	    /* check for coordinate sanity, and abort if it fails
-	     * Note: this is mainly to catch comment lines that get parsed
-	     */
-	    if ((fabs(pnpPartData.mid_x) < 0.001)&&(fabs(pnpPartData.mid_y) < 0.001)) {
-		continue;			
-	    }
-
-	    /* CVE-2021-40403
-	     */
-	    int const rc = sscanf(row[5], "%lf", &pnpPartData.rotation); // no units, always deg
-	    if (1 != rc) {
-		g_array_free (pnpParseDataArray, TRUE);
-		return NULL;  
-	    }
-	} else {
-	    continue;
-	}
-
-
-	/* 
-	 * now, try and figure out the actual footprint shape to draw, or just
-	 * guess something reasonable
-	 */
-	if(sscanf(pnpPartData.footprint, "%02d%02d", &i_length, &i_width) == 2) {
-	    // parse footprints like 0805 or 1206
-	    pnpPartData.length = 0.01 * i_length;
-	    pnpPartData.width = 0.01 * i_width;
-	    pnpPartData.shape = PART_SHAPE_RECTANGLE;
-	} else { 
-	    gerb_transf_reset(tr_rot);
-	    gerb_transf_rotate(tr_rot, -DEG2RAD(pnpPartData.rotation));/* rotate it back to get dimensions */
-	    gerb_transf_apply( pnpPartData.pad_x -  pnpPartData.mid_x, 
-			       pnpPartData.pad_y - pnpPartData.mid_y, tr_rot, &tmp_x, &tmp_y);
-	    if ((fabs(tmp_y) > fabs(tmp_x/100)) && (fabs(tmp_x) > fabs(tmp_y/100))){
-		pnpPartData.length = 2 * fabs(tmp_x);/* get dimensions*/
-		pnpPartData.width = 2 * fabs(tmp_y);
-		pnpPartData.shape = PART_SHAPE_STD;
-	    } else {
-		pnpPartData.length = 0.015;
-		pnpPartData.width = 0.015;
-		pnpPartData.shape = PART_SHAPE_UNKNOWN;
-	    }
-	}  
-	g_array_append_val (pnpParseDataArray, pnpPartData);
-	parsedLines += 1;
-    }   
+    setlocale(LC_NUMERIC, "C");
+
+    while (fgets(buf, MAXL, fd->fd) != NULL) {
+        int len      = strlen(buf) - 1;
+        int i_length = 0, i_width = 0;
+
+        lineCounter += 1; /*next line*/
+        if (lineCounter < 2) {
+            /*
+             * TODO in principle column names could be read and interpreted
+             * but we skip the first line with names of columns for this time
+             */
+            continue;
+        }
+        if (len >= 0 && buf[len] == '\n') {
+            buf[len--] = 0;
+        }
+        if (len >= 0 && buf[len] == '\r') {
+            buf[len--] = 0;
+        }
+        if (0 == strncmp(buf, def_unit_prefix, strlen(def_unit_prefix))) {
+            sscanf(&buf[strlen(def_unit_prefix)], "%40s.", def_unit);
+        }
+        if (len <= 11) {  // lets check a minimum length of 11
+            continue;
+        }
+
+        if ((len > 0) && (buf[0] == '%')) {
+            continue;
+        }
+
+        /* Abort if we see a G54 */
+        if ((len > 4) && (strncmp(buf, "G54 ", 4) == 0)) {
+            g_array_free(pnpParseDataArray, TRUE);
+            return NULL;
+        }
+
+        /* abort if we see a G04 code */
+        if ((len > 4) && (strncmp(buf, "G04 ", 4) == 0)) {
+            g_array_free(pnpParseDataArray, TRUE);
+            return NULL;
+        }
+
+        /* this accepts file both with and without quotes */
+        /* 	if (!pnp_state) { /\* we are in first line *\/ */
+        /* 	   if ((delimiter = pnp_screen_for_delimiter(buf, 8)) < 0) { */
+        /* 	   continue; */
+        /* 	   } */
+        /* 	} */
+
+        ret = csv_row_parse(buf, MAXL, buf0, MAXL, row, 11, ',', CSV_QUOTES);
+
+        if (ret > 0) {
+            foundValidDataRow = TRUE;
+        } else {
+            continue;
+        }
+        /* 	printf("direct:%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,  %s, ret %d\n", row[0], row[1], row[2],row[3],
+         * row[4], row[5], row[6], row[7], row[8], row[9], row[10], ret);        */
+        /* 	g_warning ("FFF %s %s\n",row[8],row[6]); */
+
+        if (row[0] && row[8]) {  // here could be some better check for the syntax
+            snprintf(pnpPartData.designator, sizeof(pnpPartData.designator) - 1, "%s", row[0]);
+            snprintf(pnpPartData.footprint, sizeof(pnpPartData.footprint) - 1, "%s", row[1]);
+            snprintf(pnpPartData.layer, sizeof(pnpPartData.layer) - 1, "%s", row[8]);
+            if (row[10] != NULL) {
+                if (!g_utf8_validate(row[10], -1, NULL)) {
+                    gchar* str = g_convert(row[10], strlen(row[10]), "UTF-8", "ISO-8859-1", NULL, NULL, NULL);
+                    // I have not decided yet whether it is better to use always
+                    // "ISO-8859-1" or current locale.
+                    // str = g_locale_to_utf8(row[10], -1, NULL, NULL, NULL);
+                    snprintf(pnpPartData.comment, sizeof(pnpPartData.comment) - 1, "%s", str);
+                    g_free(str);
+                } else {
+                    snprintf(pnpPartData.comment, sizeof(pnpPartData.comment) - 1, "%s", row[10]);
+                }
+            }
+            /*
+              gchar* g_convert(const gchar *str, gssize len, const gchar *to_codeset, const gchar *from_codeset, gsize
+              *bytes_read, gsize *bytes_written, GError **error);
+            */
+            pnpPartData.mid_x = pick_and_place_get_float_unit(row[2], def_unit);
+            pnpPartData.mid_y = pick_and_place_get_float_unit(row[3], def_unit);
+            pnpPartData.ref_x = pick_and_place_get_float_unit(row[4], def_unit);
+            pnpPartData.ref_y = pick_and_place_get_float_unit(row[5], def_unit);
+            pnpPartData.pad_x = pick_and_place_get_float_unit(row[6], def_unit);
+            pnpPartData.pad_y = pick_and_place_get_float_unit(row[7], def_unit);
+            /* This line causes segfault if we accidently starts parsing
+             * a gerber file. It is crap crap crap */
+            if (row[9]) {
+                const int rc = sscanf(row[9], "%lf", &pnpPartData.rotation);  // no units, always deg
+
+                /* CVE-2021-40403
+                 */
+                if (1 != rc) {
+                    g_array_free(pnpParseDataArray, TRUE);
+                    return NULL;
+                }
+            }
+        }
+        /* for now, default back to PCB program format
+         * TODO: implement better checking for format
+         */
+        else if (row[0] && row[1] && row[2] && row[3] && row[4] && row[5] && row[6]) {
+            snprintf(pnpPartData.designator, sizeof(pnpPartData.designator) - 1, "%s", row[0]);
+            snprintf(pnpPartData.footprint, sizeof(pnpPartData.footprint) - 1, "%s", row[1]);
+            snprintf(pnpPartData.layer, sizeof(pnpPartData.layer) - 1, "%s", row[6]);
+            pnpPartData.mid_x = pick_and_place_get_float_unit(row[3], def_unit);
+            pnpPartData.mid_y = pick_and_place_get_float_unit(row[4], def_unit);
+            pnpPartData.pad_x = pnpPartData.mid_x + 0.03;
+            pnpPartData.pad_y = pnpPartData.mid_y + 0.03;
+
+            /* check for coordinate sanity, and abort if it fails
+             * Note: this is mainly to catch comment lines that get parsed
+             */
+            if ((fabs(pnpPartData.mid_x) < 0.001) && (fabs(pnpPartData.mid_y) < 0.001)) {
+                continue;
+            }
+
+            /* CVE-2021-40403
+             */
+            const int rc = sscanf(row[5], "%lf", &pnpPartData.rotation);  // no units, always deg
+            if (1 != rc) {
+                g_array_free(pnpParseDataArray, TRUE);
+                return NULL;
+            }
+        } else {
+            continue;
+        }
+
+        /*
+         * now, try and figure out the actual footprint shape to draw, or just
+         * guess something reasonable
+         */
+        if (sscanf(pnpPartData.footprint, "%02d%02d", &i_length, &i_width) == 2) {
+            // parse footprints like 0805 or 1206
+            pnpPartData.length = 0.01 * i_length;
+            pnpPartData.width  = 0.01 * i_width;
+            pnpPartData.shape  = PART_SHAPE_RECTANGLE;
+        } else {
+            gerb_transf_reset(tr_rot);
+            gerb_transf_rotate(tr_rot, -DEG2RAD(pnpPartData.rotation)); /* rotate it back to get dimensions */
+            gerb_transf_apply(
+                pnpPartData.pad_x - pnpPartData.mid_x, pnpPartData.pad_y - pnpPartData.mid_y, tr_rot, &tmp_x, &tmp_y
+            );
+            if ((fabs(tmp_y) > fabs(tmp_x / 100)) && (fabs(tmp_x) > fabs(tmp_y / 100))) {
+                pnpPartData.length = 2 * fabs(tmp_x); /* get dimensions*/
+                pnpPartData.width  = 2 * fabs(tmp_y);
+                pnpPartData.shape  = PART_SHAPE_STD;
+            } else {
+                pnpPartData.length = 0.015;
+                pnpPartData.width  = 0.015;
+                pnpPartData.shape  = PART_SHAPE_UNKNOWN;
+            }
+        }
+        g_array_append_val(pnpParseDataArray, pnpPartData);
+        parsedLines += 1;
+    }
     gerb_transf_free(tr_rot);
     /* fd->ptr=0; */
     /* rewind(fd->fd); */
-	
+
     /* so a sanity check and see if this is a valid pnp file */
-    if ((((float) parsedLines / (float) lineCounter) < 0.3) ||
-	(!foundValidDataRow)) {
-	/* this doesn't look like a valid PNP file, so return error */
-	g_array_free (pnpParseDataArray, TRUE);
-	return NULL;
-    }     
+    if ((((float)parsedLines / (float)lineCounter) < 0.3) || (!foundValidDataRow)) {
+        /* this doesn't look like a valid PNP file, so return error */
+        g_array_free(pnpParseDataArray, TRUE);
+        return NULL;
+    }
     return pnpParseDataArray;
 } /* pick_and_place_parse_file */
 
-
 /*	------------------------------------------------------------------
  *	pick_and_place_check_file_type
  *	------------------------------------------------------------------
  *	Description: Tries to parse the given file into a pick-and-place
  *		data set. If it fails to read any good rows, then returns
  *		FALSE, otherwise it returns TRUE.
- *	Notes: 
+ *	Notes:
  *	------------------------------------------------------------------
  */
 gboolean
-pick_and_place_check_file_type(gerb_file_t *fd, gboolean *returnFoundBinary)
-{
-    char *buf;
-    int len = 0;
-    int i;
-    char *letter;
-    gboolean found_binary = FALSE;
-    gboolean found_G54 = FALSE;
-    gboolean found_M0 = FALSE;
-    gboolean found_M2 = FALSE;
-    gboolean found_G2 = FALSE;
-    gboolean found_ADD = FALSE;
-    gboolean found_comma = FALSE;
-    gboolean found_R = FALSE;
-    gboolean found_U = FALSE;
-    gboolean found_C = FALSE;
+pick_and_place_check_file_type(gerb_file_t* fd, gboolean* returnFoundBinary) {
+    char*    buf;
+    int      len = 0;
+    int      i;
+    char*    letter;
+    gboolean found_binary    = FALSE;
+    gboolean found_G54       = FALSE;
+    gboolean found_M0        = FALSE;
+    gboolean found_M2        = FALSE;
+    gboolean found_G2        = FALSE;
+    gboolean found_ADD       = FALSE;
+    gboolean found_comma     = FALSE;
+    gboolean found_R         = FALSE;
+    gboolean found_U         = FALSE;
+    gboolean found_C         = FALSE;
     gboolean found_boardside = FALSE;
 
     buf = malloc(MAXL);
     if (buf == NULL)
-	GERB_FATAL_ERROR("malloc buf failed in %s()", __FUNCTION__);
+        GERB_FATAL_ERROR("malloc buf failed in %s()", __FUNCTION__);
 
     while (fgets(buf, MAXL, fd->fd) != NULL) {
-	len = strlen(buf);
-     
-	/* First look through the file for indications of its type */
-	
-	/* check for non-binary file */
-	for (i = 0; i < len; i++) {
-	    if (!isprint((int) buf[i]) && (buf[i] != '\r') && 
-                (buf[i] != '\n') && (buf[i] != '\t')) {
-		found_binary = TRUE;
-	    }
-	}
-	
-	if (g_strstr_len(buf, len, "G54")) {
-	    found_G54 = TRUE;
-	}
-	if (g_strstr_len(buf, len, "M00")) {
-	    found_M0 = TRUE;
-	}
-	if (g_strstr_len(buf, len, "M02")) {
-	    found_M2 = TRUE;
-	}
-	if (g_strstr_len(buf, len, "G02")) {
-	    found_G2 = TRUE;
-	}
-	if (g_strstr_len(buf, len, "ADD")) {
-	    found_ADD = TRUE;
-	}
-	if (g_strstr_len(buf, len, ",")) {
-	    found_comma = TRUE;
-	}
-	/* Semicolon can be separator too */
-	if (g_strstr_len(buf, len, ";")) {
-	    found_comma = TRUE;
-	}
-	
-	/* Look for refdes -- This is dumb, but what else can we do? */
-	if ((letter = g_strstr_len(buf, len, "R")) != NULL) {
-	    if (isdigit((int) letter[1])) { /* grab char after R */
-		found_R = TRUE;
-	    }
-	}
-	if ((letter = g_strstr_len(buf, len, "C")) != NULL) {
-	    if (isdigit((int) letter[1])) { /* grab char after C */
-		found_C = TRUE;
-	    }
-	}
-	if ((letter = g_strstr_len(buf, len, "U")) != NULL) {
-	    if (isdigit((int) letter[1])) { /* grab char after U */
-		found_U = TRUE;
-	    }
-	}
-	
-	/* Look for board side indicator since this is required
-	 * by many vendors */
-	if (g_strstr_len(buf, len, "top")) {
-	    found_boardside = TRUE;
-	}
-	if (g_strstr_len(buf, len, "Top")) {
-	    found_boardside = TRUE;
-	}
-	if (g_strstr_len(buf, len, "TOP")) {
-	    found_boardside = TRUE;
-	}
-	/* Also look for evidence of "Layer" in header.... */
-	if (g_strstr_len(buf, len, "ayer")) {
-	    found_boardside = TRUE;
-	}
-	if (g_strstr_len(buf, len, "AYER")) {
-	    found_boardside = TRUE;
-	}
-	
+        len = strlen(buf);
+
+        /* First look through the file for indications of its type */
+
+        /* check for non-binary file */
+        for (i = 0; i < len; i++) {
+            if (!isprint((int)buf[i]) && (buf[i] != '\r') && (buf[i] != '\n') && (buf[i] != '\t')) {
+                found_binary = TRUE;
+            }
+        }
+
+        if (g_strstr_len(buf, len, "G54")) {
+            found_G54 = TRUE;
+        }
+        if (g_strstr_len(buf, len, "M00")) {
+            found_M0 = TRUE;
+        }
+        if (g_strstr_len(buf, len, "M02")) {
+            found_M2 = TRUE;
+        }
+        if (g_strstr_len(buf, len, "G02")) {
+            found_G2 = TRUE;
+        }
+        if (g_strstr_len(buf, len, "ADD")) {
+            found_ADD = TRUE;
+        }
+        if (g_strstr_len(buf, len, ",")) {
+            found_comma = TRUE;
+        }
+        /* Semicolon can be separator too */
+        if (g_strstr_len(buf, len, ";")) {
+            found_comma = TRUE;
+        }
+
+        /* Look for refdes -- This is dumb, but what else can we do? */
+        if ((letter = g_strstr_len(buf, len, "R")) != NULL) {
+            if (isdigit((int)letter[1])) { /* grab char after R */
+                found_R = TRUE;
+            }
+        }
+        if ((letter = g_strstr_len(buf, len, "C")) != NULL) {
+            if (isdigit((int)letter[1])) { /* grab char after C */
+                found_C = TRUE;
+            }
+        }
+        if ((letter = g_strstr_len(buf, len, "U")) != NULL) {
+            if (isdigit((int)letter[1])) { /* grab char after U */
+                found_U = TRUE;
+            }
+        }
+
+        /* Look for board side indicator since this is required
+         * by many vendors */
+        if (g_strstr_len(buf, len, "top")) {
+            found_boardside = TRUE;
+        }
+        if (g_strstr_len(buf, len, "Top")) {
+            found_boardside = TRUE;
+        }
+        if (g_strstr_len(buf, len, "TOP")) {
+            found_boardside = TRUE;
+        }
+        /* Also look for evidence of "Layer" in header.... */
+        if (g_strstr_len(buf, len, "ayer")) {
+            found_boardside = TRUE;
+        }
+        if (g_strstr_len(buf, len, "AYER")) {
+            found_boardside = TRUE;
+        }
     }
     rewind(fd->fd);
     free(buf);
 
     /* Now form logical expression determining if this is a pick-place file */
     *returnFoundBinary = found_binary;
-    if (found_G54) 
-	return FALSE;
-    if (found_M0) 
-	return FALSE;
-    if (found_M2) 
-	return FALSE;
-    if (found_G2) 
-	return FALSE;
-    if (found_ADD) 
-	return FALSE;
-    if (found_comma && (found_R || found_C || found_U) && 
-	found_boardside) 
-	return TRUE;
-    
+    if (found_G54)
+        return FALSE;
+    if (found_M0)
+        return FALSE;
+    if (found_M2)
+        return FALSE;
+    if (found_G2)
+        return FALSE;
+    if (found_ADD)
+        return FALSE;
+    if (found_comma && (found_R || found_C || found_U) && found_boardside)
+        return TRUE;
+
     return FALSE;
-    
-} /* pick_and_place_check_file_type */
 
+} /* pick_and_place_check_file_type */
 
 /*	------------------------------------------------------------------
  *	pick_and_place_convert_pnp_data_to_image
@@ -552,58 +533,55 @@ pick_and_place_check_file_type(gerb_file_t *fd, gboolean *returnFoundBinary)
  *	Notes:
  *	------------------------------------------------------------------
  */
-gerbv_image_t *
-pick_and_place_convert_pnp_data_to_image(GArray *parsedPickAndPlaceData, gint boardSide) 
-{
-    gerbv_image_t *image = NULL;
-    gerbv_net_t *curr_net = NULL;
-    gerbv_transf_t *tr_rot = gerb_transf_new();
-    gerbv_drill_stats_t *stats;  /* Eventually replace with pick_place_stats */
-    gboolean foundElement = FALSE;
-    const double draw_width = 0.01;
+gerbv_image_t*
+pick_and_place_convert_pnp_data_to_image(GArray* parsedPickAndPlaceData, gint boardSide) {
+    gerbv_image_t*       image    = NULL;
+    gerbv_net_t*         curr_net = NULL;
+    gerbv_transf_t*      tr_rot   = gerb_transf_new();
+    gerbv_drill_stats_t* stats; /* Eventually replace with pick_place_stats */
+    gboolean             foundElement = FALSE;
+    const double         draw_width   = 0.01;
 
     /* step through and make sure we have an element on the layer before
        we actually create a new image for it and fill it */
     for (guint i = 0; i < parsedPickAndPlaceData->len; i++) {
-	PnpPartData partData = g_array_index(parsedPickAndPlaceData, PnpPartData, i);
-	
-	if ((boardSide == 0) && !((partData.layer[0]=='b') || (partData.layer[0]=='B')))
-		continue;
-	if ((boardSide == 1) && !((partData.layer[0]=='t') || (partData.layer[0]=='T')))
-		continue;
-		
-	foundElement = TRUE;
+        PnpPartData partData = g_array_index(parsedPickAndPlaceData, PnpPartData, i);
+
+        if ((boardSide == 0) && !((partData.layer[0] == 'b') || (partData.layer[0] == 'B')))
+            continue;
+        if ((boardSide == 1) && !((partData.layer[0] == 't') || (partData.layer[0] == 'T')))
+            continue;
+
+        foundElement = TRUE;
     }
     if (!foundElement)
-    	return NULL;
+        return NULL;
 
     image = gerbv_create_image(image, "Pick and Place (X-Y) File");
     if (image == NULL) {
-	GERB_FATAL_ERROR("malloc image failed in %s()", __FUNCTION__);
+        GERB_FATAL_ERROR("malloc image failed in %s()", __FUNCTION__);
     }
 
     image->format = g_new0(gerbv_format_t, 1);
     if (image->format == NULL) {
-	GERB_FATAL_ERROR("malloc format failed in %s()", __FUNCTION__);
+        GERB_FATAL_ERROR("malloc format failed in %s()", __FUNCTION__);
     }
 
     /* Separate top/bot layer type is needed for reload purpose */
     if (boardSide == 1)
-	    image->layertype = GERBV_LAYERTYPE_PICKANDPLACE_TOP;
+        image->layertype = GERBV_LAYERTYPE_PICKANDPLACE_TOP;
     else
-	    image->layertype = GERBV_LAYERTYPE_PICKANDPLACE_BOT;
+        image->layertype = GERBV_LAYERTYPE_PICKANDPLACE_BOT;
 
     stats = gerbv_drill_stats_new();
     if (stats == NULL)
-        GERB_FATAL_ERROR("malloc pick_place_stats failed in %s()",
-			__FUNCTION__);
+        GERB_FATAL_ERROR("malloc pick_place_stats failed in %s()", __FUNCTION__);
     image->drill_stats = stats;
 
-
-    curr_net = image->netlist;
+    curr_net        = image->netlist;
     curr_net->layer = image->layers;
     curr_net->state = image->states;
-    pnp_reset_bbox (curr_net);	
+    pnp_reset_bbox(curr_net);
     image->info->min_x = HUGE_VAL;
     image->info->min_y = HUGE_VAL;
     image->info->max_x = -HUGE_VAL;
@@ -611,186 +589,167 @@ pick_and_place_convert_pnp_data_to_image(GArray *parsedPickAndPlaceData, gint bo
 
     image->aperture[0] = g_new0(gerbv_aperture_t, 1);
     assert(image->aperture[0] != NULL);
-    image->aperture[0]->type = GERBV_APTYPE_CIRCLE;
-    image->aperture[0]->amacro = NULL;
-    image->aperture[0]->parameter[0] = draw_width;
+    image->aperture[0]->type           = GERBV_APTYPE_CIRCLE;
+    image->aperture[0]->amacro         = NULL;
+    image->aperture[0]->parameter[0]   = draw_width;
     image->aperture[0]->nuf_parameters = 1;
 
     for (guint i = 0; i < parsedPickAndPlaceData->len; i++) {
-	PnpPartData partData = g_array_index(parsedPickAndPlaceData, PnpPartData, i);
-	float radius,labelOffset;  
-
-	curr_net = pnp_new_net(curr_net);
-	curr_net->layer = image->layers;
-	curr_net->state = image->states;
-
-	if ((partData.rotation > 89) && (partData.rotation < 91))
-		labelOffset = fabs(partData.length/2);
-	else if ((partData.rotation > 179) && (partData.rotation < 181))
-		labelOffset = fabs(partData.width/2);
-	else if ((partData.rotation > 269) && (partData.rotation < 271))
-		labelOffset = fabs(partData.length/2);
-	else if ((partData.rotation > -91) && (partData.rotation < -89))
-		labelOffset = fabs(partData.length/2);
-	else if ((partData.rotation > -181) && (partData.rotation < -179))
-		labelOffset = fabs(partData.width/2);
-	else if ((partData.rotation > -271) && (partData.rotation < -269))
-		labelOffset = fabs(partData.length/2);
-	else labelOffset = fabs(partData.width/2);
-
-	partData.rotation = DEG2RAD(partData.rotation);
-
-	/* check if the entry is on the specified layer */
-	if ((boardSide == 0) && !((partData.layer[0]=='b') || (partData.layer[0]=='B')))
-		continue;
-	if ((boardSide == 1) && !((partData.layer[0]=='t') || (partData.layer[0]=='T')))
-		continue;
-
-	curr_net = pnp_new_net(curr_net);
-	pnp_init_net(curr_net, image, partData.designator,
-			GERBV_APERTURE_STATE_OFF,
-			GERBV_INTERPOLATION_LINEARx1);
-
-	/* First net of PNP is just a label holder, so calculate the lower left
-	 * location to line up above the element */
-	curr_net->start_x = curr_net->stop_x = partData.mid_x;
-	curr_net->start_y = curr_net->stop_y =
-		partData.mid_y + labelOffset + draw_width;   
-
-	gerb_transf_reset(tr_rot);
-	gerb_transf_shift(tr_rot, partData.mid_x, partData.mid_y);
-	gerb_transf_rotate(tr_rot, -partData.rotation);
-	    
-	if ((partData.shape == PART_SHAPE_RECTANGLE) ||
-	    (partData.shape == PART_SHAPE_STD)) {
-	    // TODO: draw rectangle length x width taking into account rotation or pad x,y
-
-	    curr_net = pnp_new_net(curr_net);
-	    pnp_init_net(curr_net, image, partData.designator,
-			    GERBV_APERTURE_STATE_ON,
-			    GERBV_INTERPOLATION_LINEARx1);
-
-	    gerb_transf_apply(partData.length/2, partData.width/2, tr_rot, 
-			      &curr_net->start_x, &curr_net->start_y);
-	    gerb_transf_apply(-partData.length/2, partData.width/2, tr_rot, 
-			      &curr_net->stop_x, &curr_net->stop_y);
-	    
-/* TODO: write unifying function */
-
-	    curr_net = pnp_new_net(curr_net);
-	    pnp_init_net(curr_net, image, partData.designator,
-			    GERBV_APERTURE_STATE_ON,
-			    GERBV_INTERPOLATION_LINEARx1);
-
-	    gerb_transf_apply(-partData.length/2, partData.width/2, tr_rot, 
-			      &curr_net->start_x, &curr_net->start_y);
-	    gerb_transf_apply(-partData.length/2, -partData.width/2, tr_rot, 
-			      &curr_net->stop_x, &curr_net->stop_y);
-
-	    curr_net = pnp_new_net(curr_net);
-	    pnp_init_net(curr_net, image, partData.designator,
-			    GERBV_APERTURE_STATE_ON,
-			    GERBV_INTERPOLATION_LINEARx1);
-
-	    gerb_transf_apply(-partData.length/2, -partData.width/2, tr_rot, 
-			      &curr_net->start_x, &curr_net->start_y);
-	    gerb_transf_apply(partData.length/2, -partData.width/2, tr_rot, 
-			      &curr_net->stop_x, &curr_net->stop_y);
-
-	    curr_net = pnp_new_net(curr_net);
-	    pnp_init_net(curr_net, image, partData.designator,
-			    GERBV_APERTURE_STATE_ON,
-			    GERBV_INTERPOLATION_LINEARx1);
-
-	    gerb_transf_apply(partData.length/2, -partData.width/2, tr_rot, 
-			      &curr_net->start_x, &curr_net->start_y);
-	    gerb_transf_apply(partData.length/2, partData.width/2, tr_rot, 
-			      &curr_net->stop_x, &curr_net->stop_y);
-
-	    curr_net = pnp_new_net(curr_net);
-	    pnp_init_net(curr_net, image, partData.designator,
-			    GERBV_APERTURE_STATE_ON,
-			    GERBV_INTERPOLATION_LINEARx1);
-
-	    if (partData.shape == PART_SHAPE_RECTANGLE) {
-		gerb_transf_apply(partData.length/4, -partData.width/2, tr_rot, 
-				  &curr_net->start_x, &curr_net->start_y);
-		gerb_transf_apply(partData.length/4, partData.width/2, tr_rot, 
-				  &curr_net->stop_x, &curr_net->stop_y);
-	    } else {
-		gerb_transf_apply(partData.length/4, partData.width/2, tr_rot, 
-				  &curr_net->start_x, &curr_net->start_y);
-		gerb_transf_apply(partData.length/4, partData.width/4, tr_rot, 
-				  &curr_net->stop_x, &curr_net->stop_y);
-
-		curr_net = pnp_new_net(curr_net);
-		pnp_init_net(curr_net, image, partData.designator,
-				GERBV_APERTURE_STATE_ON,
-				GERBV_INTERPOLATION_LINEARx1);
-
-		gerb_transf_apply(partData.length/2, partData.width/4, tr_rot, 
-				  &curr_net->start_x, &curr_net->start_y);
-		gerb_transf_apply(partData.length/4, partData.width/4, tr_rot, 
-				  &curr_net->stop_x, &curr_net->stop_y);     
-	    }
-
-	    /* calculate a rough radius for the min/max screen calcs later */
-	    radius = MAX(partData.length/2, partData.width/2);
-	} else {
-	    gdouble tmp_x,tmp_y;
-
-	    pnp_init_net(curr_net, image, partData.designator,
-			    GERBV_APERTURE_STATE_ON,
-			    GERBV_INTERPOLATION_LINEARx1);
-
-	    curr_net->start_x = partData.mid_x;
-	    curr_net->start_y = partData.mid_y;
-	    gerb_transf_apply( partData.pad_x -  partData.mid_x, 
-			       partData.pad_y - partData.mid_y, tr_rot, &tmp_x, &tmp_y);
-			       
-	    curr_net->stop_x = tmp_x;
-	    curr_net->stop_y = tmp_y;
-
-
-	    curr_net = pnp_new_net(curr_net);
-	    pnp_init_net(curr_net, image, partData.designator,
-			    GERBV_APERTURE_STATE_ON,
-			    GERBV_INTERPOLATION_CW_CIRCULAR);
-
-	    curr_net->start_x = partData.mid_x;
-	    curr_net->start_y = partData.mid_y;
-	    curr_net->stop_x = partData.pad_x;
-	    curr_net->stop_y = partData.pad_y;
-
-	    curr_net->cirseg = g_new0 (gerbv_cirseg_t, 1);
-	    curr_net->cirseg->angle1 = 0.0;
-	    curr_net->cirseg->angle2 = 360.0;
-	    curr_net->cirseg->cp_x = partData.mid_x;
-	    curr_net->cirseg->cp_y = partData.mid_y;
-	    radius = hypot(partData.pad_x - partData.mid_x,
-			    partData.pad_y-partData.mid_y);
-	    if (radius < 0.001)
-	    	radius = 0.1;
-	    curr_net->cirseg->width = 2*radius; /* fabs(pad_x-mid_x) */
-	    curr_net->cirseg->height = 2*radius;
-	}
-
-	/* 
-	 * update min and max numbers so the screen zoom-to-fit 
-	 *function will work
-	 */
-	image->info->min_x = MIN(image->info->min_x, (partData.mid_x - radius - 0.02));
-	image->info->min_y = MIN(image->info->min_y, (partData.mid_y - radius - 0.02));
-	image->info->max_x = MAX(image->info->max_x, (partData.mid_x + radius + 0.02));
-	image->info->max_y = MAX(image->info->max_y, (partData.mid_y + radius + 0.02));
+        PnpPartData partData = g_array_index(parsedPickAndPlaceData, PnpPartData, i);
+        float       radius, labelOffset;
+
+        curr_net        = pnp_new_net(curr_net);
+        curr_net->layer = image->layers;
+        curr_net->state = image->states;
+
+        if ((partData.rotation > 89) && (partData.rotation < 91))
+            labelOffset = fabs(partData.length / 2);
+        else if ((partData.rotation > 179) && (partData.rotation < 181))
+            labelOffset = fabs(partData.width / 2);
+        else if ((partData.rotation > 269) && (partData.rotation < 271))
+            labelOffset = fabs(partData.length / 2);
+        else if ((partData.rotation > -91) && (partData.rotation < -89))
+            labelOffset = fabs(partData.length / 2);
+        else if ((partData.rotation > -181) && (partData.rotation < -179))
+            labelOffset = fabs(partData.width / 2);
+        else if ((partData.rotation > -271) && (partData.rotation < -269))
+            labelOffset = fabs(partData.length / 2);
+        else
+            labelOffset = fabs(partData.width / 2);
+
+        partData.rotation = DEG2RAD(partData.rotation);
+
+        /* check if the entry is on the specified layer */
+        if ((boardSide == 0) && !((partData.layer[0] == 'b') || (partData.layer[0] == 'B')))
+            continue;
+        if ((boardSide == 1) && !((partData.layer[0] == 't') || (partData.layer[0] == 'T')))
+            continue;
+
+        curr_net = pnp_new_net(curr_net);
+        pnp_init_net(curr_net, image, partData.designator, GERBV_APERTURE_STATE_OFF, GERBV_INTERPOLATION_LINEARx1);
+
+        /* First net of PNP is just a label holder, so calculate the lower left
+         * location to line up above the element */
+        curr_net->start_x = curr_net->stop_x = partData.mid_x;
+        curr_net->start_y = curr_net->stop_y = partData.mid_y + labelOffset + draw_width;
+
+        gerb_transf_reset(tr_rot);
+        gerb_transf_shift(tr_rot, partData.mid_x, partData.mid_y);
+        gerb_transf_rotate(tr_rot, -partData.rotation);
+
+        if ((partData.shape == PART_SHAPE_RECTANGLE) || (partData.shape == PART_SHAPE_STD)) {
+            // TODO: draw rectangle length x width taking into account rotation or pad x,y
+
+            curr_net = pnp_new_net(curr_net);
+            pnp_init_net(curr_net, image, partData.designator, GERBV_APERTURE_STATE_ON, GERBV_INTERPOLATION_LINEARx1);
+
+            gerb_transf_apply(partData.length / 2, partData.width / 2, tr_rot, &curr_net->start_x, &curr_net->start_y);
+            gerb_transf_apply(-partData.length / 2, partData.width / 2, tr_rot, &curr_net->stop_x, &curr_net->stop_y);
+
+            /* TODO: write unifying function */
+
+            curr_net = pnp_new_net(curr_net);
+            pnp_init_net(curr_net, image, partData.designator, GERBV_APERTURE_STATE_ON, GERBV_INTERPOLATION_LINEARx1);
+
+            gerb_transf_apply(-partData.length / 2, partData.width / 2, tr_rot, &curr_net->start_x, &curr_net->start_y);
+            gerb_transf_apply(-partData.length / 2, -partData.width / 2, tr_rot, &curr_net->stop_x, &curr_net->stop_y);
+
+            curr_net = pnp_new_net(curr_net);
+            pnp_init_net(curr_net, image, partData.designator, GERBV_APERTURE_STATE_ON, GERBV_INTERPOLATION_LINEARx1);
+
+            gerb_transf_apply(
+                -partData.length / 2, -partData.width / 2, tr_rot, &curr_net->start_x, &curr_net->start_y
+            );
+            gerb_transf_apply(partData.length / 2, -partData.width / 2, tr_rot, &curr_net->stop_x, &curr_net->stop_y);
+
+            curr_net = pnp_new_net(curr_net);
+            pnp_init_net(curr_net, image, partData.designator, GERBV_APERTURE_STATE_ON, GERBV_INTERPOLATION_LINEARx1);
+
+            gerb_transf_apply(partData.length / 2, -partData.width / 2, tr_rot, &curr_net->start_x, &curr_net->start_y);
+            gerb_transf_apply(partData.length / 2, partData.width / 2, tr_rot, &curr_net->stop_x, &curr_net->stop_y);
+
+            curr_net = pnp_new_net(curr_net);
+            pnp_init_net(curr_net, image, partData.designator, GERBV_APERTURE_STATE_ON, GERBV_INTERPOLATION_LINEARx1);
+
+            if (partData.shape == PART_SHAPE_RECTANGLE) {
+                gerb_transf_apply(
+                    partData.length / 4, -partData.width / 2, tr_rot, &curr_net->start_x, &curr_net->start_y
+                );
+                gerb_transf_apply(
+                    partData.length / 4, partData.width / 2, tr_rot, &curr_net->stop_x, &curr_net->stop_y
+                );
+            } else {
+                gerb_transf_apply(
+                    partData.length / 4, partData.width / 2, tr_rot, &curr_net->start_x, &curr_net->start_y
+                );
+                gerb_transf_apply(
+                    partData.length / 4, partData.width / 4, tr_rot, &curr_net->stop_x, &curr_net->stop_y
+                );
+
+                curr_net = pnp_new_net(curr_net);
+                pnp_init_net(
+                    curr_net, image, partData.designator, GERBV_APERTURE_STATE_ON, GERBV_INTERPOLATION_LINEARx1
+                );
+
+                gerb_transf_apply(
+                    partData.length / 2, partData.width / 4, tr_rot, &curr_net->start_x, &curr_net->start_y
+                );
+                gerb_transf_apply(
+                    partData.length / 4, partData.width / 4, tr_rot, &curr_net->stop_x, &curr_net->stop_y
+                );
+            }
+
+            /* calculate a rough radius for the min/max screen calcs later */
+            radius = MAX(partData.length / 2, partData.width / 2);
+        } else {
+            gdouble tmp_x, tmp_y;
+
+            pnp_init_net(curr_net, image, partData.designator, GERBV_APERTURE_STATE_ON, GERBV_INTERPOLATION_LINEARx1);
+
+            curr_net->start_x = partData.mid_x;
+            curr_net->start_y = partData.mid_y;
+            gerb_transf_apply(partData.pad_x - partData.mid_x, partData.pad_y - partData.mid_y, tr_rot, &tmp_x, &tmp_y);
+
+            curr_net->stop_x = tmp_x;
+            curr_net->stop_y = tmp_y;
+
+            curr_net = pnp_new_net(curr_net);
+            pnp_init_net(
+                curr_net, image, partData.designator, GERBV_APERTURE_STATE_ON, GERBV_INTERPOLATION_CW_CIRCULAR
+            );
+
+            curr_net->start_x = partData.mid_x;
+            curr_net->start_y = partData.mid_y;
+            curr_net->stop_x  = partData.pad_x;
+            curr_net->stop_y  = partData.pad_y;
+
+            curr_net->cirseg         = g_new0(gerbv_cirseg_t, 1);
+            curr_net->cirseg->angle1 = 0.0;
+            curr_net->cirseg->angle2 = 360.0;
+            curr_net->cirseg->cp_x   = partData.mid_x;
+            curr_net->cirseg->cp_y   = partData.mid_y;
+            radius                   = hypot(partData.pad_x - partData.mid_x, partData.pad_y - partData.mid_y);
+            if (radius < 0.001)
+                radius = 0.1;
+            curr_net->cirseg->width  = 2 * radius; /* fabs(pad_x-mid_x) */
+            curr_net->cirseg->height = 2 * radius;
+        }
+
+        /*
+         * update min and max numbers so the screen zoom-to-fit
+         *function will work
+         */
+        image->info->min_x = MIN(image->info->min_x, (partData.mid_x - radius - 0.02));
+        image->info->min_y = MIN(image->info->min_y, (partData.mid_y - radius - 0.02));
+        image->info->max_x = MAX(image->info->max_x, (partData.mid_x + radius + 0.02));
+        image->info->max_y = MAX(image->info->max_y, (partData.mid_y + radius + 0.02));
     }
     curr_net->next = NULL;
-    
+
     gerb_transf_free(tr_rot);
     return image;
 } /* pick_and_place_convert_pnp_data_to_image */
 
-
 /*	------------------------------------------------------------------
  *	pick_and_place_parse_file_to_images
  *	------------------------------------------------------------------
@@ -802,57 +761,53 @@ pick_and_place_convert_pnp_data_to_image(GArray *parsedPickAndPlaceData, gint bo
  *	------------------------------------------------------------------
  */
 void
-pick_and_place_parse_file_to_images(gerb_file_t *fd, gerbv_image_t **topImage,
-			gerbv_image_t **bottomImage) 
-{ 
-	GArray *parsedPickAndPlaceData = pick_and_place_parse_file (fd);
+pick_and_place_parse_file_to_images(gerb_file_t* fd, gerbv_image_t** topImage, gerbv_image_t** bottomImage) {
+    GArray* parsedPickAndPlaceData = pick_and_place_parse_file(fd);
 
-	if (parsedPickAndPlaceData != NULL) {
-		/* Non NULL pointer is used as "not to reload" mark */
-		if (*bottomImage == NULL)
-			*bottomImage = pick_and_place_convert_pnp_data_to_image(parsedPickAndPlaceData, 0);
+    if (parsedPickAndPlaceData != NULL) {
+        /* Non NULL pointer is used as "not to reload" mark */
+        if (*bottomImage == NULL)
+            *bottomImage = pick_and_place_convert_pnp_data_to_image(parsedPickAndPlaceData, 0);
 
-		if (*topImage == NULL)
-			*topImage = pick_and_place_convert_pnp_data_to_image(parsedPickAndPlaceData, 1);
+        if (*topImage == NULL)
+            *topImage = pick_and_place_convert_pnp_data_to_image(parsedPickAndPlaceData, 1);
 
-		g_array_free (parsedPickAndPlaceData, TRUE);
-	}
+        g_array_free(parsedPickAndPlaceData, TRUE);
+    }
 } /* pick_and_place_parse_file_to_images */
 
-static gerbv_net_t *
-pnp_new_net(gerbv_net_t *net)
-{
-	gerbv_net_t *n;
-	net->next = g_new0(gerbv_net_t, 1);
-	n = net->next;
-	assert(n != NULL);
+static gerbv_net_t*
+pnp_new_net(gerbv_net_t* net) {
+    gerbv_net_t* n;
+    net->next = g_new0(gerbv_net_t, 1);
+    n         = net->next;
+    assert(n != NULL);
 
-	pnp_reset_bbox (n);
+    pnp_reset_bbox(n);
 
-	return n;
+    return n;
 }
 
 static void
-pnp_reset_bbox (gerbv_net_t *net)
-{
-	net->boundingBox.left = -HUGE_VAL;
-	net->boundingBox.right = HUGE_VAL;
-	net->boundingBox.bottom = -HUGE_VAL;
-	net->boundingBox.top = HUGE_VAL;
+pnp_reset_bbox(gerbv_net_t* net) {
+    net->boundingBox.left   = -HUGE_VAL;
+    net->boundingBox.right  = HUGE_VAL;
+    net->boundingBox.bottom = -HUGE_VAL;
+    net->boundingBox.top    = HUGE_VAL;
 }
 
 static void
-pnp_init_net(gerbv_net_t *net, gerbv_image_t *image, const char *label,
-		gerbv_aperture_state_t apert_state,
-		gerbv_interpolation_t interpol)
-{
-	net->aperture = 0;
-	net->aperture_state = apert_state;
-	net->interpolation = interpol;
-	net->layer = image->layers;
-	net->state = image->states;
-
-	if (strlen(label) > 0) {
-		net->label = g_string_new (label);
-	}
+pnp_init_net(
+    gerbv_net_t* net, gerbv_image_t* image, const char* label, gerbv_aperture_state_t apert_state,
+    gerbv_interpolation_t interpol
+) {
+    net->aperture       = 0;
+    net->aperture_state = apert_state;
+    net->interpolation  = interpol;
+    net->layer          = image->layers;
+    net->state          = image->states;
+
+    if (strlen(label) > 0) {
+        net->label = g_string_new(label);
+    }
 }
diff --git a/src/pick-and-place.h b/src/pick-and-place.h
index 95730eb..5a56712 100644
--- a/src/pick-and-place.h
+++ b/src/pick-and-place.h
@@ -36,38 +36,35 @@ typedef struct gerb_transf {
 } gerbv_transf_t;
 
 enum e_footprint {
-    PART_SHAPE_UNKNOWN = 0, /* drawn as circle with line*/
+    PART_SHAPE_UNKNOWN   = 0, /* drawn as circle with line*/
     PART_SHAPE_RECTANGLE = 1, /* rectangle with one side marked*/
-    PART_SHAPE_STD = 2 /* rectangle with one corner marked*/
+    PART_SHAPE_STD       = 2  /* rectangle with one corner marked*/
 };
 
 typedef struct {
-    char     designator[MAXL];
-    char     footprint[MAXL];
-    double   mid_x;
-    double   mid_y;
-    double   ref_x;
-    double   ref_y;
-    double   pad_x;
-    double   pad_y;
-    char     layer[MAXL]; /*T is top B is bottom*/
-    double   rotation;
-    char     comment[MAXL];    
-    int      shape;
-    double   width;
-    double   length;
-    unsigned int nuf_push;  /* Nuf pushes to estimate stack size */
+    char         designator[MAXL];
+    char         footprint[MAXL];
+    double       mid_x;
+    double       mid_y;
+    double       ref_x;
+    double       ref_y;
+    double       pad_x;
+    double       pad_y;
+    char         layer[MAXL]; /*T is top B is bottom*/
+    double       rotation;
+    char         comment[MAXL];
+    int          shape;
+    double       width;
+    double       length;
+    unsigned int nuf_push; /* Nuf pushes to estimate stack size */
 } PnpPartData;
 
-GArray *pick_and_place_parse_file (gerb_file_t *fd);
+GArray* pick_and_place_parse_file(gerb_file_t* fd);
 
-gerbv_image_t *pick_and_place_parse_file_to_image (gerb_file_t *fd);
+gerbv_image_t* pick_and_place_parse_file_to_image(gerb_file_t* fd);
 
-void
-pick_and_place_parse_file_to_images (gerb_file_t *fd, gerbv_image_t **topImage,
-			gerbv_image_t **bottomImage);
+void pick_and_place_parse_file_to_images(gerb_file_t* fd, gerbv_image_t** topImage, gerbv_image_t** bottomImage);
 
-gboolean
-pick_and_place_check_file_type(gerb_file_t *fd, gboolean *returnFoundBinary);
+gboolean pick_and_place_check_file_type(gerb_file_t* fd, gboolean* returnFoundBinary);
 
 #endif /* GERBV_LAYERTYPE_PICKANDPLACE_H */
diff --git a/src/project.c b/src/project.c
index 71a494e..e0b03f7 100644
--- a/src/project.c
+++ b/src/project.c
@@ -25,8 +25,7 @@
 /*! \file project.c
     \brief Routines for loading and saving project files.
     \ingroup gerbv
- */ 
-
+ */
 
 #ifdef HAVE_CONFIG_H
 #include "config.h"
@@ -68,7 +67,6 @@
 #include "interface.h"
 #include "render.h"
 
-
 /*
  * update this if the project file format changes.
  *
@@ -77,7 +75,7 @@
  * Do *not* update this simply because we have a new gerbv
  * version.
  *
- * If you bump this version, then you must also bump the 
+ * If you bump this version, then you must also bump the
  * version of gerbv.  For example, supplse the file version
  * is 2.0A and gerbv has 2.4B in configure.ac.  If you change
  * the file format version, you should change both the version
@@ -91,211 +89,207 @@
  */
 #define GERBV_DEFAULT_PROJECT_FILE_VERSION "1.9A"
 
-/* 
- * List of versions that we can load with this version of 
- * gerbv 
+/*
+ * List of versions that we can load with this version of
+ * gerbv
  */
-static const char * known_versions[] = {
-  "1.9A",
-  "2.0A",
-  NULL
-};
+static const char* known_versions[] = { "1.9A", "2.0A", NULL };
 
 /* DEBUG printing.  #define DEBUG 1 in config.h to use this fcn. */
-#define dprintf if(DEBUG) printf
+#define dprintf \
+    if (DEBUG)  \
+    printf
+
+static project_list_t* project_list_top = NULL;
 
-static project_list_t *project_list_top = NULL;
+static const int alpha_def_value = 177 * 257;
 
-static const int alpha_def_value = 177*257;
-  
 /* When a project file is loaded, this variable is set to the
- * version of the project file.  That can be used by various 
+ * version of the project file.  That can be used by various
  * functions which may need to do something different.
  */
 static int current_file_version = 0;
 
-
-/* 
+/*
  * Converts a string like "2.1A" "2.12C" or "3.2ZA" to the int
  * we use internally
  */
 static int
-version_str_to_int( const char * str)
-{
-  int r = 0;
-  gchar *dup, *tmps, *ptr;
+version_str_to_int(const char* str) {
+    int    r = 0;
+    gchar *dup, *tmps, *ptr;
 
-  if(str == NULL) {
-    return -1;
-  } else {
-    dprintf("%s(\"%s\")\n", __FUNCTION__, str);
+    if (str == NULL) {
+        return -1;
+    } else {
+        dprintf("%s(\"%s\")\n", __FUNCTION__, str);
+
+        /*
+         * Extract out the major number (versions are strings like 2.1A)
+         * and we want the "2" here.
+         */
+        tmps = g_strdup(str);
+        ptr  = tmps;
+        while (*ptr != '\0' && *ptr != '.') {
+            ptr++;
+        }
+        if (*ptr == '\0') {
+            /* this should not have happened */
+            return -1;
+        }
 
+        *ptr = '\0';
+        r    = 10000 * atoi(tmps);
+        dprintf("%s():  Converted \"%s\" to r = %d\n", __FUNCTION__, tmps, r);
 
-    /* 
-     * Extract out the major number (versions are strings like 2.1A)
-     * and we want the "2" here.
-     */
-    tmps = g_strdup(str);
-    ptr = tmps;
-    while(*ptr != '\0' && *ptr != '.') { ptr++; }
-    if( *ptr == '\0' ) {
-      /* this should not have happened */
-      return -1;
-    }
+        g_free(tmps);
 
-    *ptr = '\0';
-    r = 10000 * atoi(tmps);
-    dprintf("%s():  Converted \"%s\" to r = %d\n", __FUNCTION__, tmps, r);
+        /*
+         * Extract out the minor number (versions are strings like 2.1A)
+         * and we want the "1" here.
+         */
+        dup  = g_strdup(str);
+        tmps = dup;
+        ptr  = tmps;
 
-    g_free(tmps);
+        while (*ptr != '\0' && *ptr != '.') {
+            ptr++;
+        }
+        if (*ptr == '\0') {
+            /* this should not have happened */
+            return -1;
+        }
+        ptr++;
+        tmps = ptr;
 
-    /* 
-     * Extract out the minor number (versions are strings like 2.1A)
-     * and we want the "1" here.
-     */
-    dup = g_strdup(str);
-    tmps = dup;
-    ptr = tmps;
-
-    while(*ptr != '\0' && *ptr != '.') { ptr++; }
-    if( *ptr == '\0' ) {
-      /* this should not have happened */
-      return -1;
-    }
-    ptr++;
-    tmps = ptr;
+        while (*ptr != '\0' && isdigit((int)*ptr)) {
+            ptr++;
+        }
+        if (*ptr == '\0') {
+            /* this should not have happened */
+            return -1;
+        }
 
-    while(*ptr != '\0' && isdigit( (int) *ptr)) { ptr++; }
-    if( *ptr == '\0' ) {
-      /* this should not have happened */
-      return -1;
-    }
+        *ptr = '\0';
+        r += 100 * atoi(tmps);
+        dprintf("%s():  Converted \"%s\" to r = %d\n", __FUNCTION__, tmps, r);
 
-    *ptr = '\0';
-    r += 100 * atoi(tmps);
-    dprintf("%s():  Converted \"%s\" to r = %d\n", __FUNCTION__, tmps, r);
+        g_free(dup);
 
-    g_free(dup);
+        /*
+         * Extract out the revision letter(s) (versions are strings like 2.1A)
+         * and we want the "A" here.
+         */
 
-    /* 
-     * Extract out the revision letter(s) (versions are strings like 2.1A)
-     * and we want the "A" here.
-     */
+        dup  = g_strdup(str);
+        tmps = dup;
+        ptr  = tmps;
 
-    dup = g_strdup(str);
-    tmps = dup;
-    ptr = tmps;
+        while (*ptr != '\0' && (isdigit((int)*ptr) || *ptr == '.')) {
+            ptr++;
+        }
+        if (*ptr == '\0') {
+            /* this should not have happened */
+            return -1;
+        }
+        tmps = ptr;
+
+        dprintf("%s():  Processing \"%s\"\n", __FUNCTION__, tmps);
+
+        if (strlen(tmps) == 1) {
+            r += *tmps - 'A' + 1;
+            dprintf("%s():  Converted \"%s\" to r = %d\n", __FUNCTION__, tmps, r);
+        } else if (strlen(tmps) == 2) {
+            if (*tmps == 'Z') {
+                r += 26;
+                tmps++;
+                r += *tmps - 'A' + 1;
+            } else {
+                /* this should not have happened */
+                return -1;
+            }
+        } else {
+            /* this should not have happened */
+            return -1;
+        }
 
-    while(*ptr != '\0' && (isdigit( (int) *ptr) || *ptr == '.') ) { ptr++; }
-    if( *ptr == '\0' ) {
-      /* this should not have happened */
-      return -1;
-    }
-    tmps = ptr;
-
-    dprintf("%s():  Processing \"%s\"\n", __FUNCTION__, tmps);
-
-    if( strlen(tmps) == 1) {
-      r += *tmps - 'A' + 1;
-      dprintf( "%s():  Converted \"%s\" to r = %d\n", __FUNCTION__, tmps, r);
-    } else if( strlen(tmps) == 2 ) {
-      if( *tmps == 'Z' ) {
-	r += 26;
-	tmps++;
-	r += *tmps - 'A' + 1;
-      } else {
-	/* this should not have happened */
-	return -1;
-      }
-    } else {
-      /* this should not have happened */
-      return -1;
+        g_free(dup);
     }
-      
-    g_free(dup);
-
-  }
-  return r;
-
+    return r;
 }
 
-/* 
+/*
  * convert the internal int we use for version numbers
  * to the string that users can deal with
  */
-static char *
-version_int_to_str( int ver )
-{
-  int major, minor, teeny;
-  char l[3];
-  char *str;
-
-  l[0] = '\0';
-  l[1] = '\0';
-  l[2] = '\0';
-
-  major = ver / 10000;
-  minor = (ver - 10000*major) / 100;
-  teeny = (ver - 10000*major - 100*minor);
-  if(teeny >= 1 && teeny <= 26) {
-    l[0] = 'A' + teeny - 1;
-  }  else if(teeny > 26 && teeny <= 52) {
-    l[0] = 'Z';
-    l[1] = 'A' + teeny - 26 - 1;
-  }
+static char*
+version_int_to_str(int ver) {
+    int   major, minor, teeny;
+    char  l[3];
+    char* str;
+
+    l[0] = '\0';
+    l[1] = '\0';
+    l[2] = '\0';
+
+    major = ver / 10000;
+    minor = (ver - 10000 * major) / 100;
+    teeny = (ver - 10000 * major - 100 * minor);
+    if (teeny >= 1 && teeny <= 26) {
+        l[0] = 'A' + teeny - 1;
+    } else if (teeny > 26 && teeny <= 52) {
+        l[0] = 'Z';
+        l[1] = 'A' + teeny - 26 - 1;
+    }
 
-  str = g_strdup_printf("%d.%d%s", major, minor, l);
-  return str;
+    str = g_strdup_printf("%d.%d%s", major, minor, l);
+    return str;
 }
 
 static int
-check_vector_and_length(scheme *sc, pointer value,
-		unsigned int length, const char *item)
-{
+check_vector_and_length(scheme* sc, pointer value, unsigned int length, const char* item) {
     if (!sc->vptr->is_vector(value)) {
-	GERB_MESSAGE(_("'%s' parameter not a vector"), item);
+        GERB_MESSAGE(_("'%s' parameter not a vector"), item);
 
-	return 1;
+        return 1;
     }
 
     if (sc->vptr->vector_length(value) != length) {
-	GERB_MESSAGE(_("'%s' vector of incorrect length"), item);
+        GERB_MESSAGE(_("'%s' vector of incorrect length"), item);
 
-	return 2;
+        return 2;
     }
 
     return 0;
 }
 
 static void
-get_color(scheme *sc, pointer value, int *color)
-{
-    int i;
+get_color(scheme* sc, pointer value, int* color) {
+    int     i;
     pointer elem;
 
     if (check_vector_and_length(sc, value, 3, "color"))
-	    return;
-    
+        return;
+
     for (i = 0; i < 3; i++) {
-	elem = sc->vptr->vector_elem(value, i);
-	if (sc->vptr->is_integer(elem) && sc->vptr->is_number(elem))
-	    color[i] = sc->vptr->ivalue(elem);
-	else { 
-	    color[i] = -1;
-	    GERB_MESSAGE(_("Illegal color in projectfile"));
-	}
+        elem = sc->vptr->vector_elem(value, i);
+        if (sc->vptr->is_integer(elem) && sc->vptr->is_number(elem))
+            color[i] = sc->vptr->ivalue(elem);
+        else {
+            color[i] = -1;
+            GERB_MESSAGE(_("Illegal color in projectfile"));
+        }
     }
-    
+
     return;
 } /* get_color */
 
 static void
-get_alpha(scheme *sc, pointer value, int *alpha)
-{
+get_alpha(scheme* sc, pointer value, int* alpha) {
     pointer elem;
 
     if (check_vector_and_length(sc, value, 1, "alpha"))
-	return;
+        return;
 
     elem = sc->vptr->vector_elem(value, 0);
     if (sc->vptr->is_integer(elem) && sc->vptr->is_number(elem)) {
@@ -307,75 +301,70 @@ get_alpha(scheme *sc, pointer value, int *alpha)
 } /* get_alpha */
 
 static void
-get_double(scheme *sc, pointer value, char *item, double *x, double def)
-{
+get_double(scheme* sc, pointer value, char* item, double* x, double def) {
     pointer elem;
 
     if (check_vector_and_length(sc, value, 1, item))
-	return;
+        return;
 
     elem = sc->vptr->vector_elem(value, 0);
     if (sc->vptr->is_real(elem) && sc->vptr->is_number(elem)) {
-	*x = sc->vptr->rvalue(elem);
+        *x = sc->vptr->rvalue(elem);
     } else {
-	*x = def;
-	GERB_MESSAGE(_("Illegal %s in projectfile"), item);
+        *x = def;
+        GERB_MESSAGE(_("Illegal %s in projectfile"), item);
     }
 } /* get_double */
 
 static void
-get_double_pair(scheme *sc, pointer value, char *item,
-	double *x, double *y, double def)
-{
+get_double_pair(scheme* sc, pointer value, char* item, double* x, double* y, double def) {
     pointer elem;
 
     if (check_vector_and_length(sc, value, 2, item))
-	return;
+        return;
 
     elem = sc->vptr->vector_elem(value, 0);
     if (sc->vptr->is_real(elem) && sc->vptr->is_number(elem)) {
-	*x = sc->vptr->rvalue(elem);
+        *x = sc->vptr->rvalue(elem);
     } else {
-	*x = def;
-	GERB_MESSAGE(_("Illegal %s in projectfile"), item);
+        *x = def;
+        GERB_MESSAGE(_("Illegal %s in projectfile"), item);
     }
 
     elem = sc->vptr->vector_elem(value, 1);
     if (sc->vptr->is_real(elem) && sc->vptr->is_number(elem)) {
-	*y = sc->vptr->rvalue(elem);
+        *y = sc->vptr->rvalue(elem);
     } else {
-	*y = def;
-	GERB_MESSAGE(_("Illegal %s in projectfile"), item);
+        *y = def;
+        GERB_MESSAGE(_("Illegal %s in projectfile"), item);
     }
 } /* get_double_pair */
 
 static void
-get_bool_pair(scheme *sc, pointer value, char *item,
-		char *x, char *y, char def)
-{
+get_bool_pair(scheme* sc, pointer value, char* item, char* x, char* y, char def) {
     pointer elem;
 
     if (check_vector_and_length(sc, value, 2, item))
-	return;
+        return;
 
     elem = sc->vptr->vector_elem(value, 0);
     if (elem == sc->F) {
-	*x = 0;
+        *x = 0;
     } else if (elem == sc->T) {
-	*x = 1;
+        *x = 1;
     } else {
-	*x = def;
-	GERB_MESSAGE(_("Illegal %s in projectfile"), item);
+        *x = def;
+        GERB_MESSAGE(_("Illegal %s in projectfile"), item);
     }
 
     elem = sc->vptr->vector_elem(value, 1);
     if (elem == sc->F) {
-	*y = 0;
+        *y = 0;
     } else if (elem == sc->T) {
-	*y = 1;
+        *y = 1;
     } else {
-	*y = def;
-	GERB_MESSAGE(_("Illegal %s in projectfile"), item);
+        *y = def;
+        GERB_MESSAGE(_("Illegal %s in projectfile"), item);
     }
 } /* get_bool_pair */
 
@@ -384,10 +373,10 @@ get_bool_pair(scheme *sc, pointer value, char *item,
  * and fix up the defaults for various paths.  This is largely
  * taken from InitPaths() in main.c from pcb.
  */
-static char *bindir = NULL;
-static char *exec_prefix = NULL;
-static char *pkgdatadir = NULL;
-static gchar *scmdatadir = NULL;
+static char*  bindir      = NULL;
+static char*  exec_prefix = NULL;
+static char*  pkgdatadir  = NULL;
+static gchar* scmdatadir  = NULL;
 
 /* this really should not be needed but it could
  * be hooked in to appease malloc debuggers as
@@ -424,208 +413,183 @@ destroy_paths ()
 #endif
 
 static void
-init_paths (char *argv0)
-{
-  size_t l;
-  int haspath;
-  char *t1, *t2;
-  int found_bindir = 0;
+init_paths(char* argv0) {
+    size_t l;
+    int    haspath;
+    char * t1, *t2;
+    int    found_bindir = 0;
+
+    /* Only do this stuff once */
+    if (bindir != NULL)
+        return;
 
-  /* Only do this stuff once */
-  if (bindir != NULL )
-    return;
+    /* see if argv0 has enough of a path to let lrealpath give the
+     * real path.  This should be the case if you invoke gerbv with
+     * something like /usr/local/bin/gerbv or ./gerbv or ./foo/gerbv
+     * but if you just use gerbv and it exists in your path, you'll
+     * just get back gerbv again.
+     */
 
-  /* see if argv0 has enough of a path to let lrealpath give the
-   * real path.  This should be the case if you invoke gerbv with
-   * something like /usr/local/bin/gerbv or ./gerbv or ./foo/gerbv
-   * but if you just use gerbv and it exists in your path, you'll
-   * just get back gerbv again.
-   */
-  
-  haspath = 0;
-  for (unsigned int i = 0; i < strlen (argv0) ; i++)
-    {
-      if (argv0[i] == GERBV_DIR_SEPARATOR_C) 
-        haspath = 1;
+    haspath = 0;
+    for (unsigned int i = 0; i < strlen(argv0); i++) {
+        if (argv0[i] == GERBV_DIR_SEPARATOR_C)
+            haspath = 1;
     }
-  
-  dprintf("%s (%s): haspath = %d\n", __FUNCTION__, argv0, haspath);
-  if (haspath)
-    {
-      bindir = strdup (lrealpath (argv0));
-      found_bindir = 1;
-    }
-  else
-    {
-      char *path, *p, *tmps;
-      struct stat sb;
-      int r;
-      
-      tmps = getenv ("PATH");
-      
-      if (tmps != NULL)
-        {
-          path = strdup (tmps);
-	  
-          /* search through the font path for a font file */
-          for (p = strtok (path, GERBV_PATH_DELIMETER); p && *p;
-               p = strtok (NULL, GERBV_PATH_DELIMETER))
-            {
-	      dprintf ("Looking for %s in %s\n", argv0, p);
-              if ( (tmps = malloc ( (strlen (argv0) + strlen (p) + 2) * sizeof (char))) == NULL )
-                {
-                  fprintf (stderr, "malloc failed in %s()\n", __FUNCTION__);
-                  exit (1);
+
+    dprintf("%s (%s): haspath = %d\n", __FUNCTION__, argv0, haspath);
+    if (haspath) {
+        bindir       = strdup(lrealpath(argv0));
+        found_bindir = 1;
+    } else {
+        char *      path, *p, *tmps;
+        struct stat sb;
+        int         r;
+
+        tmps = getenv("PATH");
+
+        if (tmps != NULL) {
+            path = strdup(tmps);
+
+            /* search through the font path for a font file */
+            for (p = strtok(path, GERBV_PATH_DELIMETER); p && *p; p = strtok(NULL, GERBV_PATH_DELIMETER)) {
+                dprintf("Looking for %s in %s\n", argv0, p);
+                if ((tmps = malloc((strlen(argv0) + strlen(p) + 2) * sizeof(char))) == NULL) {
+                    fprintf(stderr, "malloc failed in %s()\n", __FUNCTION__);
+                    exit(1);
                 }
-              sprintf (tmps, "%s%s%s", p, GERBV_DIR_SEPARATOR_S, argv0);
-              r = stat (tmps, &sb);
-              if (r == 0)
-                {
-		  dprintf ("Found it:  \"%s\"\n", tmps);
-                  bindir = lrealpath (tmps);
-                  found_bindir = 1;
-                  free (tmps);
-                  break;
+                sprintf(tmps, "%s%s%s", p, GERBV_DIR_SEPARATOR_S, argv0);
+                r = stat(tmps, &sb);
+                if (r == 0) {
+                    dprintf("Found it:  \"%s\"\n", tmps);
+                    bindir       = lrealpath(tmps);
+                    found_bindir = 1;
+                    free(tmps);
+                    break;
                 }
-              free (tmps);
+                free(tmps);
             }
-          free (path);
+            free(path);
         }
     }
-  dprintf ("%s():  bindir = \"%s\"\n", __FUNCTION__, bindir);
-  
-
-  if (found_bindir)
-    {
-      /* strip off the executible name leaving only the path */
-      t2 = NULL;
-      t1 = strchr (bindir, GERBV_DIR_SEPARATOR_C);
-      while (t1 != NULL && *t1 != '\0')
-        {
-          t2 = t1;
-          t1 = strchr (t2 + 1, GERBV_DIR_SEPARATOR_C);
+    dprintf("%s():  bindir = \"%s\"\n", __FUNCTION__, bindir);
+
+    if (found_bindir) {
+        /* strip off the executible name leaving only the path */
+        t2 = NULL;
+        t1 = strchr(bindir, GERBV_DIR_SEPARATOR_C);
+        while (t1 != NULL && *t1 != '\0') {
+            t2 = t1;
+            t1 = strchr(t2 + 1, GERBV_DIR_SEPARATOR_C);
         }
-      if (t2 != NULL)
-        *t2 = '\0';
-      dprintf ("After stripping off the executible name, we found\n");
-      dprintf ("bindir = \"%s\"\n", bindir);
-      
-    }
-  else
-    {
-      /* we have failed to find out anything from argv[0] so fall back to the original
-       * install prefix
-       */
-       bindir = strdup (BINDIR);
+        if (t2 != NULL)
+            *t2 = '\0';
+        dprintf("After stripping off the executible name, we found\n");
+        dprintf("bindir = \"%s\"\n", bindir);
+
+    } else {
+        /* we have failed to find out anything from argv[0] so fall back to the original
+         * install prefix
+         */
+        bindir = strdup(BINDIR);
     }
-    
-  /* now find the path to exec_prefix */
-  l = strlen (bindir) + 1 + strlen (BINDIR_TO_EXECPREFIX) + 1;
-  if ( (exec_prefix = (char *) malloc (l * sizeof (char) )) == NULL )
-    {
-      fprintf (stderr, "malloc failed in %s()\n", __FUNCTION__);
-      exit (1);
+
+    /* now find the path to exec_prefix */
+    l = strlen(bindir) + 1 + strlen(BINDIR_TO_EXECPREFIX) + 1;
+    if ((exec_prefix = (char*)malloc(l * sizeof(char))) == NULL) {
+        fprintf(stderr, "malloc failed in %s()\n", __FUNCTION__);
+        exit(1);
     }
-  sprintf (exec_prefix, "%s%s%s", bindir, GERBV_DIR_SEPARATOR_S,
-           BINDIR_TO_EXECPREFIX);
-  
-  /* now find the path to PKGDATADIR */
-  l = strlen (bindir) + 1 + strlen (BINDIR_TO_PKGDATADIR) + 1;
-  if ( (pkgdatadir = (char *) malloc (l * sizeof (char) )) == NULL )
-    {
-      fprintf (stderr, "malloc failed in %s()\n", __FUNCTION__);
-      exit (1);
+    sprintf(exec_prefix, "%s%s%s", bindir, GERBV_DIR_SEPARATOR_S, BINDIR_TO_EXECPREFIX);
+
+    /* now find the path to PKGDATADIR */
+    l = strlen(bindir) + 1 + strlen(BINDIR_TO_PKGDATADIR) + 1;
+    if ((pkgdatadir = (char*)malloc(l * sizeof(char))) == NULL) {
+        fprintf(stderr, "malloc failed in %s()\n", __FUNCTION__);
+        exit(1);
     }
-  sprintf (pkgdatadir, "%s%s%s", bindir, GERBV_DIR_SEPARATOR_S,
-           BINDIR_TO_PKGDATADIR);
-  
-  scmdatadir = g_strdup_printf ("%s%s%s", pkgdatadir, GERBV_DIR_SEPARATOR_S, SCMSUBDIR);
-
-  dprintf ("%s():  bindir      = %s\n", __FUNCTION__, bindir);
-  dprintf ("%s():  exec_prefix = %s\n", __FUNCTION__, exec_prefix);
-  dprintf ("%s():  pkgdatadir  = %s\n", __FUNCTION__, pkgdatadir);
-  dprintf ("%s():  scmdatadir  = %s\n", __FUNCTION__, scmdatadir);
-  
-}
+    sprintf(pkgdatadir, "%s%s%s", bindir, GERBV_DIR_SEPARATOR_S, BINDIR_TO_PKGDATADIR);
 
+    scmdatadir = g_strdup_printf("%s%s%s", pkgdatadir, GERBV_DIR_SEPARATOR_S, SCMSUBDIR);
 
-static char *
-get_value_string(scheme *sc, pointer value)
-{
+    dprintf("%s():  bindir      = %s\n", __FUNCTION__, bindir);
+    dprintf("%s():  exec_prefix = %s\n", __FUNCTION__, exec_prefix);
+    dprintf("%s():  pkgdatadir  = %s\n", __FUNCTION__, pkgdatadir);
+    dprintf("%s():  scmdatadir  = %s\n", __FUNCTION__, scmdatadir);
+}
+
+static char*
+get_value_string(scheme* sc, pointer value) {
     if (!sc->vptr->is_string(value))
-	return NULL;
+        return NULL;
 
     return sc->vptr->string_value(value);
 } /* get_value_string */
 
-
-/** Conversion of '\' into '/' and vice versa for compatibility under WIN32 
+/** Conversion of '\' into '/' and vice versa for compatibility under WIN32
     platforms. */
-static char *
-convert_path_separators(char* path, int conv_flag)
-{
-    if (path == NULL) return NULL;
+static char*
+convert_path_separators(char* path, int conv_flag) {
+    if (path == NULL)
+        return NULL;
 
-#if defined (__MINGW32__)        
-    char     *hit_in_path;
+#if defined(__MINGW32__)
+    char* hit_in_path;
 
     switch (conv_flag) {
-	
-    case MINGW_UNIX:
-        while ((hit_in_path = strchr(path, '\\'))) {
-            *hit_in_path = '/';
-        }
-        break;
-    case UNIX_MINGW:
-	while ((hit_in_path = strchr(path, '/'))) {
-            *hit_in_path = '\\';
-        }
-        break;
-    }    
+
+        case MINGW_UNIX:
+            while ((hit_in_path = strchr(path, '\\'))) {
+                *hit_in_path = '/';
+            }
+            break;
+        case UNIX_MINGW:
+            while ((hit_in_path = strchr(path, '/'))) {
+                *hit_in_path = '\\';
+            }
+            break;
+    }
 #endif
 
     return path;
-}/* convert_path_separators */
-
+} /* convert_path_separators */
 
 static pointer
-define_layer(scheme *sc, pointer args)
-{
-    pointer car_el, cdr_el, name, value;
-    project_list_t *plist;
-    const char *str;
-    int layerno;
+define_layer(scheme* sc, pointer args) {
+    pointer         car_el, cdr_el, name, value;
+    project_list_t* plist;
+    const char*     str;
+    int             layerno;
 
     dprintf("--> entering %s: %s\n", __FILE__, __func__);
 
     if (!sc->vptr->is_pair(args)) {
-	GERB_MESSAGE(_("%s(): too few arguments"), __func__);
+        GERB_MESSAGE(_("%s(): too few arguments"), __func__);
 
-	return sc->F;
+        return sc->F;
     }
 
     car_el = sc->vptr->pair_car(args);
     cdr_el = sc->vptr->pair_cdr(args);
 
     if (!sc->vptr->is_integer(car_el) || !sc->vptr->is_number(car_el)) {
-	GERB_MESSAGE(_("%s(): layer number missing/incorrect"), __func__);
+        GERB_MESSAGE(_("%s(): layer number missing/incorrect"), __func__);
 
-	return sc->F;
+        return sc->F;
     }
 
     layerno = sc->vptr->ivalue(car_el);
     dprintf("    layerno = %d\n", layerno);
-    
+
     car_el = sc->vptr->pair_car(cdr_el);
     cdr_el = sc->vptr->pair_cdr(cdr_el);
-    
-    plist = g_new0(project_list_t, 1);
-    plist->next = project_list_top;
-    project_list_top = plist;
-    plist->layerno = layerno;
-    plist->visible = 1;
-    plist->n_attr = 0;
-    plist->attr_list = NULL;
+
+    plist              = g_new0(project_list_t, 1);
+    plist->next        = project_list_top;
+    project_list_top   = plist;
+    plist->layerno     = layerno;
+    plist->visible     = 1;
+    plist->n_attr      = 0;
+    plist->attr_list   = NULL;
     plist->translate_x = plist->translate_y = 0.0;
     plist->scale_x = plist->scale_y = 1.0;
     plist->mirror_x = plist->mirror_y = 0;
@@ -634,254 +598,242 @@ define_layer(scheme *sc, pointer args)
     plist->alpha = alpha_def_value;
 
     while (sc->vptr->is_pair(car_el)) {
-	
-	name = sc->vptr->pair_car(car_el);
-	value =  sc->vptr->pair_cdr(car_el);
-	
-	if (!sc->vptr->is_symbol(name)) {
-	    GERB_MESSAGE(_("%s(): non-symbol found, ignoring"), __func__);
-	    goto end_name_value_parse;
-	}
-
-	str = sc->vptr->symname(name);
-	if (strcmp(str, "color") == 0) {
-	    get_color(sc, value, plist->rgb);
-	} else if (strcmp(str, "alpha") == 0) {
-	    get_alpha(sc, value, &plist->alpha);
-	} else if (strcmp(str, "translate") == 0) {
-	    get_double_pair(sc, value, "translate",
-		    &plist->translate_x, &plist->translate_y, 0.0);
-	} else if (strcmp(str, "rotation") == 0) {
-	    get_double(sc, value, "rotation", &plist->rotation, 0.0);
-	} else if (strcmp(str, "scale") == 0) {
-	    get_double_pair(sc, value, "scale",
-		    &plist->scale_x, &plist->scale_y, 1.0);
-	} else if (strcmp(str, "mirror") == 0) {
-	    get_bool_pair(sc, value, "mirror",
-		    &plist->mirror_x, &plist->mirror_y, 0);
-	} else if (strcmp(str, "filename") == 0) {
+
+        name  = sc->vptr->pair_car(car_el);
+        value = sc->vptr->pair_cdr(car_el);
+
+        if (!sc->vptr->is_symbol(name)) {
+            GERB_MESSAGE(_("%s(): non-symbol found, ignoring"), __func__);
+            goto end_name_value_parse;
+        }
+
+        str = sc->vptr->symname(name);
+        if (strcmp(str, "color") == 0) {
+            get_color(sc, value, plist->rgb);
+        } else if (strcmp(str, "alpha") == 0) {
+            get_alpha(sc, value, &plist->alpha);
+        } else if (strcmp(str, "translate") == 0) {
+            get_double_pair(sc, value, "translate", &plist->translate_x, &plist->translate_y, 0.0);
+        } else if (strcmp(str, "rotation") == 0) {
+            get_double(sc, value, "rotation", &plist->rotation, 0.0);
+        } else if (strcmp(str, "scale") == 0) {
+            get_double_pair(sc, value, "scale", &plist->scale_x, &plist->scale_y, 1.0);
+        } else if (strcmp(str, "mirror") == 0) {
+            get_bool_pair(sc, value, "mirror", &plist->mirror_x, &plist->mirror_y, 0);
+        } else if (strcmp(str, "filename") == 0) {
+            plist->filename = g_strdup(get_value_string(sc, value));
+            plist->filename = convert_path_separators(plist->filename, UNIX_MINGW);
+            plist->is_pnp   = 0;
+        } else if (strcmp(str, "pick_and_place") == 0) {
             plist->filename = g_strdup(get_value_string(sc, value));
-	    plist->filename = convert_path_separators(plist->filename,
-			    UNIX_MINGW);
-            plist->is_pnp = 0;
-	} else if (strcmp(str, "pick_and_place") == 0) {
-	    plist->filename = g_strdup(get_value_string(sc, value));
-	    plist->filename = convert_path_separators(plist->filename,
-			    UNIX_MINGW);
-	    plist->is_pnp = 1;
-	} else if (strcmp(str, "inverted") == 0) {
-	    if (value == sc->F) {
-		plist->inverted = 0;
-	    } else if (value == sc->T) {
-		plist->inverted = 1;
-	    } else {
-		GERB_MESSAGE(_("Argument to inverted must be #t or #f"));
-	    }
-	} else if (strcmp(str, "visible") == 0) {
-	    if (value == sc->F) {
-		plist->visible = 0;
-	    } else if (value == sc->T) {
-		plist->visible = 1;
-	    } else {
-		GERB_MESSAGE(_("Argument to visible must be #t or #f"));
-	    }
-       	} else if (strcmp(str, "attribs") == 0) {
-	    pointer attr_car_el, attr_cdr_el;
-	    pointer attr_name, attr_type, attr_value;
-	    char *type;
-
-	    dprintf ("Parsing file attributes\n");
-
-	    attr_car_el = sc->vptr->pair_car (value);
-	    attr_cdr_el = sc->vptr->pair_cdr (value);
-	    while (sc->vptr->is_pair(attr_car_el)) {
-		int p = plist->n_attr;
-		plist->n_attr++;
-		plist->attr_list = (gerbv_HID_Attribute *)
-		    realloc (plist->attr_list,
-			     plist->n_attr * sizeof (gerbv_HID_Attribute));
-		if (plist->attr_list == NULL ) {
-		    fprintf (stderr, _("%s():  realloc failed\n"), __FUNCTION__);
-		    exit (1);
-		}								  
-
-		/* car */
-		attr_name = sc->vptr->pair_car(attr_car_el);
-
-		/* cadr */
-		attr_type =  sc->vptr->pair_cdr (attr_car_el);
-		attr_type =  sc->vptr->pair_car (attr_type);
-
-		/* caddr */
-		attr_value =  sc->vptr->pair_cdr (attr_car_el);
-		attr_value =  sc->vptr->pair_cdr (attr_value);
-		attr_value =  sc->vptr->pair_car (attr_value);
-
-		dprintf ("  attribute %s, type is %s, value is ", 
-			 sc->vptr->symname(attr_name),
-			 sc->vptr->symname(attr_type));
-
-		plist->attr_list[p].name = strdup (sc->vptr->symname (attr_name));
-
-		type = sc->vptr->symname (attr_type);
-
-		plist->attr_list[p].default_val.str_value = NULL;
-		if (strcmp (type, "label") == 0) {
-		    dprintf ("%s", sc->vptr->string_value (attr_value));
-		    plist->attr_list[p].type = HID_Label;
-		    plist->attr_list[p].default_val.str_value =
-			strdup (sc->vptr->string_value (attr_value));
-
-		} else if (strcmp (type, "integer") == 0) {
-		    dprintf ("%ld", sc->vptr->ivalue (attr_value));
-		    plist->attr_list[p].type = HID_Integer;
-		    plist->attr_list[p].default_val.int_value =
-			sc->vptr->ivalue (attr_value);
-
-		} else if (strcmp (type, "real") == 0) {
-		    dprintf ("%g", sc->vptr->rvalue (attr_value));
-		    plist->attr_list[p].type = HID_Real;
-		    plist->attr_list[p].default_val.real_value =
-			sc->vptr->rvalue (attr_value);
-
-		} else if (strcmp (type, "string") == 0) {
-		    dprintf ("%s", sc->vptr->string_value (attr_value));
-		    plist->attr_list[p].type = HID_String;
-		    plist->attr_list[p].default_val.str_value =
-			strdup (sc->vptr->string_value (attr_value));
-
-		} else if (strcmp (type, "boolean") == 0) {
-		    dprintf ("%ld", sc->vptr->ivalue (attr_value));
-		    plist->attr_list[p].type = HID_Boolean;
-		    plist->attr_list[p].default_val.int_value =
-			sc->vptr->ivalue (attr_value);
-
-		} else if (strcmp (type, "enum") == 0) {
-		    dprintf ("%ld", sc->vptr->ivalue (attr_value));
-		    plist->attr_list[p].type = HID_Enum;
-		    plist->attr_list[p].default_val.int_value =
-			sc->vptr->ivalue (attr_value);
-
-		} else if (strcmp (type, "mixed") == 0) {
-		    plist->attr_list[p].type = HID_Mixed;
-		    plist->attr_list[p].default_val.str_value = NULL;
-		    fprintf (stderr, _("%s():  WARNING:  HID_Mixed is not yet supported\n"),
-			     __FUNCTION__);
-
-		} else if (strcmp (type, "path") == 0) {
-		    dprintf ("%s", sc->vptr->string_value (attr_value));
-		    plist->attr_list[p].type = HID_Path;
-		    plist->attr_list[p].default_val.str_value =
-			strdup (sc->vptr->string_value (attr_value));
-		} else {
-		    fprintf (stderr, _("%s():  Unknown attribute type: \"%s\"\n"),
-			     __FUNCTION__, type);
-		}
-		dprintf ("\n");
-
-		attr_car_el = sc->vptr->pair_car(attr_cdr_el);
-		attr_cdr_el = sc->vptr->pair_cdr(attr_cdr_el);
-	    }
-	} else {
+            plist->filename = convert_path_separators(plist->filename, UNIX_MINGW);
+            plist->is_pnp   = 1;
+        } else if (strcmp(str, "inverted") == 0) {
+            if (value == sc->F) {
+                plist->inverted = 0;
+            } else if (value == sc->T) {
+                plist->inverted = 1;
+            } else {
+                GERB_MESSAGE(_("Argument to inverted must be #t or #f"));
+            }
+        } else if (strcmp(str, "visible") == 0) {
+            if (value == sc->F) {
+                plist->visible = 0;
+            } else if (value == sc->T) {
+                plist->visible = 1;
+            } else {
+                GERB_MESSAGE(_("Argument to visible must be #t or #f"));
+            }
+        } else if (strcmp(str, "attribs") == 0) {
+            pointer attr_car_el, attr_cdr_el;
+            pointer attr_name, attr_type, attr_value;
+            char*   type;
+
+            dprintf("Parsing file attributes\n");
+
+            attr_car_el = sc->vptr->pair_car(value);
+            attr_cdr_el = sc->vptr->pair_cdr(value);
+            while (sc->vptr->is_pair(attr_car_el)) {
+                int p = plist->n_attr;
+                plist->n_attr++;
+                plist->attr_list =
+                    (gerbv_HID_Attribute*)realloc(plist->attr_list, plist->n_attr * sizeof(gerbv_HID_Attribute));
+                if (plist->attr_list == NULL) {
+                    fprintf(stderr, _("%s():  realloc failed\n"), __FUNCTION__);
+                    exit(1);
+                }
+
+                /* car */
+                attr_name = sc->vptr->pair_car(attr_car_el);
+
+                /* cadr */
+                attr_type = sc->vptr->pair_cdr(attr_car_el);
+                attr_type = sc->vptr->pair_car(attr_type);
+
+                /* caddr */
+                attr_value = sc->vptr->pair_cdr(attr_car_el);
+                attr_value = sc->vptr->pair_cdr(attr_value);
+                attr_value = sc->vptr->pair_car(attr_value);
+
+                dprintf(
+                    "  attribute %s, type is %s, value is ", sc->vptr->symname(attr_name), sc->vptr->symname(attr_type)
+                );
+
+                plist->attr_list[p].name = strdup(sc->vptr->symname(attr_name));
+
+                type = sc->vptr->symname(attr_type);
+
+                plist->attr_list[p].default_val.str_value = NULL;
+                if (strcmp(type, "label") == 0) {
+                    dprintf("%s", sc->vptr->string_value(attr_value));
+                    plist->attr_list[p].type                  = HID_Label;
+                    plist->attr_list[p].default_val.str_value = strdup(sc->vptr->string_value(attr_value));
+
+                } else if (strcmp(type, "integer") == 0) {
+                    dprintf("%ld", sc->vptr->ivalue(attr_value));
+                    plist->attr_list[p].type                  = HID_Integer;
+                    plist->attr_list[p].default_val.int_value = sc->vptr->ivalue(attr_value);
+
+                } else if (strcmp(type, "real") == 0) {
+                    dprintf("%g", sc->vptr->rvalue(attr_value));
+                    plist->attr_list[p].type                   = HID_Real;
+                    plist->attr_list[p].default_val.real_value = sc->vptr->rvalue(attr_value);
+
+                } else if (strcmp(type, "string") == 0) {
+                    dprintf("%s", sc->vptr->string_value(attr_value));
+                    plist->attr_list[p].type                  = HID_String;
+                    plist->attr_list[p].default_val.str_value = strdup(sc->vptr->string_value(attr_value));
+
+                } else if (strcmp(type, "boolean") == 0) {
+                    dprintf("%ld", sc->vptr->ivalue(attr_value));
+                    plist->attr_list[p].type                  = HID_Boolean;
+                    plist->attr_list[p].default_val.int_value = sc->vptr->ivalue(attr_value);
+
+                } else if (strcmp(type, "enum") == 0) {
+                    dprintf("%ld", sc->vptr->ivalue(attr_value));
+                    plist->attr_list[p].type                  = HID_Enum;
+                    plist->attr_list[p].default_val.int_value = sc->vptr->ivalue(attr_value);
+
+                } else if (strcmp(type, "mixed") == 0) {
+                    plist->attr_list[p].type                  = HID_Mixed;
+                    plist->attr_list[p].default_val.str_value = NULL;
+                    fprintf(stderr, _("%s():  WARNING:  HID_Mixed is not yet supported\n"), __FUNCTION__);
+
+                } else if (strcmp(type, "path") == 0) {
+                    dprintf("%s", sc->vptr->string_value(attr_value));
+                    plist->attr_list[p].type                  = HID_Path;
+                    plist->attr_list[p].default_val.str_value = strdup(sc->vptr->string_value(attr_value));
+                } else {
+                    fprintf(stderr, _("%s():  Unknown attribute type: \"%s\"\n"), __FUNCTION__, type);
+                }
+                dprintf("\n");
+
+                attr_car_el = sc->vptr->pair_car(attr_cdr_el);
+                attr_cdr_el = sc->vptr->pair_cdr(attr_cdr_el);
+            }
+        } else {
             GERB_MESSAGE(_("Ignoring \"%s\" in project file"), str);
-	}
+        }
 
 end_name_value_parse:
-	car_el = sc->vptr->pair_car(cdr_el);
-	cdr_el = sc->vptr->pair_cdr(cdr_el);
+        car_el = sc->vptr->pair_car(cdr_el);
+        cdr_el = sc->vptr->pair_cdr(cdr_el);
     }
 
     return sc->NIL;
 } /* define_layer */
 
 static pointer
-set_render_type(scheme *sc, pointer args)
-{
+set_render_type(scheme* sc, pointer args) {
     pointer car_el;
-    int r;
+    int     r;
 
     dprintf("--> entering project.c:%s()\n", __FUNCTION__);
 
-    if (!sc->vptr->is_pair(args)){
-	GERB_MESSAGE(_("set-render-type!: Too few arguments"));
-	return sc->F;
+    if (!sc->vptr->is_pair(args)) {
+        GERB_MESSAGE(_("set-render-type!: Too few arguments"));
+        return sc->F;
     }
 
     car_el = sc->vptr->pair_car(args);
 
-    r = sc->vptr->ivalue (car_el);
-    dprintf ("%s():  Setting render type to %d\n", __FUNCTION__, r);
-    interface_set_render_type (r);
+    r = sc->vptr->ivalue(car_el);
+    dprintf("%s():  Setting render type to %d\n", __FUNCTION__, r);
+    interface_set_render_type(r);
 
     return sc->NIL;
 } /* set_render_type */
 
 static pointer
-gerbv_file_version(scheme *sc, pointer args)
-{
+gerbv_file_version(scheme* sc, pointer args) {
     pointer car_el;
-    int r;
-    char *vstr;
-    char *tmps;
+    int     r;
+    char*   vstr;
+    char*   tmps;
 
     dprintf("--> entering project.c:%s()\n", __FUNCTION__);
 
-    if (!sc->vptr->is_pair(args)){
-	GERB_MESSAGE(_("gerbv-file-version!: Too few arguments"));
-	return sc->F;
+    if (!sc->vptr->is_pair(args)) {
+        GERB_MESSAGE(_("gerbv-file-version!: Too few arguments"));
+        return sc->F;
     }
 
     car_el = sc->vptr->pair_car(args);
-    vstr = get_value_string(sc, car_el);
-    
+    vstr   = get_value_string(sc, car_el);
+
     /* find our internal integer code */
-    r = version_str_to_int( vstr );
-
-    if( r == -1) {
-      r = version_str_to_int( GERBV_DEFAULT_PROJECT_FILE_VERSION );
-      GERB_MESSAGE(_("The project file you are attempting to load has specified that it\n"
-		   "uses project file version \"%s\" but this string is not\n"
-		   "a valid version.  Gerbv will attempt to load the file using\n"
-		   "version \"%s\".  You may experience unexpected results."),
-		   vstr, version_int_to_str( r ));
-      vstr = GERBV_DEFAULT_PROJECT_FILE_VERSION;
+    r = version_str_to_int(vstr);
+
+    if (r == -1) {
+        r = version_str_to_int(GERBV_DEFAULT_PROJECT_FILE_VERSION);
+        GERB_MESSAGE(
+            _("The project file you are attempting to load has specified that it\n"
+              "uses project file version \"%s\" but this string is not\n"
+              "a valid version.  Gerbv will attempt to load the file using\n"
+              "version \"%s\".  You may experience unexpected results."),
+            vstr, version_int_to_str(r)
+        );
+        vstr = GERBV_DEFAULT_PROJECT_FILE_VERSION;
     }
-    if( DEBUG ) {
-      tmps = version_int_to_str( r );
-      printf (_("%s():  Read a project file version of %s (%d)\n"), __FUNCTION__, vstr, r);
-      printf (_("      Translated back to \"%s\"\n"), tmps);
-      g_free (tmps);
+    if (DEBUG) {
+        tmps = version_int_to_str(r);
+        printf(_("%s():  Read a project file version of %s (%d)\n"), __FUNCTION__, vstr, r);
+        printf(_("      Translated back to \"%s\"\n"), tmps);
+        g_free(tmps);
     }
 
-    dprintf ("%s():  Read a project file version of %s (%d)\n", __FUNCTION__, vstr, r);
+    dprintf("%s():  Read a project file version of %s (%d)\n", __FUNCTION__, vstr, r);
 
-    if ( r > version_str_to_int( GERBV_PROJECT_FILE_VERSION )) {
+    if (r > version_str_to_int(GERBV_PROJECT_FILE_VERSION)) {
         /* The project file we're trying to load is too new for this version of gerbv */
-	GERB_MESSAGE(_("The project file you are attempting to load is version \"%s\"\n"
-	    "but this copy of gerbv is only capable of loading project files\n"
-	    "using version \"%s\" or older.  You may experience unexpected results."),
-		     vstr, GERBV_PROJECT_FILE_VERSION);
+        GERB_MESSAGE(
+            _("The project file you are attempting to load is version \"%s\"\n"
+              "but this copy of gerbv is only capable of loading project files\n"
+              "using version \"%s\" or older.  You may experience unexpected results."),
+            vstr, GERBV_PROJECT_FILE_VERSION
+        );
     } else {
-      int i = 0;
-      int vok = 0;
-
-      while( known_versions[i] != NULL ) {
-	if( strcmp( known_versions[i], vstr) == 0 ) {
-	  vok = 1;
-	}
-	i++;
-      }
-
-      if( ! vok ) {
-	/* The project file we're trying to load is not too new
-	 * but it is unknown to us
-	 */
-	GERB_MESSAGE(_("The project file you are attempting to load is version \"%s\"\n"
-		     "which is an unknown version.\n"
-		     "You may experience unexpected results."),
-		     vstr);
-	
-      }
+        int i   = 0;
+        int vok = 0;
+
+        while (known_versions[i] != NULL) {
+            if (strcmp(known_versions[i], vstr) == 0) {
+                vok = 1;
+            }
+            i++;
+        }
+
+        if (!vok) {
+            /* The project file we're trying to load is not too new
+             * but it is unknown to us
+             */
+            GERB_MESSAGE(
+                _("The project file you are attempting to load is version \"%s\"\n"
+                  "which is an unknown version.\n"
+                  "You may experience unexpected results."),
+                vstr
+            );
+        }
     }
 
     /*
@@ -898,51 +850,51 @@ gerbv_file_version(scheme *sc, pointer args)
  * reading the first line and checking if it contains gerbv-file-version
  *
  * Returns 0 on success -1 on open error
-  */
+ */
 int
-project_is_gerbv_project(const char *filename, gboolean *ret)
-{
-	FILE *fd;
-	*ret = FALSE;
-	char *buf;
-	const gsize buf_size = 200;
-
-	fd = fopen(filename, "rb");
-	if (fd == NULL) {
-		GERB_MESSAGE(_("Failed to open \"%s\" for reading: %s"),
-				filename, strerror(errno));
-		return -1;
-	}
-
-	buf = (char *) g_malloc(buf_size);
-	if (buf == NULL)
-		GERB_FATAL_ERROR("malloc buf failed while checking for "
-				"Gerbv project in %s()", __FUNCTION__);
-
-	if (fgets(buf, buf_size, fd) != NULL)
-		*ret = (g_strrstr(buf, "gerbv-file-version") != NULL);
-
-	fclose(fd);
-	g_free(buf);
-
-	return 0;
+project_is_gerbv_project(const char* filename, gboolean* ret) {
+    FILE* fd;
+    *ret = FALSE;
+    char*       buf;
+    const gsize buf_size = 200;
+
+    fd = fopen(filename, "rb");
+    if (fd == NULL) {
+        GERB_MESSAGE(_("Failed to open \"%s\" for reading: %s"), filename, strerror(errno));
+        return -1;
+    }
+
+    buf = (char*)g_malloc(buf_size);
+    if (buf == NULL)
+        GERB_FATAL_ERROR(
+            "malloc buf failed while checking for "
+            "Gerbv project in %s()",
+            __FUNCTION__
+        );
+
+    if (fgets(buf, buf_size, fd) != NULL)
+        *ret = (g_strrstr(buf, "gerbv-file-version") != NULL);
+
+    fclose(fd);
+    g_free(buf);
+
+    return 0;
 }
 
 /** Reads the content of a project file.
-  *  Global:\n
-  *    Background color,\n
-  *    global path,\n
-  *    corresponding pick and place file: labelled 'picknplace'\n
-  *   Per layer:\n
-  *    layer color,\n
-  *    layer filename
-  */
-project_list_t *
-read_project_file(char const* filename)
-{
+ *  Global:\n
+ *    Background color,\n
+ *    global path,\n
+ *    corresponding pick and place file: labelled 'picknplace'\n
+ *   Per layer:\n
+ *    layer color,\n
+ *    layer filename
+ */
+project_list_t*
+read_project_file(const char* filename) {
     struct stat stat_info;
-    scheme *sc;
-    FILE *fd;
+    scheme*     sc;
+    FILE*       fd;
     /* always let the environment variable win so one can force
      * a particular init.scm.  Then we use the default installed
      * directory based on where the binary has been installed to
@@ -950,11 +902,8 @@ read_project_file(char const* filename)
      * default compiled in directory.  After that try the directory
      * where the binary lives and finally the current directory.
      */
-    char *initdirs[] = {"$GERBV_SCHEMEINIT","", BACKEND_DIR, 
-                        mainProject->execpath, ".", 
-			NULL};
-    char *initfile;
-
+    char* initdirs[] = { "$GERBV_SCHEMEINIT", "", BACKEND_DIR, mainProject->execpath, ".", NULL };
+    char* initfile;
 
     /*
      * Figure out some directories so we can find init.scm
@@ -962,53 +911,51 @@ read_project_file(char const* filename)
     init_paths(mainProject->execname);
     initdirs[1] = scmdatadir;
 
-#if defined(DEBUG) 
-    if (DEBUG > 0)
-      {
-	int i=0;
-	
-	while(initdirs[i] != NULL) {
-	  printf("%s():  initdirs[%d] = \"%s\"\n", __FUNCTION__, i, initdirs[i]);
-	  i++;
-	}
-      }
-#endif 
+#if defined(DEBUG)
+    if (DEBUG > 0) {
+        int i = 0;
+
+        while (initdirs[i] != NULL) {
+            printf("%s():  initdirs[%d] = \"%s\"\n", __FUNCTION__, i, initdirs[i]);
+            i++;
+        }
+    }
+#endif
 
     /*
      * set the current version of the project file to 1 day before we started adding
      * versioning to the files.  While the file is being loaded, this will
      * be set to the correct version on newer files and ignored on older files
      */
-    current_file_version =
-		version_str_to_int(GERBV_DEFAULT_PROJECT_FILE_VERSION);
+    current_file_version = version_str_to_int(GERBV_DEFAULT_PROJECT_FILE_VERSION);
 
     if (stat(filename, &stat_info) || !S_ISREG(stat_info.st_mode)) {
-	GERB_MESSAGE(_("Failed to read %s"), filename);
+        GERB_MESSAGE(_("Failed to read %s"), filename);
 
-	return NULL;
+        return NULL;
     }
 
     sc = scheme_init_new();
     scheme_set_output_port_file(sc, stdout);
 
-    if(!sc){
-	GERB_FATAL_ERROR(_("Couldn't init scheme"));
-	exit(1);
+    if (!sc) {
+        GERB_FATAL_ERROR(_("Couldn't init scheme"));
+        exit(1);
     }
 
-    errno = 0;
+    errno    = 0;
     initfile = gerb_find_file("init.scm", initdirs);
     if (initfile == NULL) {
-	scheme_deinit(sc);
-	GERB_MESSAGE(_("Problem loading init.scm (%s)"), strerror(errno));
-	return NULL;
+        scheme_deinit(sc);
+        GERB_MESSAGE(_("Problem loading init.scm (%s)"), strerror(errno));
+        return NULL;
     }
     dprintf("%s():  initfile = \"%s\"\n", __FUNCTION__, initfile);
 
     if ((fd = fopen(initfile, "r")) == NULL) {
-	scheme_deinit(sc);
-	GERB_MESSAGE(_("Couldn't open %s (%s)"), initfile, strerror(errno));
-	return NULL;
+        scheme_deinit(sc);
+        GERB_MESSAGE(_("Couldn't open %s (%s)"), initfile, strerror(errno));
+        return NULL;
     }
 
     /* Force gerbv to input decimals as dots */
@@ -1017,25 +964,25 @@ read_project_file(char const* filename)
     sc->vptr->load_file(sc, fd);
     fclose(fd);
 
-    sc->vptr->scheme_define(sc, sc->global_env, 
-			    sc->vptr->mk_symbol(sc, "define-layer!"),
-			    sc->vptr->mk_foreign_func(sc, define_layer));
+    sc->vptr->scheme_define(
+        sc, sc->global_env, sc->vptr->mk_symbol(sc, "define-layer!"), sc->vptr->mk_foreign_func(sc, define_layer)
+    );
 
-    sc->vptr->scheme_define(sc, sc->global_env, 
-			    sc->vptr->mk_symbol(sc, "set-render-type!"),
-			    sc->vptr->mk_foreign_func(sc, set_render_type));
+    sc->vptr->scheme_define(
+        sc, sc->global_env, sc->vptr->mk_symbol(sc, "set-render-type!"), sc->vptr->mk_foreign_func(sc, set_render_type)
+    );
 
-    sc->vptr->scheme_define(sc, sc->global_env, 
-			    sc->vptr->mk_symbol(sc, "gerbv-file-version!"),
-			    sc->vptr->mk_foreign_func(sc, gerbv_file_version));
+    sc->vptr->scheme_define(
+        sc, sc->global_env, sc->vptr->mk_symbol(sc, "gerbv-file-version!"),
+        sc->vptr->mk_foreign_func(sc, gerbv_file_version)
+    );
 
     if ((fd = fopen(filename, "r")) == NULL) {
-	setlocale(LC_NUMERIC, "");	/* Default locale */
-	scheme_deinit(sc);
-	GERB_MESSAGE(_("Couldn't open project file %s (%s)"), filename,
-		     strerror(errno));
+        setlocale(LC_NUMERIC, ""); /* Default locale */
+        scheme_deinit(sc);
+        GERB_MESSAGE(_("Couldn't open project file %s (%s)"), filename, strerror(errno));
 
-	return NULL;
+        return NULL;
     }
 
     project_list_top = NULL;
@@ -1043,44 +990,42 @@ read_project_file(char const* filename)
     scheme_load_file(sc, fd);
     fclose(fd);
 
-    setlocale(LC_NUMERIC, "");	/* Default locale */
+    setlocale(LC_NUMERIC, ""); /* Default locale */
     scheme_deinit(sc);
 
     return project_list_top;
 } /* read_project */
 
-
 void
-project_destroy_project_list (project_list_t *projectList){
-	project_list_t *tempP,*tempP2;
-	
-	for (tempP = projectList; tempP != NULL; ){
-		tempP2 = tempP->next;
-		
-		g_free (tempP->filename);
-		gerbv_attribute_destroy_HID_attribute (tempP->attr_list, tempP->n_attr);
-		tempP->attr_list = NULL;
-		tempP = tempP2;
-	}
+project_destroy_project_list(project_list_t* projectList) {
+    project_list_t *tempP, *tempP2;
+
+    for (tempP = projectList; tempP != NULL;) {
+        tempP2 = tempP->next;
+
+        g_free(tempP->filename);
+        gerbv_attribute_destroy_HID_attribute(tempP->attr_list, tempP->n_attr);
+        tempP->attr_list = NULL;
+        tempP            = tempP2;
+    }
 }
 
 /*
- * Writes a description of a project to a file 
+ * Writes a description of a project to a file
  * that can be parsed by read_project above
  */
-int 
-write_project_file(gerbv_project_t *gerbvProject, char const* filename, project_list_t *project)
-{
-    FILE *fd;
-    project_list_t *p = project;
-    int n_attr = 0;
-    gerbv_HID_Attribute *attr_list = NULL;
-    const float min_val = GERBV_PRECISION_LINEAR_INCH;
-    int i;
+int
+write_project_file(gerbv_project_t* gerbvProject, const char* filename, project_list_t* project) {
+    FILE*                fd;
+    project_list_t*      p         = project;
+    int                  n_attr    = 0;
+    gerbv_HID_Attribute* attr_list = NULL;
+    const float          min_val   = GERBV_PRECISION_LINEAR_INCH;
+    int                  i;
 
     if ((fd = fopen(filename, "w")) == NULL) {
-	    GERB_MESSAGE(_("Couldn't save project %s"), filename);
-	    return -1;
+        GERB_MESSAGE(_("Couldn't save project %s"), filename);
+        return -1;
     }
 
     /* Force gerbv to input decimals as dots */
@@ -1089,118 +1034,106 @@ write_project_file(gerbv_project_t *gerbvProject, char const* filename, project_
     fprintf(fd, "(gerbv-file-version! \"%s\")\n", GERBV_PROJECT_FILE_VERSION);
 
     while (p) {
-	fprintf(fd, "(define-layer! %d ", p->layerno);
-	
-	fprintf(fd, "(cons 'filename \"%s\")\n",
-		convert_path_separators(p->filename, MINGW_UNIX));
-    
-	if (p->inverted)
-	    fprintf(fd, "\t(cons 'inverted #t)\n");
-
-	if (p->layerno >= 0) {
-	    fprintf(fd, "\t(cons 'visible #%c)\n", p->visible? 't': 'f');
-	}
-
-	fprintf(fd, "\t(cons 'color #(%d %d %d))\n",
-		p->rgb[0], p->rgb[1], p->rgb[2]);
-
-	if (p->layerno >= 0) {
-	    if (p->alpha != alpha_def_value)
-		fprintf(fd, "\t(cons 'alpha #(%d))\n", p->alpha);
-
-	    /* Check if there is transformation. Write if so. */
-	    if ((fabs(p->translate_x) > min_val)
-		    || (fabs(p->translate_y) > min_val)) {
-		fprintf(fd, "\t(cons 'translate #(%f %f))\n",
-			p->translate_x, p->translate_y);
-	    }
-	    if (fabs(p->rotation) > GERBV_PRECISION_ANGLE_RAD) {
-		fprintf(fd, "\t(cons 'rotation #(%f))\n", p->rotation);
-	    }
-	    if ((fabs(p->scale_x - 1.0) > min_val)
-		    || (fabs(p->scale_y - 1.0) > min_val)) {
-		fprintf(fd, "\t(cons 'scale #(%f %f))\n",
-				p->scale_x, p->scale_y);
-	    }
-	    if (p->mirror_x || p->mirror_y) {
-		fprintf(fd, "\t(cons 'mirror #(#%c #%c))\n",
-			p->mirror_x? 't': 'f', p->mirror_y? 't': 'f');
-	    }
-	}
-	/* now write out the attribute list which specifies the
-	 * file format 
-	 */
-	if (p->layerno < 0) {
-	    attr_list = NULL;
-	    n_attr = 0;
-	} else {
-	    attr_list = gerbvProject->file[p->layerno]->image->info->attr_list;
-	    n_attr =  gerbvProject->file[p->layerno]->image->info->n_attr;
-	}
-
-	if (n_attr > 0) {
-	    fprintf(fd, "\t(cons 'attribs (list\n");
-	}
-	for (i = 0; i < n_attr ; i++) {
-	    switch (attr_list[i].type) {
-	    case HID_Label:
-		  fprintf(fd, "\t\t(list '%s 'Label \"%s\")\n", attr_list[i].name,
-			  attr_list[i].default_val.str_value);
-		  break;
-		  
-	      case HID_Integer:
-		  fprintf(fd, "\t\t(list '%s 'Integer %d)\n", attr_list[i].name,
-			  attr_list[i].default_val.int_value);
-		  break;
-		  
-	      case HID_Real:
-		  fprintf(fd, "\t\t(list '%s 'Real %g)\n", attr_list[i].name,
-			  attr_list[i].default_val.real_value);
-		  break;
-		  
-	      case HID_String:
-		  fprintf(fd, "\t\t(list '%s 'String \"%s\")\n", attr_list[i].name,
-			  attr_list[i].default_val.str_value);
-		  break;
-		  
-	      case HID_Boolean:
-		  fprintf(fd, "\t\t(list '%s 'Boolean %d)\n", attr_list[i].name,
-			  attr_list[i].default_val.int_value);
-		  break;
-		  
-	      case HID_Enum:
-		  fprintf(fd, "\t\t(list '%s 'Enum %d)\n", attr_list[i].name,
-			  attr_list[i].default_val.int_value);
-		  break;
-
-	      case HID_Mixed:
-		  dprintf ("HID_Mixed\n");
-		  fprintf (stderr, _("%s():  WARNING:  HID_Mixed is not yet supported.\n"),
-			   __FUNCTION__);
-		  break;
-
-	      case HID_Path:
-		  fprintf(fd, "\t\t(list '%s 'Path \"%s\")\n", attr_list[i].name,
-			  attr_list[i].default_val.str_value);
-		  break;
-
-	      default:
-		  fprintf (stderr, _("%s: unknown type of HID attribute (%d)\n"),
-			   __FUNCTION__, attr_list[i].type);
-		  break;
-	      }
-	}
-	if (n_attr > 0) {
-	    fprintf (fd, "\t))\n");
-	}
-
-	fprintf(fd, ")\n");
-	p = p->next;
+        fprintf(fd, "(define-layer! %d ", p->layerno);
+
+        fprintf(fd, "(cons 'filename \"%s\")\n", convert_path_separators(p->filename, MINGW_UNIX));
+
+        if (p->inverted)
+            fprintf(fd, "\t(cons 'inverted #t)\n");
+
+        if (p->layerno >= 0) {
+            fprintf(fd, "\t(cons 'visible #%c)\n", p->visible ? 't' : 'f');
+        }
+
+        fprintf(fd, "\t(cons 'color #(%d %d %d))\n", p->rgb[0], p->rgb[1], p->rgb[2]);
+
+        if (p->layerno >= 0) {
+            if (p->alpha != alpha_def_value)
+                fprintf(fd, "\t(cons 'alpha #(%d))\n", p->alpha);
+
+            /* Check if there is transformation. Write if so. */
+            if ((fabs(p->translate_x) > min_val) || (fabs(p->translate_y) > min_val)) {
+                fprintf(fd, "\t(cons 'translate #(%f %f))\n", p->translate_x, p->translate_y);
+            }
+            if (fabs(p->rotation) > GERBV_PRECISION_ANGLE_RAD) {
+                fprintf(fd, "\t(cons 'rotation #(%f))\n", p->rotation);
+            }
+            if ((fabs(p->scale_x - 1.0) > min_val) || (fabs(p->scale_y - 1.0) > min_val)) {
+                fprintf(fd, "\t(cons 'scale #(%f %f))\n", p->scale_x, p->scale_y);
+            }
+            if (p->mirror_x || p->mirror_y) {
+                fprintf(fd, "\t(cons 'mirror #(#%c #%c))\n", p->mirror_x ? 't' : 'f', p->mirror_y ? 't' : 'f');
+            }
+        }
+        /* now write out the attribute list which specifies the
+         * file format
+         */
+        if (p->layerno < 0) {
+            attr_list = NULL;
+            n_attr    = 0;
+        } else {
+            attr_list = gerbvProject->file[p->layerno]->image->info->attr_list;
+            n_attr    = gerbvProject->file[p->layerno]->image->info->n_attr;
+        }
+
+        if (n_attr > 0) {
+            fprintf(fd, "\t(cons 'attribs (list\n");
+        }
+        for (i = 0; i < n_attr; i++) {
+            switch (attr_list[i].type) {
+                case HID_Label:
+                    fprintf(
+                        fd, "\t\t(list '%s 'Label \"%s\")\n", attr_list[i].name, attr_list[i].default_val.str_value
+                    );
+                    break;
+
+                case HID_Integer:
+                    fprintf(fd, "\t\t(list '%s 'Integer %d)\n", attr_list[i].name, attr_list[i].default_val.int_value);
+                    break;
+
+                case HID_Real:
+                    fprintf(fd, "\t\t(list '%s 'Real %g)\n", attr_list[i].name, attr_list[i].default_val.real_value);
+                    break;
+
+                case HID_String:
+                    fprintf(
+                        fd, "\t\t(list '%s 'String \"%s\")\n", attr_list[i].name, attr_list[i].default_val.str_value
+                    );
+                    break;
+
+                case HID_Boolean:
+                    fprintf(fd, "\t\t(list '%s 'Boolean %d)\n", attr_list[i].name, attr_list[i].default_val.int_value);
+                    break;
+
+                case HID_Enum:
+                    fprintf(fd, "\t\t(list '%s 'Enum %d)\n", attr_list[i].name, attr_list[i].default_val.int_value);
+                    break;
+
+                case HID_Mixed:
+                    dprintf("HID_Mixed\n");
+                    fprintf(stderr, _("%s():  WARNING:  HID_Mixed is not yet supported.\n"), __FUNCTION__);
+                    break;
+
+                case HID_Path:
+                    fprintf(fd, "\t\t(list '%s 'Path \"%s\")\n", attr_list[i].name, attr_list[i].default_val.str_value);
+                    break;
+
+                default:
+                    fprintf(stderr, _("%s: unknown type of HID attribute (%d)\n"), __FUNCTION__, attr_list[i].type);
+                    break;
+            }
+        }
+        if (n_attr > 0) {
+            fprintf(fd, "\t))\n");
+        }
+
+        fprintf(fd, ")\n");
+        p = p->next;
     }
 
-    fprintf (fd, "(set-render-type! %d)\n", screenRenderInfo.renderType);
+    fprintf(fd, "(set-render-type! %d)\n", screenRenderInfo.renderType);
 
-    setlocale(LC_NUMERIC, "");	/* Default locale */
+    setlocale(LC_NUMERIC, ""); /* Default locale */
 
     fclose(fd);
 
diff --git a/src/project.h b/src/project.h
index ebcf36a..ae6a5dd 100644
--- a/src/project.h
+++ b/src/project.h
@@ -21,53 +21,50 @@
  * along with this program; if not, write to the Free Software
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA
  */
- 
+
 /** \file project.h
     \brief Header info for loading and saving project files.
     \ingroup gerbv
- */ 
+ */
 
 #ifndef PROJECT_H
 #define PROJECT_H
 
 typedef struct project_list_t {
-    int layerno;
-    char *filename;
-    int rgb[3];
-    int alpha;
-    char inverted;
-    double translate_x;
-    double translate_y;
-    double rotation;
-    double scale_x;
-    double scale_y;
-    char mirror_x;
-    char mirror_y;
-    char is_pnp;
-    char visible;
-    gerbv_HID_Attribute *attr_list;
-    int n_attr;
-    struct project_list_t *next;
+    int                    layerno;
+    char*                  filename;
+    int                    rgb[3];
+    int                    alpha;
+    char                   inverted;
+    double                 translate_x;
+    double                 translate_y;
+    double                 rotation;
+    double                 scale_x;
+    double                 scale_y;
+    char                   mirror_x;
+    char                   mirror_y;
+    char                   is_pnp;
+    char                   visible;
+    gerbv_HID_Attribute*   attr_list;
+    int                    n_attr;
+    struct project_list_t* next;
 } project_list_t;
 
-
 enum conv_type {
     MINGW_UNIX = 0,
     UNIX_MINGW = 1
 };
 
-int project_is_gerbv_project(const char *filename, gboolean *ret);
+int project_is_gerbv_project(const char* filename, gboolean* ret);
 
 /*
  * Reads a project from a file and returns a linked list describing the project
  */
-project_list_t *read_project_file(char const* filename);
-
+project_list_t* read_project_file(const char* filename);
 
 /* Writes a description of a project to a file
  * that can be parsed by read_project above */
-int write_project_file(gerbv_project_t *gerbvProject, char const* filename, project_list_t *project);
+int write_project_file(gerbv_project_t* gerbvProject, const char* filename, project_list_t* project);
 
-void
-project_destroy_project_list (project_list_t *projectList);
+void project_destroy_project_list(project_list_t* projectList);
 #endif /* PROJECT_H */
diff --git a/src/render.c b/src/render.c
index d90c393..09192a1 100644
--- a/src/render.c
+++ b/src/render.c
@@ -30,19 +30,19 @@
 #include "gerbv.h"
 
 #ifdef HAVE_STDLIB_H
-# include <stdlib.h>
+#include <stdlib.h>
 #endif
 
 #ifdef HAVE_STRING_H
-# include <string.h>
+#include <string.h>
 #endif
 
 #ifdef HAVE_UNISTD_H
-# include <unistd.h>
+#include <unistd.h>
 #endif
 
 #ifdef HAVE_LIBGEN_H
-# include <libgen.h> /* dirname */
+#include <libgen.h> /* dirname */
 #endif
 
 #include <math.h>
@@ -55,648 +55,604 @@
 #include "selection.h"
 
 #ifdef WIN32
-# include <cairo-win32.h>
+#include <cairo-win32.h>
 #elif QUARTZ
-# include <cairo-quartz.h>
+#include <cairo-quartz.h>
 #else
-# include <cairo-xlib.h>
+#include <cairo-xlib.h>
 #endif
 #include "draw.h"
 
-#define dprintf if(DEBUG) printf
+#define dprintf \
+    if (DEBUG)  \
+    printf
 
 gerbv_render_info_t screenRenderInfo;
 
 /* ------------------------------------------------------ */
 void
-render_zoom_display (gint zoomType, gdouble scaleFactor, gdouble mouseX, gdouble mouseY)
-{
-	gdouble mouseCoordinateX = 0.0;
-	gdouble mouseCoordinateY = 0.0;
-	double oldWidth, oldHeight;
-
-	oldWidth = screenRenderInfo.displayWidth / screenRenderInfo.scaleFactorX;
-	oldHeight = screenRenderInfo.displayHeight / screenRenderInfo.scaleFactorY;
-
-	if (zoomType == ZOOM_IN_CMOUSE || zoomType == ZOOM_OUT_CMOUSE) {
-		/* calculate what user coordinate the mouse is pointing at */
-		mouseCoordinateX = mouseX / screenRenderInfo.scaleFactorX + screenRenderInfo.lowerLeftX;
-		mouseCoordinateY = (screenRenderInfo.displayHeight - mouseY) /
-			screenRenderInfo.scaleFactorY + screenRenderInfo.lowerLeftY;
-	}
-
-	switch(zoomType) {
-		case ZOOM_IN : /* Zoom In */
-		case ZOOM_IN_CMOUSE : /* Zoom In Around Mouse Pointer */
-			screenRenderInfo.scaleFactorX = MIN((gdouble)GERBV_SCALE_MAX,
-					(1 + 1/3.0)*screenRenderInfo.scaleFactorX);
-			screenRenderInfo.scaleFactorY = screenRenderInfo.scaleFactorX;
-			screenRenderInfo.lowerLeftX += (oldWidth - (screenRenderInfo.displayWidth /
-						screenRenderInfo.scaleFactorX)) / 2.0;
-			screenRenderInfo.lowerLeftY += (oldHeight - (screenRenderInfo.displayHeight /
-						screenRenderInfo.scaleFactorY)) / 2.0;
-			break;
-		case ZOOM_OUT :  /* Zoom Out */
-		case ZOOM_OUT_CMOUSE : /* Zoom Out Around Mouse Pointer */
-			screenRenderInfo.scaleFactorX = MAX((gdouble)GERBV_SCALE_MIN,
-					(1 - 1/3.0)*screenRenderInfo.scaleFactorX);
-			screenRenderInfo.scaleFactorY = screenRenderInfo.scaleFactorX;
-			screenRenderInfo.lowerLeftX += (oldWidth - (screenRenderInfo.displayWidth /
-						screenRenderInfo.scaleFactorX)) / 2.0;
-			screenRenderInfo.lowerLeftY += (oldHeight - (screenRenderInfo.displayHeight /
-						screenRenderInfo.scaleFactorY)) / 2.0;
-			break;
-		case ZOOM_FIT : /* Zoom Fit */
-			gerbv_render_zoom_to_fit_display (mainProject, &screenRenderInfo);
-			break;
-		case ZOOM_SET : /*explicit scale set by user */
-			screenRenderInfo.scaleFactorX =
-				MIN((gdouble)GERBV_SCALE_MAX, scaleFactor);
-			screenRenderInfo.scaleFactorY = screenRenderInfo.scaleFactorX;
-			screenRenderInfo.lowerLeftX += (oldWidth - (screenRenderInfo.displayWidth /
-						screenRenderInfo.scaleFactorX)) / 2.0;
-			screenRenderInfo.lowerLeftY += (oldHeight - (screenRenderInfo.displayHeight /
-						screenRenderInfo.scaleFactorY)) / 2.0;
-			break;
-		default :
-			GERB_MESSAGE(_("Illegal zoom direction %d"), zoomType);
-	}
-
-	if (zoomType == ZOOM_IN_CMOUSE || zoomType == ZOOM_OUT_CMOUSE) {
-		/* make sure the mouse is still pointing at the point calculated earlier */
-		screenRenderInfo.lowerLeftX = mouseCoordinateX - mouseX / screenRenderInfo.scaleFactorX;
-		screenRenderInfo.lowerLeftY = mouseCoordinateY - (screenRenderInfo.displayHeight - mouseY) /
-			screenRenderInfo.scaleFactorY;
-	}
-	render_refresh_rendered_image_on_screen();
-	return;
+render_zoom_display(gint zoomType, gdouble scaleFactor, gdouble mouseX, gdouble mouseY) {
+    gdouble mouseCoordinateX = 0.0;
+    gdouble mouseCoordinateY = 0.0;
+    double  oldWidth, oldHeight;
+
+    oldWidth  = screenRenderInfo.displayWidth / screenRenderInfo.scaleFactorX;
+    oldHeight = screenRenderInfo.displayHeight / screenRenderInfo.scaleFactorY;
+
+    if (zoomType == ZOOM_IN_CMOUSE || zoomType == ZOOM_OUT_CMOUSE) {
+        /* calculate what user coordinate the mouse is pointing at */
+        mouseCoordinateX = mouseX / screenRenderInfo.scaleFactorX + screenRenderInfo.lowerLeftX;
+        mouseCoordinateY =
+            (screenRenderInfo.displayHeight - mouseY) / screenRenderInfo.scaleFactorY + screenRenderInfo.lowerLeftY;
+    }
+
+    switch (zoomType) {
+        case ZOOM_IN:        /* Zoom In */
+        case ZOOM_IN_CMOUSE: /* Zoom In Around Mouse Pointer */
+            screenRenderInfo.scaleFactorX =
+                MIN((gdouble)GERBV_SCALE_MAX, (1 + 1 / 3.0) * screenRenderInfo.scaleFactorX);
+            screenRenderInfo.scaleFactorY = screenRenderInfo.scaleFactorX;
+            screenRenderInfo.lowerLeftX +=
+                (oldWidth - (screenRenderInfo.displayWidth / screenRenderInfo.scaleFactorX)) / 2.0;
+            screenRenderInfo.lowerLeftY +=
+                (oldHeight - (screenRenderInfo.displayHeight / screenRenderInfo.scaleFactorY)) / 2.0;
+            break;
+        case ZOOM_OUT:        /* Zoom Out */
+        case ZOOM_OUT_CMOUSE: /* Zoom Out Around Mouse Pointer */
+            screenRenderInfo.scaleFactorX =
+                MAX((gdouble)GERBV_SCALE_MIN, (1 - 1 / 3.0) * screenRenderInfo.scaleFactorX);
+            screenRenderInfo.scaleFactorY = screenRenderInfo.scaleFactorX;
+            screenRenderInfo.lowerLeftX +=
+                (oldWidth - (screenRenderInfo.displayWidth / screenRenderInfo.scaleFactorX)) / 2.0;
+            screenRenderInfo.lowerLeftY +=
+                (oldHeight - (screenRenderInfo.displayHeight / screenRenderInfo.scaleFactorY)) / 2.0;
+            break;
+        case ZOOM_FIT: /* Zoom Fit */ gerbv_render_zoom_to_fit_display(mainProject, &screenRenderInfo); break;
+        case ZOOM_SET: /*explicit scale set by user */
+            screenRenderInfo.scaleFactorX = MIN((gdouble)GERBV_SCALE_MAX, scaleFactor);
+            screenRenderInfo.scaleFactorY = screenRenderInfo.scaleFactorX;
+            screenRenderInfo.lowerLeftX +=
+                (oldWidth - (screenRenderInfo.displayWidth / screenRenderInfo.scaleFactorX)) / 2.0;
+            screenRenderInfo.lowerLeftY +=
+                (oldHeight - (screenRenderInfo.displayHeight / screenRenderInfo.scaleFactorY)) / 2.0;
+            break;
+        default: GERB_MESSAGE(_("Illegal zoom direction %d"), zoomType);
+    }
+
+    if (zoomType == ZOOM_IN_CMOUSE || zoomType == ZOOM_OUT_CMOUSE) {
+        /* make sure the mouse is still pointing at the point calculated earlier */
+        screenRenderInfo.lowerLeftX = mouseCoordinateX - mouseX / screenRenderInfo.scaleFactorX;
+        screenRenderInfo.lowerLeftY =
+            mouseCoordinateY - (screenRenderInfo.displayHeight - mouseY) / screenRenderInfo.scaleFactorY;
+    }
+    render_refresh_rendered_image_on_screen();
+    return;
 }
 
-
 /* --------------------------------------------------------- */
 /** Will determine the outline of the zoomed regions.
  * In case region to be zoomed is too small (which correspondes
- * e.g. to a double click) it is interpreted as a right-click 
- * and will be used to identify a part from the CURRENT selection, 
+ * e.g. to a double click) it is interpreted as a right-click
+ * and will be used to identify a part from the CURRENT selection,
  * which is drawn on screen*/
 void
-render_calculate_zoom_from_outline(GtkWidget *widget, GdkEventButton *event)
-{
-	int x1, y1, x2, y2, dx, dy;	/* Zoom outline (UR and LL corners) */
-	double centerPointX, centerPointY;
-	int half_x, half_y;		/* cache for half window dimensions */
-
-	x1 = MIN((gdouble)screen.start_x, event->x);
-	y1 = MIN((gdouble)screen.start_y, event->y);
-	x2 = MAX((gdouble)screen.start_x, event->x);
-	y2 = MAX((gdouble)screen.start_y, event->y);
-	dx = x2-x1;
-	dy = y2-y1;
-
-	if ((dx >= 4) && (dy >= 4)) {
-		if (screen.centered_outline_zoom) {
-			/* Centered outline mode */
-			x1 = screen.start_x - dx;
-			y1 = screen.start_y - dy;
-			dx *= 2;
-			dy *= 2;
-		}
-		half_x = (x1+x2)/2;
-		half_y = (y1+y2)/2;
-		centerPointX = half_x/screenRenderInfo.scaleFactorX + screenRenderInfo.lowerLeftX;
-		centerPointY = (screenRenderInfo.displayHeight - half_y)/screenRenderInfo.scaleFactorY +
-				screenRenderInfo.lowerLeftY;
-
-		screenRenderInfo.scaleFactorX *=
-			MIN((double)screenRenderInfo.displayWidth / dx,
-				(double)screenRenderInfo.displayHeight / dy);
-		screenRenderInfo.scaleFactorX = MIN((gdouble)GERBV_SCALE_MAX,
-				screenRenderInfo.scaleFactorX);
-		screenRenderInfo.scaleFactorY = screenRenderInfo.scaleFactorX;
-		screenRenderInfo.lowerLeftX = centerPointX - (screenRenderInfo.displayWidth /
-					2.0 / screenRenderInfo.scaleFactorX);
-		screenRenderInfo.lowerLeftY = centerPointY - (screenRenderInfo.displayHeight /
-					2.0 / screenRenderInfo.scaleFactorY);
-	}
-	render_refresh_rendered_image_on_screen();
+render_calculate_zoom_from_outline(GtkWidget* widget, GdkEventButton* event) {
+    int    x1, y1, x2, y2, dx, dy; /* Zoom outline (UR and LL corners) */
+    double centerPointX, centerPointY;
+    int    half_x, half_y; /* cache for half window dimensions */
+
+    x1 = MIN((gdouble)screen.start_x, event->x);
+    y1 = MIN((gdouble)screen.start_y, event->y);
+    x2 = MAX((gdouble)screen.start_x, event->x);
+    y2 = MAX((gdouble)screen.start_y, event->y);
+    dx = x2 - x1;
+    dy = y2 - y1;
+
+    if ((dx >= 4) && (dy >= 4)) {
+        if (screen.centered_outline_zoom) {
+            /* Centered outline mode */
+            x1 = screen.start_x - dx;
+            y1 = screen.start_y - dy;
+            dx *= 2;
+            dy *= 2;
+        }
+        half_x       = (x1 + x2) / 2;
+        half_y       = (y1 + y2) / 2;
+        centerPointX = half_x / screenRenderInfo.scaleFactorX + screenRenderInfo.lowerLeftX;
+        centerPointY =
+            (screenRenderInfo.displayHeight - half_y) / screenRenderInfo.scaleFactorY + screenRenderInfo.lowerLeftY;
+
+        screenRenderInfo.scaleFactorX *=
+            MIN((double)screenRenderInfo.displayWidth / dx, (double)screenRenderInfo.displayHeight / dy);
+        screenRenderInfo.scaleFactorX = MIN((gdouble)GERBV_SCALE_MAX, screenRenderInfo.scaleFactorX);
+        screenRenderInfo.scaleFactorY = screenRenderInfo.scaleFactorX;
+        screenRenderInfo.lowerLeftX =
+            centerPointX - (screenRenderInfo.displayWidth / 2.0 / screenRenderInfo.scaleFactorX);
+        screenRenderInfo.lowerLeftY =
+            centerPointY - (screenRenderInfo.displayHeight / 2.0 / screenRenderInfo.scaleFactorY);
+    }
+    render_refresh_rendered_image_on_screen();
 }
 
 /* ------------------------------------------------------ */
 void
 render_draw_selection_box_outline(void) {
-	GdkGC *gc;
-	GdkGCValues values;
-	GdkGCValuesMask values_mask;
-	gint x1, y1, x2, y2, dx, dy;
-
-	memset(&values, 0, sizeof(values));
-	values.function = GDK_XOR;
-	if (!screen.zoom_outline_color.pixel)
-	 	gdk_colormap_alloc_color(gdk_colormap_get_system(), &screen.zoom_outline_color, FALSE, TRUE);
-	values.foreground = screen.zoom_outline_color;
-	values_mask = GDK_GC_FUNCTION | GDK_GC_FOREGROUND;
-	gc = gdk_gc_new_with_values(screen.drawing_area->window, &values, values_mask);
-	
-	x1 = MIN(screen.start_x, screen.last_x);
-	y1 = MIN(screen.start_y, screen.last_y);
-	x2 = MAX(screen.start_x, screen.last_x);
-	y2 = MAX(screen.start_y, screen.last_y);
-	dx = x2-x1;
-	dy = y2-y1;
-
-	gdk_draw_rectangle(screen.drawing_area->window, gc, FALSE, x1, y1, dx, dy);
-	gdk_gc_unref(gc);
+    GdkGC*          gc;
+    GdkGCValues     values;
+    GdkGCValuesMask values_mask;
+    gint            x1, y1, x2, y2, dx, dy;
+
+    memset(&values, 0, sizeof(values));
+    values.function = GDK_XOR;
+    if (!screen.zoom_outline_color.pixel)
+        gdk_colormap_alloc_color(gdk_colormap_get_system(), &screen.zoom_outline_color, FALSE, TRUE);
+    values.foreground = screen.zoom_outline_color;
+    values_mask       = GDK_GC_FUNCTION | GDK_GC_FOREGROUND;
+    gc                = gdk_gc_new_with_values(screen.drawing_area->window, &values, values_mask);
+
+    x1 = MIN(screen.start_x, screen.last_x);
+    y1 = MIN(screen.start_y, screen.last_y);
+    x2 = MAX(screen.start_x, screen.last_x);
+    y2 = MAX(screen.start_y, screen.last_y);
+    dx = x2 - x1;
+    dy = y2 - y1;
+
+    gdk_draw_rectangle(screen.drawing_area->window, gc, FALSE, x1, y1, dx, dy);
+    gdk_gc_unref(gc);
 }
 
 /* --------------------------------------------------------- */
 void
-render_draw_zoom_outline(gboolean centered)
-{
-	GdkGC *gc;
-	GdkGCValues values;
-	GdkGCValuesMask values_mask;
-	gint x1, y1, x2, y2, dx, dy;
-
-	memset(&values, 0, sizeof(values));
-	values.function = GDK_XOR;
-	if (!screen.zoom_outline_color.pixel)
-	 	gdk_colormap_alloc_color(gdk_colormap_get_system(), &screen.zoom_outline_color, FALSE, TRUE);
-	values.foreground = screen.zoom_outline_color;
-	values_mask = GDK_GC_FUNCTION | GDK_GC_FOREGROUND;
-	gc = gdk_gc_new_with_values(screen.drawing_area->window, &values, values_mask);
-	
-	x1 = MIN(screen.start_x, screen.last_x);
-	y1 = MIN(screen.start_y, screen.last_y);
-	x2 = MAX(screen.start_x, screen.last_x);
-	y2 = MAX(screen.start_y, screen.last_y);
-	dx = x2-x1;
-	dy = y2-y1;
-
-	if (centered) {
-		/* Centered outline mode */
-		x1 = screen.start_x - dx;
-		y1 = screen.start_y - dy;
-		dx *= 2;
-		dy *= 2;
-		x2 = x1+dx;
-		y2 = y1+dy;
-	}
-
-	gdk_draw_rectangle(screen.drawing_area->window, gc, FALSE, x1, y1, dx, dy);
-	gdk_gc_unref(gc);
-
-	/* Draw actual zoom area in dashed lines */
-	memset(&values, 0, sizeof(values));
-	values.function = GDK_XOR;
-	values.foreground = screen.zoom_outline_color;
-	values.line_style = GDK_LINE_ON_OFF_DASH;
-	values_mask = GDK_GC_FUNCTION | GDK_GC_FOREGROUND | GDK_GC_LINE_STYLE;
-	gc = gdk_gc_new_with_values(screen.drawing_area->window, &values,
-				values_mask);
-	
-	if ((dy == 0) || ((double)dx/dy > (double)screen.drawing_area->allocation.width/
-				screen.drawing_area->allocation.height)) {
-		dy = dx * (double)screen.drawing_area->allocation.height/
-			screen.drawing_area->allocation.width;
-	} 
-	else {
-		dx = dy * (double)screen.drawing_area->allocation.width/
-			screen.drawing_area->allocation.height;
-	}
-
-	gdk_draw_rectangle(screen.drawing_area->window, gc, FALSE, (x1+x2-dx)/2,
-		(y1+y2-dy)/2, dx, dy);
-
-	gdk_gc_unref(gc);
+render_draw_zoom_outline(gboolean centered) {
+    GdkGC*          gc;
+    GdkGCValues     values;
+    GdkGCValuesMask values_mask;
+    gint            x1, y1, x2, y2, dx, dy;
+
+    memset(&values, 0, sizeof(values));
+    values.function = GDK_XOR;
+    if (!screen.zoom_outline_color.pixel)
+        gdk_colormap_alloc_color(gdk_colormap_get_system(), &screen.zoom_outline_color, FALSE, TRUE);
+    values.foreground = screen.zoom_outline_color;
+    values_mask       = GDK_GC_FUNCTION | GDK_GC_FOREGROUND;
+    gc                = gdk_gc_new_with_values(screen.drawing_area->window, &values, values_mask);
+
+    x1 = MIN(screen.start_x, screen.last_x);
+    y1 = MIN(screen.start_y, screen.last_y);
+    x2 = MAX(screen.start_x, screen.last_x);
+    y2 = MAX(screen.start_y, screen.last_y);
+    dx = x2 - x1;
+    dy = y2 - y1;
+
+    if (centered) {
+        /* Centered outline mode */
+        x1 = screen.start_x - dx;
+        y1 = screen.start_y - dy;
+        dx *= 2;
+        dy *= 2;
+        x2 = x1 + dx;
+        y2 = y1 + dy;
+    }
+
+    gdk_draw_rectangle(screen.drawing_area->window, gc, FALSE, x1, y1, dx, dy);
+    gdk_gc_unref(gc);
+
+    /* Draw actual zoom area in dashed lines */
+    memset(&values, 0, sizeof(values));
+    values.function   = GDK_XOR;
+    values.foreground = screen.zoom_outline_color;
+    values.line_style = GDK_LINE_ON_OFF_DASH;
+    values_mask       = GDK_GC_FUNCTION | GDK_GC_FOREGROUND | GDK_GC_LINE_STYLE;
+    gc                = gdk_gc_new_with_values(screen.drawing_area->window, &values, values_mask);
+
+    if ((dy == 0)
+        || ((double)dx / dy > (double)screen.drawing_area->allocation.width / screen.drawing_area->allocation.height)) {
+        dy = dx * (double)screen.drawing_area->allocation.height / screen.drawing_area->allocation.width;
+    } else {
+        dx = dy * (double)screen.drawing_area->allocation.width / screen.drawing_area->allocation.height;
+    }
+
+    gdk_draw_rectangle(screen.drawing_area->window, gc, FALSE, (x1 + x2 - dx) / 2, (y1 + y2 - dy) / 2, dx, dy);
+
+    gdk_gc_unref(gc);
 }
 
 /* ------------------------------------------------------ */
 /* Transforms board coordinates to screen ones */
 static void
-render_board2screen(gdouble *X, gdouble *Y, gdouble x, gdouble y) {
-	*X = (x - screenRenderInfo.lowerLeftX) * screenRenderInfo.scaleFactorX;
-	*Y = screenRenderInfo.displayHeight - (y - screenRenderInfo.lowerLeftY)
-		* screenRenderInfo.scaleFactorY;
+render_board2screen(gdouble* X, gdouble* Y, gdouble x, gdouble y) {
+    *X = (x - screenRenderInfo.lowerLeftX) * screenRenderInfo.scaleFactorX;
+    *Y = screenRenderInfo.displayHeight - (y - screenRenderInfo.lowerLeftY) * screenRenderInfo.scaleFactorY;
 }
 
 /* Trims the coordinates to avoid overflows in gdk_draw_line */
 static void
-render_trim_point(gdouble *start_x, gdouble *start_y, gdouble last_x, gdouble last_y)
-{
-	const gdouble max_coord = (1<<15) - 2;/* a value that causes no overflow
-											 and lies out of screen */
-	gdouble dx, dy;
-
-    if (fabs (*start_x) < max_coord && fabs (*start_y) < max_coord)
-		return;	
-
-	dx = last_x - *start_x;
-	dy = last_y - *start_y;
-
-	if (*start_x < -max_coord) {
-		*start_x = -max_coord;
-		if (last_x > -max_coord && fabs (dx) > 0.1)
-			*start_y = last_y - (last_x + max_coord) / dx * dy;
-	}
-	if (*start_x > max_coord) {
-		*start_x = max_coord;
-		if (last_x < max_coord && fabs (dx) > 0.1)
-			*start_y = last_y - (last_x - max_coord) / dx * dy;
-	}
-
-	dx = last_x - *start_x;
-	dy = last_y - *start_y;
-
-	if (*start_y < -max_coord) {
-		*start_y = -max_coord;
-		if (last_y > -max_coord && fabs (dy) > 0.1)
-			*start_x = last_x - (last_y + max_coord) / dy * dx;
-	}
-	if (*start_y > max_coord) {
-		*start_y = max_coord;
-		if (last_y < max_coord && fabs (dy) > 0.1)
-			*start_x = last_x - (last_y - max_coord) / dy * dx;
-	}
+render_trim_point(gdouble* start_x, gdouble* start_y, gdouble last_x, gdouble last_y) {
+    const gdouble max_coord = (1 << 15) - 2; /* a value that causes no overflow
+                                                and lies out of screen */
+    gdouble dx, dy;
+
+    if (fabs(*start_x) < max_coord && fabs(*start_y) < max_coord)
+        return;
+
+    dx = last_x - *start_x;
+    dy = last_y - *start_y;
+
+    if (*start_x < -max_coord) {
+        *start_x = -max_coord;
+        if (last_x > -max_coord && fabs(dx) > 0.1)
+            *start_y = last_y - (last_x + max_coord) / dx * dy;
+    }
+    if (*start_x > max_coord) {
+        *start_x = max_coord;
+        if (last_x < max_coord && fabs(dx) > 0.1)
+            *start_y = last_y - (last_x - max_coord) / dx * dy;
+    }
+
+    dx = last_x - *start_x;
+    dy = last_y - *start_y;
+
+    if (*start_y < -max_coord) {
+        *start_y = -max_coord;
+        if (last_y > -max_coord && fabs(dy) > 0.1)
+            *start_x = last_x - (last_y + max_coord) / dy * dx;
+    }
+    if (*start_y > max_coord) {
+        *start_y = max_coord;
+        if (last_y < max_coord && fabs(dy) > 0.1)
+            *start_x = last_x - (last_y - max_coord) / dy * dx;
+    }
 }
 
 /* ------------------------------------------------------ */
 /** Draws/erases measure line
  */
 void
-render_toggle_measure_line(void)
-{
-
-	GdkGC *gc;
-	GdkGCValues values;
-	GdkGCValuesMask values_mask;
-	gdouble start_x, start_y, last_x, last_y;
-	memset(&values, 0, sizeof(values));
-	values.function = GDK_XOR;
-	values.line_width = 6;
-	if (!screen.zoom_outline_color.pixel)
-	 	gdk_colormap_alloc_color(gdk_colormap_get_system(), &screen.zoom_outline_color, FALSE, TRUE);
-	values.foreground = screen.zoom_outline_color;
-	values_mask = GDK_GC_FUNCTION | GDK_GC_LINE_WIDTH | GDK_GC_FOREGROUND;
-	gc = gdk_gc_new_with_values(screen.drawing_area->window, &values,
-				values_mask);
-	render_board2screen(&start_x, &start_y,
-				screen.measure_start_x, screen.measure_start_y);
-	render_board2screen(&last_x, &last_y,
-				screen.measure_stop_x, screen.measure_stop_y);
-	render_trim_point(&start_x, &start_y, last_x, last_y);
-	render_trim_point(&last_x, &last_y, start_x, start_y);
-	gdk_draw_line(screen.drawing_area->window, gc, start_x,
-		  start_y, last_x, last_y);
-	gdk_gc_unref(gc);
+render_toggle_measure_line(void) {
+
+    GdkGC*          gc;
+    GdkGCValues     values;
+    GdkGCValuesMask values_mask;
+    gdouble         start_x, start_y, last_x, last_y;
+    memset(&values, 0, sizeof(values));
+    values.function   = GDK_XOR;
+    values.line_width = 6;
+    if (!screen.zoom_outline_color.pixel)
+        gdk_colormap_alloc_color(gdk_colormap_get_system(), &screen.zoom_outline_color, FALSE, TRUE);
+    values.foreground = screen.zoom_outline_color;
+    values_mask       = GDK_GC_FUNCTION | GDK_GC_LINE_WIDTH | GDK_GC_FOREGROUND;
+    gc                = gdk_gc_new_with_values(screen.drawing_area->window, &values, values_mask);
+    render_board2screen(&start_x, &start_y, screen.measure_start_x, screen.measure_start_y);
+    render_board2screen(&last_x, &last_y, screen.measure_stop_x, screen.measure_stop_y);
+    render_trim_point(&start_x, &start_y, last_x, last_y);
+    render_trim_point(&last_x, &last_y, start_x, start_y);
+    gdk_draw_line(screen.drawing_area->window, gc, start_x, start_y, last_x, last_y);
+    gdk_gc_unref(gc);
 } /* toggle_measure_line */
 
 /* ------------------------------------------------------ */
 /** Displays a measured distance graphically on screen and in statusbar. */
 void
-render_draw_measure_distance(void)
-{
-	gdouble dx, dy;
+render_draw_measure_distance(void) {
+    gdouble dx, dy;
 
-	dx = fabs (screen.measure_start_x - screen.measure_stop_x);
-	dy = fabs (screen.measure_start_y - screen.measure_stop_y);
+    dx = fabs(screen.measure_start_x - screen.measure_stop_x);
+    dy = fabs(screen.measure_start_y - screen.measure_stop_y);
 
-	screen.measure_last_x = dx;
-	screen.measure_last_y = dy;
-	callbacks_update_statusbar_measured_distance (dx, dy);
-	render_toggle_measure_line();
+    screen.measure_last_x = dx;
+    screen.measure_last_y = dy;
+    callbacks_update_statusbar_measured_distance(dx, dy);
+    render_toggle_measure_line();
 }
 
 /* ------------------------------------------------------ */
-static void render_selection (void)
-{
-	gerbv_selection_item_t sel_item;
-	gerbv_fileinfo_t *file;
-	gdouble pixel_width;
-	cairo_t *cr;
-	int i;
-	guint j;
-
-	if (selection_length (&screen.selectionInfo) == 0)
-		return;
-
-	if (screen.selectionRenderData)
-		cairo_surface_destroy (
-				(cairo_surface_t *)screen.selectionRenderData);
-
-	screen.selectionRenderData =
-		(gpointer) cairo_surface_create_similar (
-			(cairo_surface_t *)screen.windowSurface,
-			CAIRO_CONTENT_COLOR_ALPHA,
-			screenRenderInfo.displayWidth,
-			screenRenderInfo.displayHeight);
-
-	pixel_width = 1.0/MAX(screenRenderInfo.scaleFactorX,
-				screenRenderInfo.scaleFactorY);
-
-	for (i = mainProject->last_loaded; i >= 0; i--) {
-		file = mainProject->file[i]; 
-
-		if (!file ||
-		(!mainProject->show_invisible_selection && !file->isVisible))
-			continue;
-
-		for (j = 0; j < selection_length (&screen.selectionInfo); j++) {
-			sel_item = selection_get_item_by_index (
-					&screen.selectionInfo, j);
-			if (file->image != sel_item.image)
-				continue;
-
-			/* Have selected image(s) on this file, draw it */
-
-			cr = cairo_create(screen.selectionRenderData);
-			gerbv_render_cairo_set_scale_and_translation(cr,
-					&screenRenderInfo);
-			cairo_set_source_rgba (cr, 1.0, 1.0, 1.0, 0.85);
-			draw_image_to_cairo_target (cr,
-				file->image, pixel_width,
-				DRAW_SELECTIONS, &screen.selectionInfo,
-				&screenRenderInfo, TRUE,
-				file->transform, TRUE);
-			cairo_destroy (cr);
-
-			break;	/* All done, go to next file */
-		}
-	}
+static void
+render_selection(void) {
+    gerbv_selection_item_t sel_item;
+    gerbv_fileinfo_t*      file;
+    gdouble                pixel_width;
+    cairo_t*               cr;
+    int                    i;
+    guint                  j;
+
+    if (selection_length(&screen.selectionInfo) == 0)
+        return;
+
+    if (screen.selectionRenderData)
+        cairo_surface_destroy((cairo_surface_t*)screen.selectionRenderData);
+
+    screen.selectionRenderData = (gpointer)cairo_surface_create_similar(
+        (cairo_surface_t*)screen.windowSurface, CAIRO_CONTENT_COLOR_ALPHA, screenRenderInfo.displayWidth,
+        screenRenderInfo.displayHeight
+    );
+
+    pixel_width = 1.0 / MAX(screenRenderInfo.scaleFactorX, screenRenderInfo.scaleFactorY);
+
+    for (i = mainProject->last_loaded; i >= 0; i--) {
+        file = mainProject->file[i];
+
+        if (!file || (!mainProject->show_invisible_selection && !file->isVisible))
+            continue;
+
+        for (j = 0; j < selection_length(&screen.selectionInfo); j++) {
+            sel_item = selection_get_item_by_index(&screen.selectionInfo, j);
+            if (file->image != sel_item.image)
+                continue;
+
+            /* Have selected image(s) on this file, draw it */
+
+            cr = cairo_create(screen.selectionRenderData);
+            gerbv_render_cairo_set_scale_and_translation(cr, &screenRenderInfo);
+            cairo_set_source_rgba(cr, 1.0, 1.0, 1.0, 0.85);
+            draw_image_to_cairo_target(
+                cr, file->image, pixel_width, DRAW_SELECTIONS, &screen.selectionInfo, &screenRenderInfo, TRUE,
+                file->transform, TRUE
+            );
+            cairo_destroy(cr);
+
+            break; /* All done, go to next file */
+        }
+    }
 }
 
 /* ------------------------------------------------------ */
-void render_refresh_rendered_image_on_screen (void) {
-	GdkCursor *cursor;
-	
-	dprintf("----> Entering redraw_pixmap...\n");
-	cursor = gdk_cursor_new(GDK_WATCH);
-	gdk_window_set_cursor(GDK_WINDOW(screen.drawing_area->window), cursor);
-	gdk_cursor_destroy(cursor);
-
-	if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR){
-	    if (screen.pixmap) 
-		gdk_pixmap_unref(screen.pixmap);
-	    screen.pixmap = gdk_pixmap_new(screen.drawing_area->window, screenRenderInfo.displayWidth,
-	    screenRenderInfo.displayHeight, -1);
-	    gerbv_render_to_pixmap_using_gdk (mainProject, screen.pixmap, &screenRenderInfo, &screen.selectionInfo,
-	    		&screen.selection_color);	
-	    dprintf("<---- leaving redraw_pixmap.\n");
-	}
-	else{
-	    int i;
-	    dprintf("    .... Now try rendering the drawing using cairo .... \n");
-	    /* 
-	     * This now allows drawing several layers on top of each other.
-	     * Higher layer numbers have higher priority in the Z-order.
-	     */
-	    for(i = mainProject->last_loaded; i >= 0; i--) {
-		if (mainProject->file[i]) {
-		    cairo_t *cr;
-		    if (mainProject->file[i]->privateRenderData) 
-			cairo_surface_destroy ((cairo_surface_t *) mainProject->file[i]->privateRenderData);
-		    mainProject->file[i]->privateRenderData = 
-			(gpointer) cairo_surface_create_similar ((cairo_surface_t *)screen.windowSurface,
-			CAIRO_CONTENT_COLOR_ALPHA, screenRenderInfo.displayWidth,
-			screenRenderInfo.displayHeight);
-		    cr= cairo_create(mainProject->file[i]->privateRenderData );
-		    gerbv_render_layer_to_cairo_target (cr, mainProject->file[i], &screenRenderInfo);
-		    dprintf("    .... calling render_image_to_cairo_target on layer %d...\n", i);			
-		    cairo_destroy (cr);
-		}
-	    }
-	    
-	    render_recreate_composite_surface ();
-	}
-	/* remove watch cursor and switch back to normal cursor */
-	callbacks_switch_to_correct_cursor ();
-	callbacks_force_expose_event_for_screen();
+void
+render_refresh_rendered_image_on_screen(void) {
+    GdkCursor* cursor;
+
+    dprintf("----> Entering redraw_pixmap...\n");
+    cursor = gdk_cursor_new(GDK_WATCH);
+    gdk_window_set_cursor(GDK_WINDOW(screen.drawing_area->window), cursor);
+    gdk_cursor_destroy(cursor);
+
+    if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
+        if (screen.pixmap)
+            gdk_pixmap_unref(screen.pixmap);
+        screen.pixmap = gdk_pixmap_new(
+            screen.drawing_area->window, screenRenderInfo.displayWidth, screenRenderInfo.displayHeight, -1
+        );
+        gerbv_render_to_pixmap_using_gdk(
+            mainProject, screen.pixmap, &screenRenderInfo, &screen.selectionInfo, &screen.selection_color
+        );
+        dprintf("<---- leaving redraw_pixmap.\n");
+    } else {
+        int i;
+        dprintf("    .... Now try rendering the drawing using cairo .... \n");
+        /*
+         * This now allows drawing several layers on top of each other.
+         * Higher layer numbers have higher priority in the Z-order.
+         */
+        for (i = mainProject->last_loaded; i >= 0; i--) {
+            if (mainProject->file[i]) {
+                cairo_t* cr;
+                if (mainProject->file[i]->privateRenderData)
+                    cairo_surface_destroy((cairo_surface_t*)mainProject->file[i]->privateRenderData);
+                mainProject->file[i]->privateRenderData = (gpointer)cairo_surface_create_similar(
+                    (cairo_surface_t*)screen.windowSurface, CAIRO_CONTENT_COLOR_ALPHA, screenRenderInfo.displayWidth,
+                    screenRenderInfo.displayHeight
+                );
+                cr = cairo_create(mainProject->file[i]->privateRenderData);
+                gerbv_render_layer_to_cairo_target(cr, mainProject->file[i], &screenRenderInfo);
+                dprintf("    .... calling render_image_to_cairo_target on layer %d...\n", i);
+                cairo_destroy(cr);
+            }
+        }
+
+        render_recreate_composite_surface();
+    }
+    /* remove watch cursor and switch back to normal cursor */
+    callbacks_switch_to_correct_cursor();
+    callbacks_force_expose_event_for_screen();
 }
 
 /* ------------------------------------------------------ */
 void
-render_remove_selected_objects_belonging_to_layer (
-			gerbv_selection_info_t *sel_info, gerbv_image_t *image)
-{
-	guint i;
-
-	for (i = 0; i < selection_length (sel_info);) {
-		gerbv_selection_item_t sItem =
-			selection_get_item_by_index (sel_info, i);
-
-		if (image == (gerbv_image_t *) sItem.image)
-			selection_clear_item_by_index (sel_info, i);
-		else
-			i++;
-	}
+render_remove_selected_objects_belonging_to_layer(gerbv_selection_info_t* sel_info, gerbv_image_t* image) {
+    guint i;
+
+    for (i = 0; i < selection_length(sel_info);) {
+        gerbv_selection_item_t sItem = selection_get_item_by_index(sel_info, i);
+
+        if (image == (gerbv_image_t*)sItem.image)
+            selection_clear_item_by_index(sel_info, i);
+        else
+            i++;
+    }
 }
 
 /* ------------------------------------------------------ */
 gint
-render_create_cairo_buffer_surface () {
-	if (screen.bufferSurface) {
-		cairo_surface_destroy (screen.bufferSurface);
-		screen.bufferSurface = NULL;
-	}
-	if (!screen.windowSurface)
-		return 0;
-
-	screen.bufferSurface= cairo_surface_create_similar ((cairo_surface_t *)screen.windowSurface,
-	                                    CAIRO_CONTENT_COLOR, screenRenderInfo.displayWidth,
-	                                    screenRenderInfo.displayHeight);
-	return 1;
+render_create_cairo_buffer_surface() {
+    if (screen.bufferSurface) {
+        cairo_surface_destroy(screen.bufferSurface);
+        screen.bufferSurface = NULL;
+    }
+    if (!screen.windowSurface)
+        return 0;
+
+    screen.bufferSurface = cairo_surface_create_similar(
+        (cairo_surface_t*)screen.windowSurface, CAIRO_CONTENT_COLOR, screenRenderInfo.displayWidth,
+        screenRenderInfo.displayHeight
+    );
+    return 1;
 }
 
 /* ------------------------------------------------------ */
 static void
-render_find_selected_objects_and_refresh_display (gint activeFileIndex,
-		enum selection_action action)
-{
-	enum draw_mode mode = FIND_SELECTIONS;
-
-	/* clear the old selection array if desired */
-	if ((action == SELECTION_REPLACE)
-	 && (selection_length (&screen.selectionInfo) != 0))
-		selection_clear (&screen.selectionInfo);
-
-	if (action == SELECTION_TOGGLE)
-		mode = FIND_SELECTIONS_TOGGLE;
-
-	/* make sure we have a bufferSurface...if we start up in FAST mode, we may not
-	   have one yet, but we need it for selections */
-	if (!render_create_cairo_buffer_surface ())
-		return;
-
-	/* call draw_image... passing the FILL_SELECTION mode to just search for
-	   nets which match the selection, and fill the selection buffer with them */
-	cairo_t *cr = cairo_create (screen.bufferSurface);	
-	gerbv_render_cairo_set_scale_and_translation (cr, &screenRenderInfo);
-	draw_image_to_cairo_target (cr,
-			mainProject->file[activeFileIndex]->image,
-			1.0/MAX (screenRenderInfo.scaleFactorX,
-				screenRenderInfo.scaleFactorY),
-			mode, &screen.selectionInfo, &screenRenderInfo, TRUE,
-			mainProject->file[activeFileIndex]->transform, TRUE);
-	cairo_destroy (cr);
-
-	/* re-render the selection buffer layer */
-	if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
-		render_refresh_rendered_image_on_screen ();
-	} else {
-		render_recreate_composite_surface ();
-		callbacks_force_expose_event_for_screen ();
-	}
+render_find_selected_objects_and_refresh_display(gint activeFileIndex, enum selection_action action) {
+    enum draw_mode mode = FIND_SELECTIONS;
+
+    /* clear the old selection array if desired */
+    if ((action == SELECTION_REPLACE) && (selection_length(&screen.selectionInfo) != 0))
+        selection_clear(&screen.selectionInfo);
+
+    if (action == SELECTION_TOGGLE)
+        mode = FIND_SELECTIONS_TOGGLE;
+
+    /* make sure we have a bufferSurface...if we start up in FAST mode, we may not
+       have one yet, but we need it for selections */
+    if (!render_create_cairo_buffer_surface())
+        return;
+
+    /* call draw_image... passing the FILL_SELECTION mode to just search for
+       nets which match the selection, and fill the selection buffer with them */
+    cairo_t* cr = cairo_create(screen.bufferSurface);
+    gerbv_render_cairo_set_scale_and_translation(cr, &screenRenderInfo);
+    draw_image_to_cairo_target(
+        cr, mainProject->file[activeFileIndex]->image,
+        1.0 / MAX(screenRenderInfo.scaleFactorX, screenRenderInfo.scaleFactorY), mode, &screen.selectionInfo,
+        &screenRenderInfo, TRUE, mainProject->file[activeFileIndex]->transform, TRUE
+    );
+    cairo_destroy(cr);
+
+    /* re-render the selection buffer layer */
+    if (screenRenderInfo.renderType <= GERBV_RENDER_TYPE_GDK_XOR) {
+        render_refresh_rendered_image_on_screen();
+    } else {
+        render_recreate_composite_surface();
+        callbacks_force_expose_event_for_screen();
+    }
 }
 
 /* ------------------------------------------------------ */
 void
-render_fill_selection_buffer_from_mouse_click (gint mouseX, gint mouseY,
-		gint activeFileIndex, enum selection_action action)
-{
-	screen.selectionInfo.lowerLeftX = mouseX;
-	screen.selectionInfo.lowerLeftY = mouseY;
-	/* no need to populate the upperright coordinates for a point_click */
-	screen.selectionInfo.type = GERBV_SELECTION_POINT_CLICK;
-	render_find_selected_objects_and_refresh_display (
-			activeFileIndex, action);
+render_fill_selection_buffer_from_mouse_click(
+    gint mouseX, gint mouseY, gint activeFileIndex, enum selection_action action
+) {
+    screen.selectionInfo.lowerLeftX = mouseX;
+    screen.selectionInfo.lowerLeftY = mouseY;
+    /* no need to populate the upperright coordinates for a point_click */
+    screen.selectionInfo.type = GERBV_SELECTION_POINT_CLICK;
+    render_find_selected_objects_and_refresh_display(activeFileIndex, action);
 }
 
 /* ------------------------------------------------------ */
 void
-render_fill_selection_buffer_from_mouse_drag (gint corner1X, gint corner1Y,
-		gint corner2X, gint corner2Y,
-		gint activeFileIndex, enum selection_action action)
-{
-	/* figure out the lower left corner of the box */
-	screen.selectionInfo.lowerLeftX = MIN(corner1X, corner2X);
-	screen.selectionInfo.lowerLeftY = MIN(corner1Y, corner2Y);
-	/* figure out the upper right corner of the box */
-	screen.selectionInfo.upperRightX = MAX(corner1X, corner2X);
-	screen.selectionInfo.upperRightY = MAX(corner1Y, corner2Y);
-	
-	screen.selectionInfo.type = GERBV_SELECTION_DRAG_BOX;
-	render_find_selected_objects_and_refresh_display (
-			activeFileIndex, action);
+render_fill_selection_buffer_from_mouse_drag(
+    gint corner1X, gint corner1Y, gint corner2X, gint corner2Y, gint activeFileIndex, enum selection_action action
+) {
+    /* figure out the lower left corner of the box */
+    screen.selectionInfo.lowerLeftX = MIN(corner1X, corner2X);
+    screen.selectionInfo.lowerLeftY = MIN(corner1Y, corner2Y);
+    /* figure out the upper right corner of the box */
+    screen.selectionInfo.upperRightX = MAX(corner1X, corner2X);
+    screen.selectionInfo.upperRightY = MAX(corner1Y, corner2Y);
+
+    screen.selectionInfo.type = GERBV_SELECTION_DRAG_BOX;
+    render_find_selected_objects_and_refresh_display(activeFileIndex, action);
 }
 
 /* ------------------------------------------------------ */
-void render_recreate_composite_surface ()
-{
-	gint i;
-	
-	if (!render_create_cairo_buffer_surface())
-		return;
-
-	cairo_t *cr= cairo_create(screen.bufferSurface);
-	/* fill the background with the appropriate color */
-	cairo_set_source_rgba (cr, (double) mainProject->background.red/G_MAXUINT16,
-		(double) mainProject->background.green/G_MAXUINT16,
-		(double) mainProject->background.blue/G_MAXUINT16, 1);
-	cairo_paint (cr);
-	
-	for(i = mainProject->last_loaded; i >= 0; i--) {
-		if (mainProject->file[i] && mainProject->file[i]->isVisible) {
-			cairo_set_source_surface (cr, (cairo_surface_t *) mainProject->file[i]->privateRenderData,
-			                              0, 0);
-			/* ignore alpha if we are in high-speed render mode */
-			if (((double) mainProject->file[i]->alpha < 65535)&&(screenRenderInfo.renderType != GERBV_RENDER_TYPE_GDK_XOR)) {
-				cairo_paint_with_alpha(cr,(double) mainProject->file[i]->alpha/G_MAXUINT16);
-			}
-			else {
-				cairo_paint (cr);
-			}
-		}
-	}
-
-	/* render the selection layer at the end */
-	if (selection_length (&screen.selectionInfo) != 0) {
-		render_selection ();
-		cairo_set_source_surface (cr, (cairo_surface_t *) screen.selectionRenderData,
-			                              0, 0);
-		cairo_paint_with_alpha (cr,1.0);
-	}
-	cairo_destroy (cr);
+void
+render_recreate_composite_surface() {
+    gint i;
+
+    if (!render_create_cairo_buffer_surface())
+        return;
+
+    cairo_t* cr = cairo_create(screen.bufferSurface);
+    /* fill the background with the appropriate color */
+    cairo_set_source_rgba(
+        cr, (double)mainProject->background.red / G_MAXUINT16, (double)mainProject->background.green / G_MAXUINT16,
+        (double)mainProject->background.blue / G_MAXUINT16, 1
+    );
+    cairo_paint(cr);
+
+    for (i = mainProject->last_loaded; i >= 0; i--) {
+        if (mainProject->file[i] && mainProject->file[i]->isVisible) {
+            cairo_set_source_surface(cr, (cairo_surface_t*)mainProject->file[i]->privateRenderData, 0, 0);
+            /* ignore alpha if we are in high-speed render mode */
+            if (((double)mainProject->file[i]->alpha < 65535)
+                && (screenRenderInfo.renderType != GERBV_RENDER_TYPE_GDK_XOR)) {
+                cairo_paint_with_alpha(cr, (double)mainProject->file[i]->alpha / G_MAXUINT16);
+            } else {
+                cairo_paint(cr);
+            }
+        }
+    }
+
+    /* render the selection layer at the end */
+    if (selection_length(&screen.selectionInfo) != 0) {
+        render_selection();
+        cairo_set_source_surface(cr, (cairo_surface_t*)screen.selectionRenderData, 0, 0);
+        cairo_paint_with_alpha(cr, 1.0);
+    }
+    cairo_destroy(cr);
 }
 
 /* ------------------------------------------------------ */
-void render_project_to_cairo_target (cairo_t *cr) {
-	/* fill the background with the appropriate color */
-	cairo_set_source_rgba (cr, (double) mainProject->background.red/G_MAXUINT16,
-		(double) mainProject->background.green/G_MAXUINT16,
-		(double) mainProject->background.blue/G_MAXUINT16, 1);
-	cairo_paint (cr);
-
-	cairo_set_source_surface (cr, (cairo_surface_t *) screen.bufferSurface, 0 , 0);
-                                                   
-	cairo_paint (cr);
+void
+render_project_to_cairo_target(cairo_t* cr) {
+    /* fill the background with the appropriate color */
+    cairo_set_source_rgba(
+        cr, (double)mainProject->background.red / G_MAXUINT16, (double)mainProject->background.green / G_MAXUINT16,
+        (double)mainProject->background.blue / G_MAXUINT16, 1
+    );
+    cairo_paint(cr);
+
+    cairo_set_source_surface(cr, (cairo_surface_t*)screen.bufferSurface, 0, 0);
+
+    cairo_paint(cr);
 }
 
 void
-render_free_screen_resources (void) {
-	if (screen.selectionRenderData) 
-		cairo_surface_destroy ((cairo_surface_t *)
-			screen.selectionRenderData);
-	if (screen.bufferSurface)
-		cairo_surface_destroy ((cairo_surface_t *)
-			screen.bufferSurface);
-	if (screen.windowSurface)
-		cairo_surface_destroy ((cairo_surface_t *)
-			screen.windowSurface);
-	if (screen.pixmap) 
-		gdk_pixmap_unref(screen.pixmap);
+render_free_screen_resources(void) {
+    if (screen.selectionRenderData)
+        cairo_surface_destroy((cairo_surface_t*)screen.selectionRenderData);
+    if (screen.bufferSurface)
+        cairo_surface_destroy((cairo_surface_t*)screen.bufferSurface);
+    if (screen.windowSurface)
+        cairo_surface_destroy((cairo_surface_t*)screen.windowSurface);
+    if (screen.pixmap)
+        gdk_pixmap_unref(screen.pixmap);
 }
 
-
 /* ------------------------------------------------------------------ */
 /*! This fills out the project's Gerber statistics table.
  *  It is called from within callbacks.c when the user
  *  asks for a Gerber report.  */
-gerbv_stats_t *
-generate_gerber_analysis(void)
-{
-	int i;
-	gerbv_stats_t *stats;
-	gerbv_stats_t *instats;
-
-	/* Create new stats structure to hold report for whole project 
-	* (i.e. all layers together) */
-	stats = gerbv_stats_new();
-
-	/* Loop through open layers and compile statistics by accumulating reports from each layer */
-	for (i = 0; i <= mainProject->last_loaded; i++) {
-		if (mainProject->file[i] && mainProject->file[i]->isVisible &&
-				(mainProject->file[i]->image->layertype == GERBV_LAYERTYPE_RS274X) ) {
-			instats = mainProject->file[i]->image->gerbv_stats;
-			gerbv_stats_add_layer(stats, instats, i+1);
-		}
-	}
-	return stats;
+gerbv_stats_t*
+generate_gerber_analysis(void) {
+    int            i;
+    gerbv_stats_t* stats;
+    gerbv_stats_t* instats;
+
+    /* Create new stats structure to hold report for whole project
+     * (i.e. all layers together) */
+    stats = gerbv_stats_new();
+
+    /* Loop through open layers and compile statistics by accumulating reports from each layer */
+    for (i = 0; i <= mainProject->last_loaded; i++) {
+        if (mainProject->file[i] && mainProject->file[i]->isVisible
+            && (mainProject->file[i]->image->layertype == GERBV_LAYERTYPE_RS274X)) {
+            instats = mainProject->file[i]->image->gerbv_stats;
+            gerbv_stats_add_layer(stats, instats, i + 1);
+        }
+    }
+    return stats;
 }
 
-
 /* ------------------------------------------------------------------ */
 /*! This fills out the project's Drill statistics table.
  *  It is called from within callbacks.c when the user
  *  asks for a Drill report.  */
-gerbv_drill_stats_t *
-generate_drill_analysis(void)
-{
-	int i;
-	gerbv_drill_stats_t *stats;
-	gerbv_drill_stats_t *instats;
-
-	stats = gerbv_drill_stats_new();
-
-	/* Loop through open layers and compile statistics by accumulating reports from each layer */
-	for(i = mainProject->last_loaded; i >= 0; i--) {
-		if (mainProject->file[i] && 
-				mainProject->file[i]->isVisible &&
-				(mainProject->file[i]->image->layertype == GERBV_LAYERTYPE_DRILL) ) {
-			instats = mainProject->file[i]->image->drill_stats;
-			/* add this batch of stats.  Send the layer 
-			* index for error reporting */
-			gerbv_drill_stats_add_layer(stats, instats, i+1);
-		}
-	}
-	return stats;
+gerbv_drill_stats_t*
+generate_drill_analysis(void) {
+    int                  i;
+    gerbv_drill_stats_t* stats;
+    gerbv_drill_stats_t* instats;
+
+    stats = gerbv_drill_stats_new();
+
+    /* Loop through open layers and compile statistics by accumulating reports from each layer */
+    for (i = mainProject->last_loaded; i >= 0; i--) {
+        if (mainProject->file[i] && mainProject->file[i]->isVisible
+            && (mainProject->file[i]->image->layertype == GERBV_LAYERTYPE_DRILL)) {
+            instats = mainProject->file[i]->image->drill_stats;
+            /* add this batch of stats.  Send the layer
+             * index for error reporting */
+            gerbv_drill_stats_add_layer(stats, instats, i + 1);
+        }
+    }
+    return stats;
 }
-
diff --git a/src/render.h b/src/render.h
index d769d6f..016de25 100644
--- a/src/render.h
+++ b/src/render.h
@@ -29,52 +29,42 @@
 
 #include "gerber.h"
 
-gerbv_stats_t *generate_gerber_analysis(void);
-gerbv_drill_stats_t *generate_drill_analysis(void);
+gerbv_stats_t*       generate_gerber_analysis(void);
+gerbv_drill_stats_t* generate_drill_analysis(void);
 
-void render_recreate_composite_surface ();
-void render_project_to_cairo_target (cairo_t *cr);
+void render_recreate_composite_surface();
+void render_project_to_cairo_target(cairo_t* cr);
 
-void
-render_zoom_display (gint zoomType, gdouble scaleFactor, gdouble mouseX, gdouble mouseY);
+void render_zoom_display(gint zoomType, gdouble scaleFactor, gdouble mouseX, gdouble mouseY);
 
-void
-render_calculate_zoom_from_outline(GtkWidget *widget, GdkEventButton *event);
+void render_calculate_zoom_from_outline(GtkWidget* widget, GdkEventButton* event);
 
-void
-render_draw_selection_box_outline(void);
+void render_draw_selection_box_outline(void);
 
-void
-render_draw_zoom_outline(gboolean centered);
+void render_draw_zoom_outline(gboolean centered);
 
-void
-render_toggle_measure_line(void);
+void render_toggle_measure_line(void);
 
-void
-render_draw_measure_distance(void);
+void render_draw_measure_distance(void);
 
+void render_refresh_rendered_image_on_screen(void);
 
-void render_refresh_rendered_image_on_screen (void);
+void render_remove_selected_objects_belonging_to_layer(gerbv_selection_info_t* sel_info, gerbv_image_t* image);
 
-void
-render_remove_selected_objects_belonging_to_layer (
-			gerbv_selection_info_t *sel_info, gerbv_image_t *image);
-
-void
-render_free_screen_resources (void);
+void render_free_screen_resources(void);
 
 enum selection_action {
-	SELECTION_REPLACE = 0,
-	SELECTION_ADD,
-	SELECTION_TOGGLE,
+    SELECTION_REPLACE = 0,
+    SELECTION_ADD,
+    SELECTION_TOGGLE,
 };
 
-void render_fill_selection_buffer_from_mouse_click (gint mouseX, gint mouseY,
-		gint activeFileIndex, enum selection_action action);
+void render_fill_selection_buffer_from_mouse_click(
+    gint mouseX, gint mouseY, gint activeFileIndex, enum selection_action action
+);
 
-void render_fill_selection_buffer_from_mouse_drag (gint corner1X, gint corner1Y,
-		gint corner2X, gint corner2Y,
-		gint activeFileIndex, enum selection_action action);
+void render_fill_selection_buffer_from_mouse_drag(
+    gint corner1X, gint corner1Y, gint corner2X, gint corner2Y, gint activeFileIndex, enum selection_action action
+);
 
 extern gerbv_render_info_t screenRenderInfo;
-
diff --git a/src/scheme-private.h b/src/scheme-private.h
index 67ec9ad..2b03c44 100644
--- a/src/scheme-private.h
+++ b/src/scheme-private.h
@@ -10,180 +10,184 @@
 
 #include "scheme.h"
 
-enum scheme_port_kind { 
-  port_free=0, 
-  port_file=1, 
-  port_string=2, 
-  port_input=16, 
-  port_output=32 
+enum scheme_port_kind {
+    port_free   = 0,
+    port_file   = 1,
+    port_string = 2,
+    port_input  = 16,
+    port_output = 32
 };
 
 typedef struct port {
-  unsigned char kind;
-  union {
-    struct {
-      FILE *file;
-      int closeit;
-    } stdio;
-    struct {
-      char *start;
-      char *past_the_end;
-      char *curr;
-    } string;
-  } rep;
+    unsigned char kind;
+
+    union {
+        struct {
+            FILE* file;
+            int   closeit;
+        } stdio;
+
+        struct {
+            char* start;
+            char* past_the_end;
+            char* curr;
+        } string;
+    } rep;
 } port;
 
 /* cell structure */
 struct cell {
-  unsigned int _flag;
-  union {
-    struct {
-      char   *_svalue;
-      int   _length;
-    } _string;
-    num _number;
-    port *_port;
-    foreign_func _ff;
-    struct {
-      struct cell *_car;
-      struct cell *_cdr;
-    } _cons;
-  } _object;
+    unsigned int _flag;
+
+    union {
+        struct {
+            char* _svalue;
+            int   _length;
+        } _string;
+
+        num          _number;
+        port*        _port;
+        foreign_func _ff;
+
+        struct {
+            struct cell* _car;
+            struct cell* _cdr;
+        } _cons;
+    } _object;
 };
 
 struct scheme {
-/* arrays for segments */
-func_alloc malloc;
-func_dealloc free;
-
-/* return code */
-int retcode;
-int tracing;
-
-#define CELL_SEGSIZE    5000  /* # of cells in one segment */
-#define CELL_NSEGMENT   10    /* # of segments for cells */
-char *alloc_seg[CELL_NSEGMENT];
-pointer cell_seg[CELL_NSEGMENT];
-int     last_cell_seg;
-
-/* We use 4 registers. */
-pointer args;            /* register for arguments of function */
-pointer envir;           /* stack register for current environment */
-pointer code;            /* register for current code */
-pointer dump;            /* stack register for next evaluation */
-
-int interactive_repl;    /* are we in an interactive REPL? */
-
-struct cell _sink;
-pointer sink;            /* when mem. alloc. fails */
-struct cell _NIL;
-pointer NIL;             /* special cell representing empty cell */
-struct cell _HASHT;
-pointer T;               /* special cell representing #t */
-struct cell _HASHF;
-pointer F;               /* special cell representing #f */
-struct cell _EOF_OBJ;
-pointer EOF_OBJ;         /* special cell representing end-of-file object */
-pointer oblist;          /* pointer to symbol table */
-pointer global_env;      /* pointer to global environment */
-
-/* global pointers to special symbols */
-pointer LAMBDA;               /* pointer to syntax lambda */
-pointer QUOTE;           /* pointer to syntax quote */
-
-pointer QQUOTE;               /* pointer to symbol quasiquote */
-pointer UNQUOTE;         /* pointer to symbol unquote */
-pointer UNQUOTESP;       /* pointer to symbol unquote-splicing */
-pointer FEED_TO;         /* => */
-pointer COLON_HOOK;      /* *colon-hook* */
-pointer ERROR_HOOK;      /* *error-hook* */
-pointer SHARP_HOOK;  /* *sharp-hook* */
-
-pointer free_cell;       /* pointer to top of free cells */
-long    fcells;          /* # of free cells */
-
-pointer inport;
-pointer outport;
-pointer save_inport;
-pointer loadport;
+    /* arrays for segments */
+    func_alloc   malloc;
+    func_dealloc free;
+
+    /* return code */
+    int retcode;
+    int tracing;
+
+#define CELL_SEGSIZE  5000 /* # of cells in one segment */
+#define CELL_NSEGMENT 10   /* # of segments for cells */
+    char*   alloc_seg[CELL_NSEGMENT];
+    pointer cell_seg[CELL_NSEGMENT];
+    int     last_cell_seg;
+
+    /* We use 4 registers. */
+    pointer args;  /* register for arguments of function */
+    pointer envir; /* stack register for current environment */
+    pointer code;  /* register for current code */
+    pointer dump;  /* stack register for next evaluation */
+
+    int interactive_repl; /* are we in an interactive REPL? */
+
+    struct cell _sink;
+    pointer     sink; /* when mem. alloc. fails */
+    struct cell _NIL;
+    pointer     NIL; /* special cell representing empty cell */
+    struct cell _HASHT;
+    pointer     T; /* special cell representing #t */
+    struct cell _HASHF;
+    pointer     F; /* special cell representing #f */
+    struct cell _EOF_OBJ;
+    pointer     EOF_OBJ;    /* special cell representing end-of-file object */
+    pointer     oblist;     /* pointer to symbol table */
+    pointer     global_env; /* pointer to global environment */
+
+    /* global pointers to special symbols */
+    pointer LAMBDA; /* pointer to syntax lambda */
+    pointer QUOTE;  /* pointer to syntax quote */
+
+    pointer QQUOTE;     /* pointer to symbol quasiquote */
+    pointer UNQUOTE;    /* pointer to symbol unquote */
+    pointer UNQUOTESP;  /* pointer to symbol unquote-splicing */
+    pointer FEED_TO;    /* => */
+    pointer COLON_HOOK; /* *colon-hook* */
+    pointer ERROR_HOOK; /* *error-hook* */
+    pointer SHARP_HOOK; /* *sharp-hook* */
+
+    pointer free_cell; /* pointer to top of free cells */
+    long    fcells;    /* # of free cells */
+
+    pointer inport;
+    pointer outport;
+    pointer save_inport;
+    pointer loadport;
 
 #define MAXFIL 64
-port load_stack[MAXFIL];     /* Stack of open files for port -1 (LOADing) */
-int nesting_stack[MAXFIL];
-int file_i;
-int nesting;
+    port load_stack[MAXFIL]; /* Stack of open files for port -1 (LOADing) */
+    int  nesting_stack[MAXFIL];
+    int  file_i;
+    int  nesting;
 
-char    gc_verbose;      /* if gc_verbose is not zero, print gc status */
-char    no_memory;       /* Whether mem. alloc. has failed */
+    char gc_verbose; /* if gc_verbose is not zero, print gc status */
+    char no_memory;  /* Whether mem. alloc. has failed */
 
 #define LINESIZE 1024
-char    linebuff[LINESIZE];
-char    strbuff[256];
+    char linebuff[LINESIZE];
+    char strbuff[256];
 
-FILE *tmpfp;
-int tok;
-int print_flag;
-pointer value;
-int op;
+    FILE*   tmpfp;
+    int     tok;
+    int     print_flag;
+    pointer value;
+    int     op;
 
-void *ext_data;     /* For the benefit of foreign functions */
-long gensym_cnt;
+    void* ext_data; /* For the benefit of foreign functions */
+    long  gensym_cnt;
 
-struct scheme_interface *vptr;
-void *dump_base;	 /* pointer to base of allocated dump stack */
-int dump_size;		 /* number of frames allocated for dump stack */
+    struct scheme_interface* vptr;
+    void*                    dump_base; /* pointer to base of allocated dump stack */
+    int                      dump_size; /* number of frames allocated for dump stack */
 };
 
 /* operator code */
-enum scheme_opcodes { 
-#define _OP_DEF(A,B,C,D,E,OP) OP, 
-#include "opdefines.h" 
-  OP_MAXDEFINED 
-}; 
-
+enum scheme_opcodes {
+#define _OP_DEF(A, B, C, D, E, OP) OP,
+#include "opdefines.h"
+    OP_MAXDEFINED
+};
 
-#define cons(sc,a,b) _cons(sc,a,b,0)
-#define immutable_cons(sc,a,b) _cons(sc,a,b,1)
+#define cons(sc, a, b)           _cons(sc, a, b, 0)
+#define immutable_cons(sc, a, b) _cons(sc, a, b, 1)
 
-int is_string(pointer p);
-char *string_value(pointer p);
-int is_number(pointer p);
-num nvalue(pointer p);
-long ivalue(pointer p);
+int    is_string(pointer p);
+char*  string_value(pointer p);
+int    is_number(pointer p);
+num    nvalue(pointer p);
+long   ivalue(pointer p);
 double rvalue(pointer p);
-int is_integer(pointer p);
-int is_real(pointer p);
-int is_character(pointer p);
-long charvalue(pointer p);
-int is_vector(pointer p);
+int    is_integer(pointer p);
+int    is_real(pointer p);
+int    is_character(pointer p);
+long   charvalue(pointer p);
+int    is_vector(pointer p);
 
 int is_port(pointer p);
 
-int is_pair(pointer p);
+int     is_pair(pointer p);
 pointer pair_car(pointer p);
 pointer pair_cdr(pointer p);
 pointer set_car(pointer p, pointer q);
 pointer set_cdr(pointer p, pointer q);
 
-int is_symbol(pointer p);
-char *symname(pointer p);
-int hasprop(pointer p);
+int   is_symbol(pointer p);
+char* symname(pointer p);
+int   hasprop(pointer p);
 
-int is_syntax(pointer p);
-int is_proc(pointer p);
-int is_foreign(pointer p);
-char *syntaxname(pointer p);
-int is_closure(pointer p);
+int   is_syntax(pointer p);
+int   is_proc(pointer p);
+int   is_foreign(pointer p);
+char* syntaxname(pointer p);
+int   is_closure(pointer p);
 #ifdef USE_MACRO
 int is_macro(pointer p);
 #endif
 pointer closure_code(pointer p);
 pointer closure_env(pointer p);
 
-int is_continuation(pointer p);
-int is_promise(pointer p);
-int is_environment(pointer p);
-int is_immutable(pointer p);
+int  is_continuation(pointer p);
+int  is_promise(pointer p);
+int  is_environment(pointer p);
+int  is_immutable(pointer p);
 void setimmutable(pointer p);
 
 #endif
diff --git a/src/scheme.c b/src/scheme.c
index 51761ac..e44cf6d 100644
--- a/src/scheme.c
+++ b/src/scheme.c
@@ -26,13 +26,13 @@
 #define _SCHEME_SOURCE
 #include "scheme-private.h"
 #ifndef WIN32
-# include <unistd.h>
+#include <unistd.h>
 #endif
 #if USE_DL
-# include "dynload.h"
+#include "dynload.h"
 #endif
 #if USE_MATH
-# include <math.h>
+#include <math.h>
 #endif
 #include <limits.h>
 #include <float.h>
@@ -50,22 +50,22 @@
 /* Used for documentation purposes, to signal functions in 'interface' */
 #define INTERFACE
 
-#define TOK_EOF     (-1)
-#define TOK_LPAREN  0
-#define TOK_RPAREN  1
-#define TOK_DOT     2
-#define TOK_ATOM    3
-#define TOK_QUOTE   4
-#define TOK_COMMENT 5
-#define TOK_DQUOTE  6
-#define TOK_BQUOTE  7
-#define TOK_COMMA   8
-#define TOK_ATMARK  9
-#define TOK_SHARP   10
+#define TOK_EOF         (-1)
+#define TOK_LPAREN      0
+#define TOK_RPAREN      1
+#define TOK_DOT         2
+#define TOK_ATOM        3
+#define TOK_QUOTE       4
+#define TOK_COMMENT     5
+#define TOK_DQUOTE      6
+#define TOK_BQUOTE      7
+#define TOK_COMMA       8
+#define TOK_ATMARK      9
+#define TOK_SHARP       10
 #define TOK_SHARP_CONST 11
-#define TOK_VEC     12
+#define TOK_VEC         12
 
-# define BACKQUOTE '`'
+#define BACKQUOTE '`'
 
 /*
  *  Basic memory allocation units
@@ -79,77 +79,77 @@
 #include <stdlib.h>
 #ifndef macintosh
 #ifdef HAVE_MALLOC_H
-# include <malloc.h>
+#include <malloc.h>
 #endif
 #else
-static int stricmp(const char *s1, const char *s2)
-{
-  unsigned char c1, c2;
-  do {
-    c1 = tolower(*s1);
-    c2 = tolower(*s2);
-    if (c1 < c2)
-      return -1;
-    else if (c1 > c2)
-      return 1;
-    s1++, s2++;
-  } while (c1 != 0);
-  return 0;
+static int
+stricmp(const char* s1, const char* s2) {
+    unsigned char c1, c2;
+    do {
+        c1 = tolower(*s1);
+        c2 = tolower(*s2);
+        if (c1 < c2)
+            return -1;
+        else if (c1 > c2)
+            return 1;
+        s1++, s2++;
+    } while (c1 != 0);
+    return 0;
 }
 #endif /* macintosh */
 
 #ifndef HAVE_STRLWR
-static const char *strlwr(char *s) {
-  const char *p=s;
-  while(*s) {
-    *s=tolower((int) *s);
-    s++;
-  }
-  return p;
+static const char*
+strlwr(char* s) {
+    const char* p = s;
+    while (*s) {
+        *s = tolower((int)*s);
+        s++;
+    }
+    return p;
 }
 #endif
 
 #ifndef prompt
-# define prompt "> "
+#define prompt "> "
 #endif
 
 #ifndef InitFile
-# define InitFile "init.scm"
+#define InitFile "init.scm"
 #endif
 
 #ifndef FIRST_CELLSEGS
-# define FIRST_CELLSEGS 3
+#define FIRST_CELLSEGS 3
 #endif
 
 enum scheme_types {
-  T_STRING=1,
-  T_NUMBER=2,
-  T_SYMBOL=3,
-  T_PROC=4,
-  T_PAIR=5,
-  T_CLOSURE=6,
-  T_CONTINUATION=7,
-  T_FOREIGN=8,
-  T_CHARACTER=9,
-  T_PORT=10,
-  T_VECTOR=11,
-  T_MACRO=12,
-  T_PROMISE=13,
-  T_ENVIRONMENT=14,
-  T_LAST_SYSTEM_TYPE=14
+    T_STRING           = 1,
+    T_NUMBER           = 2,
+    T_SYMBOL           = 3,
+    T_PROC             = 4,
+    T_PAIR             = 5,
+    T_CLOSURE          = 6,
+    T_CONTINUATION     = 7,
+    T_FOREIGN          = 8,
+    T_CHARACTER        = 9,
+    T_PORT             = 10,
+    T_VECTOR           = 11,
+    T_MACRO            = 12,
+    T_PROMISE          = 13,
+    T_ENVIRONMENT      = 14,
+    T_LAST_SYSTEM_TYPE = 14
 };
 
 /* ADJ is enough slack to align cells in a TYPE_BITS-bit boundary */
-#define ADJ 32
-#define TYPE_BITS 5
-#define T_MASKTYPE      31    /* 0000000000011111 */
-#define T_SYNTAX      4096    /* 0001000000000000 */
-#define T_IMMUTABLE   8192    /* 0010000000000000 */
-#define T_ATOM       16384    /* 0100000000000000 */   /* only for gc */
-#define CLRATOM      49151    /* 1011111111111111 */   /* only for gc */
-#define MARK         32768    /* 1000000000000000 */
-#define UNMARK       32767    /* 0111111111111111 */
-
+#define ADJ         32
+#define TYPE_BITS   5
+#define T_MASKTYPE  31                           /* 0000000000011111 */
+#define T_SYNTAX    4096                         /* 0001000000000000 */
+#define T_IMMUTABLE 8192                         /* 0010000000000000 */
+#define T_ATOM      16384 /* 0100000000000000 */ /* only for gc */
+#define CLRATOM     49151 /* 1011111111111111 */ /* only for gc */
+#define MARK        32768                        /* 1000000000000000 */
+#define UNMARK      32767                        /* 0111111111111111 */
 
 static num num_add(num a, num b);
 static num num_mul(num a, num b);
@@ -173,4215 +173,4356 @@ static num num_zero;
 static num num_one;
 
 /* macros for cell operations */
-#define typeflag(p)      ((p)->_flag)
-#define type(p)          (typeflag(p)&T_MASKTYPE)
+#define typeflag(p) ((p)->_flag)
+#define type(p)     (typeflag(p) & T_MASKTYPE)
 
-INTERFACE INLINE int is_string(pointer p)     { return (type(p)==T_STRING); }
-#define strvalue(p)      ((p)->_object._string._svalue)
-#define strlength(p)        ((p)->_object._string._length)
+INTERFACE INLINE int
+is_string(pointer p) {
+    return (type(p) == T_STRING);
+}
+
+#define strvalue(p)  ((p)->_object._string._svalue)
+#define strlength(p) ((p)->_object._string._length)
+
+INTERFACE INLINE int
+is_vector(pointer p) {
+    return (type(p) == T_VECTOR);
+}
 
-INTERFACE INLINE int is_vector(pointer p)    { return (type(p)==T_VECTOR); }
-INTERFACE static void fill_vector(pointer vec, pointer obj);
+INTERFACE static void    fill_vector(pointer vec, pointer obj);
 INTERFACE static pointer vector_elem(pointer vec, int ielem);
 INTERFACE static pointer set_vector_elem(pointer vec, int ielem, pointer a);
-INTERFACE INLINE int is_number(pointer p)    { return (type(p)==T_NUMBER); }
-INTERFACE INLINE int is_integer(pointer p) { 
-  return ((p)->_object._number.is_fixnum); 
-}
-INTERFACE INLINE int is_real(pointer p) { 
-  return (!(p)->_object._number.is_fixnum); 
-}
-
-INTERFACE INLINE int is_character(pointer p) { return (type(p)==T_CHARACTER); }
-INTERFACE INLINE char *string_value(pointer p) { return strvalue(p); }
-INLINE num nvalue(pointer p)       { return ((p)->_object._number); }
-INTERFACE long ivalue(pointer p)      { return (is_integer(p)?(p)->_object._number.value.ivalue:(long)(p)->_object._number.value.rvalue); }
-INTERFACE double rvalue(pointer p)    { return (!is_integer(p)?(p)->_object._number.value.rvalue:(double)(p)->_object._number.value.ivalue); }
-#define ivalue_unchecked(p)       ((p)->_object._number.value.ivalue)
-#define rvalue_unchecked(p)       ((p)->_object._number.value.rvalue)
-#define set_integer(p)   (p)->_object._number.is_fixnum=1;
-#define set_real(p)      (p)->_object._number.is_fixnum=0;
-INTERFACE  long charvalue(pointer p)  { return ivalue_unchecked(p); }
-
-INTERFACE INLINE int is_port(pointer p)     { return (type(p)==T_PORT); }
-#define is_inport(p) (type(p)==T_PORT && p->_object._port->kind&port_input)
-#define is_outport(p) (type(p)==T_PORT && p->_object._port->kind&port_output)
-
-INTERFACE INLINE int is_pair(pointer p)     { return (type(p)==T_PAIR); }
-#define car(p)           ((p)->_object._cons._car)
-#define cdr(p)           ((p)->_object._cons._cdr)
-INTERFACE pointer pair_car(pointer p)   { return car(p); }
-INTERFACE pointer pair_cdr(pointer p)   { return cdr(p); }
-INTERFACE pointer set_car(pointer p, pointer q) { return car(p)=q; }
-INTERFACE pointer set_cdr(pointer p, pointer q) { return cdr(p)=q; }
-
-INTERFACE INLINE int is_symbol(pointer p)   { return (type(p)==T_SYMBOL); }
-INTERFACE INLINE char *symname(pointer p)   { return strvalue(car(p)); }
+
+INTERFACE INLINE int
+is_number(pointer p) {
+    return (type(p) == T_NUMBER);
+}
+
+INTERFACE INLINE int
+is_integer(pointer p) {
+    return ((p)->_object._number.is_fixnum);
+}
+
+INTERFACE INLINE int
+is_real(pointer p) {
+    return (!(p)->_object._number.is_fixnum);
+}
+
+INTERFACE INLINE int
+is_character(pointer p) {
+    return (type(p) == T_CHARACTER);
+}
+
+INTERFACE INLINE char*
+string_value(pointer p) {
+    return strvalue(p);
+}
+
+INLINE num
+nvalue(pointer p) {
+    return ((p)->_object._number);
+}
+
+INTERFACE long
+ivalue(pointer p) {
+    return (is_integer(p) ? (p)->_object._number.value.ivalue : (long)(p)->_object._number.value.rvalue);
+}
+
+INTERFACE double
+rvalue(pointer p) {
+    return (!is_integer(p) ? (p)->_object._number.value.rvalue : (double)(p)->_object._number.value.ivalue);
+}
+
+#define ivalue_unchecked(p) ((p)->_object._number.value.ivalue)
+#define rvalue_unchecked(p) ((p)->_object._number.value.rvalue)
+#define set_integer(p)      (p)->_object._number.is_fixnum = 1;
+#define set_real(p)         (p)->_object._number.is_fixnum = 0;
+
+INTERFACE long
+charvalue(pointer p) {
+    return ivalue_unchecked(p);
+}
+
+INTERFACE INLINE int
+is_port(pointer p) {
+    return (type(p) == T_PORT);
+}
+
+#define is_inport(p)  (type(p) == T_PORT && p->_object._port->kind & port_input)
+#define is_outport(p) (type(p) == T_PORT && p->_object._port->kind & port_output)
+
+INTERFACE INLINE int
+is_pair(pointer p) {
+    return (type(p) == T_PAIR);
+}
+
+#define car(p) ((p)->_object._cons._car)
+#define cdr(p) ((p)->_object._cons._cdr)
+
+INTERFACE pointer
+pair_car(pointer p) {
+    return car(p);
+}
+
+INTERFACE pointer
+pair_cdr(pointer p) {
+    return cdr(p);
+}
+
+INTERFACE pointer
+set_car(pointer p, pointer q) {
+    return car(p) = q;
+}
+
+INTERFACE pointer
+set_cdr(pointer p, pointer q) {
+    return cdr(p) = q;
+}
+
+INTERFACE INLINE int
+is_symbol(pointer p) {
+    return (type(p) == T_SYMBOL);
+}
+
+INTERFACE INLINE char*
+symname(pointer p) {
+    return strvalue(car(p));
+}
 #if USE_PLIST
-SCHEME_EXPORT INLINE int hasprop(pointer p)     { return (typeflag(p)&T_SYMBOL); }
-#define symprop(p)       cdr(p)
+SCHEME_EXPORT INLINE int
+hasprop(pointer p) {
+    return (typeflag(p) & T_SYMBOL);
+}
+
+#define symprop(p) cdr(p)
 #endif
 
-INTERFACE INLINE int is_syntax(pointer p)   { return (typeflag(p)&T_SYNTAX); }
-INTERFACE INLINE int is_proc(pointer p)     { return (type(p)==T_PROC); }
-INTERFACE INLINE int is_foreign(pointer p)  { return (type(p)==T_FOREIGN); }
-INTERFACE INLINE char *syntaxname(pointer p) { return strvalue(car(p)); }
-#define procnum(p)       ivalue(p)
-static const char *procname(pointer x);
+INTERFACE INLINE int
+is_syntax(pointer p) {
+    return (typeflag(p) & T_SYNTAX);
+}
+
+INTERFACE INLINE int
+is_proc(pointer p) {
+    return (type(p) == T_PROC);
+}
+
+INTERFACE INLINE int
+is_foreign(pointer p) {
+    return (type(p) == T_FOREIGN);
+}
+
+INTERFACE INLINE char*
+syntaxname(pointer p) {
+    return strvalue(car(p));
+}
 
-INTERFACE INLINE int is_closure(pointer p)  { return (type(p)==T_CLOSURE); }
-INTERFACE INLINE int is_macro(pointer p)    { return (type(p)==T_MACRO); }
-INTERFACE INLINE pointer closure_code(pointer p)   { return car(p); }
-INTERFACE INLINE pointer closure_env(pointer p)    { return cdr(p); }
+#define procnum(p) ivalue(p)
+static const char* procname(pointer x);
 
-INTERFACE INLINE int is_continuation(pointer p)    { return (type(p)==T_CONTINUATION); }
-#define cont_dump(p)     cdr(p)
+INTERFACE INLINE int
+is_closure(pointer p) {
+    return (type(p) == T_CLOSURE);
+}
+
+INTERFACE INLINE int
+is_macro(pointer p) {
+    return (type(p) == T_MACRO);
+}
+
+INTERFACE INLINE pointer
+closure_code(pointer p) {
+    return car(p);
+}
+
+INTERFACE INLINE pointer
+closure_env(pointer p) {
+    return cdr(p);
+}
+
+INTERFACE INLINE int
+is_continuation(pointer p) {
+    return (type(p) == T_CONTINUATION);
+}
+
+#define cont_dump(p) cdr(p)
 
 /* To do: promise should be forced ONCE only */
-INTERFACE INLINE int is_promise(pointer p)  { return (type(p)==T_PROMISE); }
+INTERFACE INLINE int
+is_promise(pointer p) {
+    return (type(p) == T_PROMISE);
+}
+
+INTERFACE INLINE int
+is_environment(pointer p) {
+    return (type(p) == T_ENVIRONMENT);
+}
 
-INTERFACE INLINE int is_environment(pointer p) { return (type(p)==T_ENVIRONMENT); }
-#define setenvironment(p)    typeflag(p) = T_ENVIRONMENT
+#define setenvironment(p) typeflag(p) = T_ENVIRONMENT
 
-#define is_atom(p)       (typeflag(p)&T_ATOM)
-#define setatom(p)       typeflag(p) |= T_ATOM
-#define clratom(p)       typeflag(p) &= CLRATOM
+#define is_atom(p) (typeflag(p) & T_ATOM)
+#define setatom(p) typeflag(p) |= T_ATOM
+#define clratom(p) typeflag(p) &= CLRATOM
 
-#define is_mark(p)       (typeflag(p)&MARK)
-#define setmark(p)       typeflag(p) |= MARK
-#define clrmark(p)       typeflag(p) &= UNMARK
+#define is_mark(p) (typeflag(p) & MARK)
+#define setmark(p) typeflag(p) |= MARK
+#define clrmark(p) typeflag(p) &= UNMARK
+
+INTERFACE INLINE int
+is_immutable(pointer p) {
+    return (typeflag(p) & T_IMMUTABLE);
+}
 
-INTERFACE INLINE int is_immutable(pointer p) { return (typeflag(p)&T_IMMUTABLE); }
 /*#define setimmutable(p)  typeflag(p) |= T_IMMUTABLE*/
-INTERFACE INLINE void setimmutable(pointer p) { typeflag(p) |= T_IMMUTABLE; }
-
-#define caar(p)          car(car(p))
-#define cadr(p)          car(cdr(p))
-#define cdar(p)          cdr(car(p))
-#define cddr(p)          cdr(cdr(p))
-#define cadar(p)         car(cdr(car(p)))
-#define caddr(p)         car(cdr(cdr(p)))
-#define cadaar(p)        car(cdr(car(car(p))))
-#define cadddr(p)        car(cdr(cdr(cdr(p))))
-#define cddddr(p)        cdr(cdr(cdr(cdr(p))))
+INTERFACE INLINE void
+setimmutable(pointer p) {
+    typeflag(p) |= T_IMMUTABLE;
+}
+
+#define caar(p)   car(car(p))
+#define cadr(p)   car(cdr(p))
+#define cdar(p)   cdr(car(p))
+#define cddr(p)   cdr(cdr(p))
+#define cadar(p)  car(cdr(car(p)))
+#define caddr(p)  car(cdr(cdr(p)))
+#define cadaar(p) car(cdr(car(car(p))))
+#define cadddr(p) car(cdr(cdr(cdr(p))))
+#define cddddr(p) cdr(cdr(cdr(cdr(p))))
 
 #if USE_CHAR_CLASSIFIERS
-static INLINE int Cisalpha(int c) { return isascii(c) && isalpha(c); }
-static INLINE int Cisdigit(int c) { return isascii(c) && isdigit(c); }
-static INLINE int Cisspace(int c) { return isascii(c) && isspace(c); }
-static INLINE int Cisupper(int c) { return isascii(c) && isupper(c); }
-static INLINE int Cislower(int c) { return isascii(c) && islower(c); }
+static INLINE int
+Cisalpha(int c) {
+    return isascii(c) && isalpha(c);
+}
+
+static INLINE int
+Cisdigit(int c) {
+    return isascii(c) && isdigit(c);
+}
+
+static INLINE int
+Cisspace(int c) {
+    return isascii(c) && isspace(c);
+}
+
+static INLINE int
+Cisupper(int c) {
+    return isascii(c) && isupper(c);
+}
+
+static INLINE int
+Cislower(int c) {
+    return isascii(c) && islower(c);
+}
 #endif
 
 #if USE_ASCII_NAMES
-static const char *charnames[32]={
- "nul",
- "soh",
- "stx",
- "etx",
- "eot",
- "enq",
- "ack",
- "bel",
- "bs",
- "ht",
- "lf",
- "vt",
- "ff",
- "cr",
- "so",
- "si",
- "dle",
- "dc1",
- "dc2",
- "dc3",
- "dc4",
- "nak",
- "syn",
- "etb",
- "can",
- "em",
- "sub",
- "esc",
- "fs",
- "gs",
- "rs",
- "us"
-};
-
-static int is_ascii_name(const char *name, int *pc) {
-  int i;
-  for(i=0; i<32; i++) {
-     if(stricmp(name,charnames[i])==0) {
-          *pc=i;
-          return 1;
-     }
-  }
-  if(stricmp(name,"del")==0) {
-     *pc=127;
-     return 1;
-  }
-  return 0;
+static const char* charnames[32] = { "nul", "soh", "stx", "etx", "eot", "enq", "ack", "bel", "bs",  "ht",  "lf",
+                                     "vt",  "ff",  "cr",  "so",  "si",  "dle", "dc1", "dc2", "dc3", "dc4", "nak",
+                                     "syn", "etb", "can", "em",  "sub", "esc", "fs",  "gs",  "rs",  "us" };
+
+static int
+is_ascii_name(const char* name, int* pc) {
+    int i;
+    for (i = 0; i < 32; i++) {
+        if (stricmp(name, charnames[i]) == 0) {
+            *pc = i;
+            return 1;
+        }
+    }
+    if (stricmp(name, "del") == 0) {
+        *pc = 127;
+        return 1;
+    }
+    return 0;
 }
 
 #endif
 
-static int file_push(scheme *sc, const char *fname);
-static void file_pop(scheme *sc);
-static int file_interactive(scheme *sc);
-static INLINE int is_one_of(char *s, int c);
-static int alloc_cellseg(scheme *sc, int n);
-static long binary_decode(const char *s);
-static INLINE pointer get_cell(scheme *sc, pointer a, pointer b);
-static pointer _get_cell(scheme *sc, pointer a, pointer b);
-static pointer get_consecutive_cells(scheme *sc, int n);
-static pointer find_consecutive_cells(scheme *sc, int n);
-static void finalize_cell(scheme *sc, pointer a);
-static int count_consecutive_cells(pointer x, int needed);
-static pointer find_slot_in_env(scheme *sc, pointer env, pointer sym, int all);
-static pointer mk_number(scheme *sc, num n);
-static pointer mk_empty_string(scheme *sc, int len, char fill);
-static char *store_string(scheme *sc, int len, const char *str, char fill);
-static pointer mk_vector(scheme *sc, int len);
-static pointer mk_atom(scheme *sc, char *q);
-static pointer mk_sharp_const(scheme *sc, char *name);
-static pointer mk_port(scheme *sc, port *p);
-static pointer port_from_filename(scheme *sc, const char *fn, int prop);
-static pointer port_from_file(scheme *sc, FILE *, int prop);
-static pointer port_from_string(scheme *sc, char *start, char *past_the_end, int prop);
-static port *port_rep_from_filename(scheme *sc, const char *fn, int prop);
-static port *port_rep_from_file(scheme *sc, FILE *, int prop);
-static port *port_rep_from_string(scheme *sc, char *start, char *past_the_end, int prop);
-static void port_close(scheme *sc, pointer p, int flag);
-static void mark(pointer a);
-static void gc(scheme *sc, pointer a, pointer b);
-static int basic_inchar(port *pt);
-static int inchar(scheme *sc);
-static void backchar(scheme *sc, int c);
-static char   *readstr_upto(scheme *sc, char *delim);
-static pointer readstrexp(scheme *sc);
-static INLINE void skipspace(scheme *sc);
-static int token(scheme *sc);
-static void printslashstring(scheme *sc, char *s, int len);
-static void atom2str(scheme *sc, pointer l, int f, char **pp, int *plen);
-static void printatom(scheme *sc, pointer l, int f);
-static pointer mk_proc(scheme *sc, enum scheme_opcodes op);
-static pointer mk_closure(scheme *sc, pointer c, pointer e);
-static pointer mk_continuation(scheme *sc, pointer d);
-static pointer reverse(scheme *sc, pointer a);
-static pointer reverse_in_place(scheme *sc, pointer term, pointer list);
-static pointer append(scheme *sc, pointer a, pointer b);
-static int list_length(scheme *sc, pointer a);
-static int eqv(pointer a, pointer b);
-static void dump_stack_mark(scheme *);
-static pointer opexe_0(scheme *sc, enum scheme_opcodes op);
-static pointer opexe_1(scheme *sc, enum scheme_opcodes op);
-static pointer opexe_2(scheme *sc, enum scheme_opcodes op);
-static pointer opexe_3(scheme *sc, enum scheme_opcodes op);
-static pointer opexe_4(scheme *sc, enum scheme_opcodes op);
-static pointer opexe_5(scheme *sc, enum scheme_opcodes op);
-static pointer opexe_6(scheme *sc, enum scheme_opcodes op);
-static void Eval_Cycle(scheme *sc, enum scheme_opcodes op);
-static void assign_syntax(scheme *sc, char *name);
-static int syntaxnum(pointer p);
-static void assign_proc(scheme *sc, enum scheme_opcodes, char *name);
-
-#define num_ivalue(n)       (n.is_fixnum?(n).value.ivalue:(long)(n).value.rvalue)
-#define num_rvalue(n)       (!n.is_fixnum?(n).value.rvalue:(double)(n).value.ivalue)
-
-static num num_add(num a, num b) {
- num ret;
- ret.is_fixnum=a.is_fixnum && b.is_fixnum;
- if(ret.is_fixnum) {
-     ret.value.ivalue= a.value.ivalue+b.value.ivalue;
- } else {
-     ret.value.rvalue=num_rvalue(a)+num_rvalue(b);
- }
- return ret;
-}
-
-static num num_mul(num a, num b) {
- num ret;
- ret.is_fixnum=a.is_fixnum && b.is_fixnum;
- if(ret.is_fixnum) {
-     ret.value.ivalue= a.value.ivalue*b.value.ivalue;
- } else {
-     ret.value.rvalue=num_rvalue(a)*num_rvalue(b);
- }
- return ret;
-}
-
-static num num_div(num a, num b) {
- num ret;
- ret.is_fixnum=a.is_fixnum && b.is_fixnum && a.value.ivalue%b.value.ivalue==0;
- if(ret.is_fixnum) {
-     ret.value.ivalue= a.value.ivalue/b.value.ivalue;
- } else {
-     ret.value.rvalue=num_rvalue(a)/num_rvalue(b);
- }
- return ret;
-}
-
-static num num_intdiv(num a, num b) {
- num ret;
- ret.is_fixnum=a.is_fixnum && b.is_fixnum;
- if(ret.is_fixnum) {
-     ret.value.ivalue= a.value.ivalue/b.value.ivalue;
- } else {
-     ret.value.rvalue=num_rvalue(a)/num_rvalue(b);
- }
- return ret;
-}
-
-static num num_sub(num a, num b) {
- num ret;
- ret.is_fixnum=a.is_fixnum && b.is_fixnum;
- if(ret.is_fixnum) {
-     ret.value.ivalue= a.value.ivalue-b.value.ivalue;
- } else {
-     ret.value.rvalue=num_rvalue(a)-num_rvalue(b);
- }
- return ret;
-}
-
-static num num_rem(num a, num b) {
- num ret;
- long e1, e2, res;
- ret.is_fixnum=a.is_fixnum && b.is_fixnum;
- e1=num_ivalue(a);
- e2=num_ivalue(b);
- res=e1%e2;
- /* modulo should have same sign as second operand */
- if (res > 0) {
-     if (e1 < 0) {
-        res -= labs(e2);
-     }
- } else if (res < 0) {
-     if (e1 > 0) {
-         res += labs(e2);
-     }
- }
- ret.value.ivalue=res;
- return ret;
-}
-
-static num num_mod(num a, num b) {
- num ret;
- long e1, e2, res;
- ret.is_fixnum=a.is_fixnum && b.is_fixnum;
- e1=num_ivalue(a);
- e2=num_ivalue(b);
- res=e1%e2;
- if(res*e2<0) {    /* modulo should have same sign as second operand */
-     e2=labs(e2);
-     if(res>0) {
-          res-=e2;
-     } else {
-          res+=e2;
-     }
- }
- ret.value.ivalue=res;
- return ret;
-}
-
-static int num_eq(num a, num b) {
- int ret;
- int is_fixnum=a.is_fixnum && b.is_fixnum;
- if(is_fixnum) {
-     ret= a.value.ivalue==b.value.ivalue;
- } else {
-     ret=num_rvalue(a)==num_rvalue(b);
- }
- return ret;
-}
-
-
-static int num_gt(num a, num b) {
- int ret;
- int is_fixnum=a.is_fixnum && b.is_fixnum;
- if(is_fixnum) {
-     ret= a.value.ivalue>b.value.ivalue;
- } else {
-     ret=num_rvalue(a)>num_rvalue(b);
- }
- return ret;
-}
-
-static int num_ge(num a, num b) {
- return !num_lt(a,b);
-}
-
-static int num_lt(num a, num b) {
- int ret;
- int is_fixnum=a.is_fixnum && b.is_fixnum;
- if(is_fixnum) {
-     ret= a.value.ivalue<b.value.ivalue;
- } else {
-     ret=num_rvalue(a)<num_rvalue(b);
- }
- return ret;
-}
-
-static int num_le(num a, num b) {
- return !num_gt(a,b);
+static int            file_push(scheme* sc, const char* fname);
+static void           file_pop(scheme* sc);
+static int            file_interactive(scheme* sc);
+static INLINE int     is_one_of(char* s, int c);
+static int            alloc_cellseg(scheme* sc, int n);
+static long           binary_decode(const char* s);
+static INLINE pointer get_cell(scheme* sc, pointer a, pointer b);
+static pointer        _get_cell(scheme* sc, pointer a, pointer b);
+static pointer        get_consecutive_cells(scheme* sc, int n);
+static pointer        find_consecutive_cells(scheme* sc, int n);
+static void           finalize_cell(scheme* sc, pointer a);
+static int            count_consecutive_cells(pointer x, int needed);
+static pointer        find_slot_in_env(scheme* sc, pointer env, pointer sym, int all);
+static pointer        mk_number(scheme* sc, num n);
+static pointer        mk_empty_string(scheme* sc, int len, char fill);
+static char*          store_string(scheme* sc, int len, const char* str, char fill);
+static pointer        mk_vector(scheme* sc, int len);
+static pointer        mk_atom(scheme* sc, char* q);
+static pointer        mk_sharp_const(scheme* sc, char* name);
+static pointer        mk_port(scheme* sc, port* p);
+static pointer        port_from_filename(scheme* sc, const char* fn, int prop);
+static pointer        port_from_file(scheme* sc, FILE*, int prop);
+static pointer        port_from_string(scheme* sc, char* start, char* past_the_end, int prop);
+static port*          port_rep_from_filename(scheme* sc, const char* fn, int prop);
+static port*          port_rep_from_file(scheme* sc, FILE*, int prop);
+static port*          port_rep_from_string(scheme* sc, char* start, char* past_the_end, int prop);
+static void           port_close(scheme* sc, pointer p, int flag);
+static void           mark(pointer a);
+static void           gc(scheme* sc, pointer a, pointer b);
+static int            basic_inchar(port* pt);
+static int            inchar(scheme* sc);
+static void           backchar(scheme* sc, int c);
+static char*          readstr_upto(scheme* sc, char* delim);
+static pointer        readstrexp(scheme* sc);
+static INLINE void    skipspace(scheme* sc);
+static int            token(scheme* sc);
+static void           printslashstring(scheme* sc, char* s, int len);
+static void           atom2str(scheme* sc, pointer l, int f, char** pp, int* plen);
+static void           printatom(scheme* sc, pointer l, int f);
+static pointer        mk_proc(scheme* sc, enum scheme_opcodes op);
+static pointer        mk_closure(scheme* sc, pointer c, pointer e);
+static pointer        mk_continuation(scheme* sc, pointer d);
+static pointer        reverse(scheme* sc, pointer a);
+static pointer        reverse_in_place(scheme* sc, pointer term, pointer list);
+static pointer        append(scheme* sc, pointer a, pointer b);
+static int            list_length(scheme* sc, pointer a);
+static int            eqv(pointer a, pointer b);
+static void           dump_stack_mark(scheme*);
+static pointer        opexe_0(scheme* sc, enum scheme_opcodes op);
+static pointer        opexe_1(scheme* sc, enum scheme_opcodes op);
+static pointer        opexe_2(scheme* sc, enum scheme_opcodes op);
+static pointer        opexe_3(scheme* sc, enum scheme_opcodes op);
+static pointer        opexe_4(scheme* sc, enum scheme_opcodes op);
+static pointer        opexe_5(scheme* sc, enum scheme_opcodes op);
+static pointer        opexe_6(scheme* sc, enum scheme_opcodes op);
+static void           Eval_Cycle(scheme* sc, enum scheme_opcodes op);
+static void           assign_syntax(scheme* sc, char* name);
+static int            syntaxnum(pointer p);
+static void           assign_proc(scheme* sc, enum scheme_opcodes, char* name);
+
+#define num_ivalue(n) (n.is_fixnum ? (n).value.ivalue : (long)(n).value.rvalue)
+#define num_rvalue(n) (!n.is_fixnum ? (n).value.rvalue : (double)(n).value.ivalue)
+
+static num
+num_add(num a, num b) {
+    num ret;
+    ret.is_fixnum = a.is_fixnum && b.is_fixnum;
+    if (ret.is_fixnum) {
+        ret.value.ivalue = a.value.ivalue + b.value.ivalue;
+    } else {
+        ret.value.rvalue = num_rvalue(a) + num_rvalue(b);
+    }
+    return ret;
+}
+
+static num
+num_mul(num a, num b) {
+    num ret;
+    ret.is_fixnum = a.is_fixnum && b.is_fixnum;
+    if (ret.is_fixnum) {
+        ret.value.ivalue = a.value.ivalue * b.value.ivalue;
+    } else {
+        ret.value.rvalue = num_rvalue(a) * num_rvalue(b);
+    }
+    return ret;
+}
+
+static num
+num_div(num a, num b) {
+    num ret;
+    ret.is_fixnum = a.is_fixnum && b.is_fixnum && a.value.ivalue % b.value.ivalue == 0;
+    if (ret.is_fixnum) {
+        ret.value.ivalue = a.value.ivalue / b.value.ivalue;
+    } else {
+        ret.value.rvalue = num_rvalue(a) / num_rvalue(b);
+    }
+    return ret;
+}
+
+static num
+num_intdiv(num a, num b) {
+    num ret;
+    ret.is_fixnum = a.is_fixnum && b.is_fixnum;
+    if (ret.is_fixnum) {
+        ret.value.ivalue = a.value.ivalue / b.value.ivalue;
+    } else {
+        ret.value.rvalue = num_rvalue(a) / num_rvalue(b);
+    }
+    return ret;
+}
+
+static num
+num_sub(num a, num b) {
+    num ret;
+    ret.is_fixnum = a.is_fixnum && b.is_fixnum;
+    if (ret.is_fixnum) {
+        ret.value.ivalue = a.value.ivalue - b.value.ivalue;
+    } else {
+        ret.value.rvalue = num_rvalue(a) - num_rvalue(b);
+    }
+    return ret;
+}
+
+static num
+num_rem(num a, num b) {
+    num  ret;
+    long e1, e2, res;
+    ret.is_fixnum = a.is_fixnum && b.is_fixnum;
+    e1            = num_ivalue(a);
+    e2            = num_ivalue(b);
+    res           = e1 % e2;
+    /* modulo should have same sign as second operand */
+    if (res > 0) {
+        if (e1 < 0) {
+            res -= labs(e2);
+        }
+    } else if (res < 0) {
+        if (e1 > 0) {
+            res += labs(e2);
+        }
+    }
+    ret.value.ivalue = res;
+    return ret;
+}
+
+static num
+num_mod(num a, num b) {
+    num  ret;
+    long e1, e2, res;
+    ret.is_fixnum = a.is_fixnum && b.is_fixnum;
+    e1            = num_ivalue(a);
+    e2            = num_ivalue(b);
+    res           = e1 % e2;
+    if (res * e2 < 0) { /* modulo should have same sign as second operand */
+        e2 = labs(e2);
+        if (res > 0) {
+            res -= e2;
+        } else {
+            res += e2;
+        }
+    }
+    ret.value.ivalue = res;
+    return ret;
+}
+
+static int
+num_eq(num a, num b) {
+    int ret;
+    int is_fixnum = a.is_fixnum && b.is_fixnum;
+    if (is_fixnum) {
+        ret = a.value.ivalue == b.value.ivalue;
+    } else {
+        ret = num_rvalue(a) == num_rvalue(b);
+    }
+    return ret;
+}
+
+static int
+num_gt(num a, num b) {
+    int ret;
+    int is_fixnum = a.is_fixnum && b.is_fixnum;
+    if (is_fixnum) {
+        ret = a.value.ivalue > b.value.ivalue;
+    } else {
+        ret = num_rvalue(a) > num_rvalue(b);
+    }
+    return ret;
+}
+
+static int
+num_ge(num a, num b) {
+    return !num_lt(a, b);
+}
+
+static int
+num_lt(num a, num b) {
+    int ret;
+    int is_fixnum = a.is_fixnum && b.is_fixnum;
+    if (is_fixnum) {
+        ret = a.value.ivalue < b.value.ivalue;
+    } else {
+        ret = num_rvalue(a) < num_rvalue(b);
+    }
+    return ret;
+}
+
+static int
+num_le(num a, num b) {
+    return !num_gt(a, b);
 }
 
 #if USE_MATH
 /* Round to nearest. Round to even if midway */
-static double round_per_R5RS(double x) {
- double fl=floor(x);
- double ce=ceil(x);
- double dfl=x-fl;
- double dce=ce-x;
- if(dfl>dce) {
-     return ce;
- } else if(dfl<dce) {
-     return fl;
- } else {
-     if(fmod(fl,2.0)==0.0) {       /* I imagine this holds */
-          return fl;
-     } else {
-          return ce;
-     }
- }
+static double
+round_per_R5RS(double x) {
+    double fl  = floor(x);
+    double ce  = ceil(x);
+    double dfl = x - fl;
+    double dce = ce - x;
+    if (dfl > dce) {
+        return ce;
+    } else if (dfl < dce) {
+        return fl;
+    } else {
+        if (fmod(fl, 2.0) == 0.0) { /* I imagine this holds */
+            return fl;
+        } else {
+            return ce;
+        }
+    }
 }
 #endif
 
-static int is_zero_double(double x) {
- return x<DBL_MIN && x>-DBL_MIN;
+static int
+is_zero_double(double x) {
+    return x < DBL_MIN && x > -DBL_MIN;
 }
 
-static long binary_decode(const char *s) {
- long x=0;
+static long
+binary_decode(const char* s) {
+    long x = 0;
 
- while(*s!=0 && (*s=='1' || *s=='0')) {
-     x<<=1;
-     x+=*s-'0';
-     s++;
- }
+    while (*s != 0 && (*s == '1' || *s == '0')) {
+        x <<= 1;
+        x += *s - '0';
+        s++;
+    }
 
- return x;
+    return x;
 }
 
 /* allocate new cell segment */
-static int alloc_cellseg(scheme *sc, int n) {
-     pointer newp;
-     pointer last;
-     pointer p;
-     char *cp;
-     long i;
-     int k;
-     size_t adj=ADJ;
-
-     if(adj<sizeof(struct cell)) {
-       adj=sizeof(struct cell);
-     }
-
-     for (k = 0; k < n; k++) {
-          if (sc->last_cell_seg >= CELL_NSEGMENT - 1)
-               return k;
-          cp = (char*) sc->malloc(CELL_SEGSIZE * sizeof(struct cell)+adj);
-          if (cp == 0)
-               return k;
-	  i = ++sc->last_cell_seg ;
-	  sc->alloc_seg[i] = cp;
-	  /* adjust in TYPE_BITS-bit boundary */
-	  /* Check that the casting below is safe. */
-	  static_assert(sizeof(size_t) == sizeof(cp),
-	                "Can't cast pointer to size_t.");
-	  if((size_t)cp%adj!=0) {
-	    cp=(char*)(adj*((size_t)cp/adj+1));
-	  }
+static int
+alloc_cellseg(scheme* sc, int n) {
+    pointer newp;
+    pointer last;
+    pointer p;
+    char*   cp;
+    long    i;
+    int     k;
+    size_t  adj = ADJ;
+
+    if (adj < sizeof(struct cell)) {
+        adj = sizeof(struct cell);
+    }
+
+    for (k = 0; k < n; k++) {
+        if (sc->last_cell_seg >= CELL_NSEGMENT - 1)
+            return k;
+        cp = (char*)sc->malloc(CELL_SEGSIZE * sizeof(struct cell) + adj);
+        if (cp == 0)
+            return k;
+        i                = ++sc->last_cell_seg;
+        sc->alloc_seg[i] = cp;
+        /* adjust in TYPE_BITS-bit boundary */
+        /* Check that the casting below is safe. */
+        static_assert(sizeof(size_t) == sizeof(cp), "Can't cast pointer to size_t.");
+        if ((size_t)cp % adj != 0) {
+            cp = (char*)(adj * ((size_t)cp / adj + 1));
+        }
         /* insert new segment in address order */
-	  newp=(pointer)cp;
+        newp            = (pointer)cp;
         sc->cell_seg[i] = newp;
         while (i > 0 && sc->cell_seg[i - 1] > sc->cell_seg[i]) {
-              p = sc->cell_seg[i];
-            sc->cell_seg[i] = sc->cell_seg[i - 1];
+            p                 = sc->cell_seg[i];
+            sc->cell_seg[i]   = sc->cell_seg[i - 1];
             sc->cell_seg[--i] = p;
         }
-          sc->fcells += CELL_SEGSIZE;
+        sc->fcells += CELL_SEGSIZE;
         last = newp + CELL_SEGSIZE - 1;
-          for (p = newp; p <= last; p++) {
-               typeflag(p) = 0;
-               cdr(p) = p + 1;
-               car(p) = sc->NIL;
-          }
+        for (p = newp; p <= last; p++) {
+            typeflag(p) = 0;
+            cdr(p)      = p + 1;
+            car(p)      = sc->NIL;
+        }
         /* insert new cells in address order on free list */
         if (sc->free_cell == sc->NIL || p < sc->free_cell) {
-             cdr(last) = sc->free_cell;
-             sc->free_cell = newp;
+            cdr(last)     = sc->free_cell;
+            sc->free_cell = newp;
         } else {
-              p = sc->free_cell;
-              while (cdr(p) != sc->NIL && newp > cdr(p))
-                   p = cdr(p);
-              cdr(last) = cdr(p);
-              cdr(p) = newp;
+            p = sc->free_cell;
+            while (cdr(p) != sc->NIL && newp > cdr(p))
+                p = cdr(p);
+            cdr(last) = cdr(p);
+            cdr(p)    = newp;
         }
-     }
-     return n;
+    }
+    return n;
 }
 
-static INLINE pointer get_cell(scheme *sc, pointer a, pointer b) {
-  if (sc->free_cell != sc->NIL) {
-    pointer x = sc->free_cell;
+static INLINE pointer
+get_cell(scheme* sc, pointer a, pointer b) {
+    if (sc->free_cell != sc->NIL) {
+        pointer x     = sc->free_cell;
+        sc->free_cell = cdr(x);
+        --sc->fcells;
+        return (x);
+    }
+    return _get_cell(sc, a, b);
+}
+
+/* get new cell.  parameter a, b is marked by gc. */
+static pointer
+_get_cell(scheme* sc, pointer a, pointer b) {
+    pointer x;
+
+    if (sc->no_memory) {
+        return sc->sink;
+    }
+
+    if (sc->free_cell == sc->NIL) {
+        gc(sc, a, b);
+        if (sc->fcells < sc->last_cell_seg * 8 || sc->free_cell == sc->NIL) {
+            /* if only a few recovered, get more to avoid fruitless gc's */
+            if (!alloc_cellseg(sc, 1) && sc->free_cell == sc->NIL) {
+                sc->no_memory = 1;
+                return sc->sink;
+            }
+        }
+    }
+    x             = sc->free_cell;
     sc->free_cell = cdr(x);
     --sc->fcells;
     return (x);
-  } 
-  return _get_cell (sc, a, b);
 }
 
+static pointer
+get_consecutive_cells(scheme* sc, int n) {
+    pointer x;
 
-/* get new cell.  parameter a, b is marked by gc. */
-static pointer _get_cell(scheme *sc, pointer a, pointer b) {
-  pointer x;
-
-  if(sc->no_memory) {
-    return sc->sink;
-  }
-  
-  if (sc->free_cell == sc->NIL) {
-    gc(sc,a, b);
-    if (sc->fcells < sc->last_cell_seg*8
-	|| sc->free_cell == sc->NIL) {
-      /* if only a few recovered, get more to avoid fruitless gc's */
-      if (!alloc_cellseg(sc,1) && sc->free_cell == sc->NIL) {
-	sc->no_memory=1;
-	return sc->sink;
-      }
+    if (sc->no_memory) {
+        return sc->sink;
     }
-  }
-  x = sc->free_cell;
-  sc->free_cell = cdr(x);
-  --sc->fcells;
-  return (x);
-}
-
-static pointer get_consecutive_cells(scheme *sc, int n) {
-  pointer x;
-
-  if(sc->no_memory) {
-    return sc->sink;
-  }
-  
-  /* Are there any cells available? */
-  x=find_consecutive_cells(sc,n);
-  if (x == sc->NIL) {
-    /* If not, try gc'ing some */
-    gc(sc, sc->NIL, sc->NIL);
-    x=find_consecutive_cells(sc,n);
+
+    /* Are there any cells available? */
+    x = find_consecutive_cells(sc, n);
     if (x == sc->NIL) {
-      /* If there still aren't, try getting more heap */
-      if (!alloc_cellseg(sc,1)) {
-	sc->no_memory=1;
-	return sc->sink;
-      }
+        /* If not, try gc'ing some */
+        gc(sc, sc->NIL, sc->NIL);
+        x = find_consecutive_cells(sc, n);
+        if (x == sc->NIL) {
+            /* If there still aren't, try getting more heap */
+            if (!alloc_cellseg(sc, 1)) {
+                sc->no_memory = 1;
+                return sc->sink;
+            }
+        }
+        x = find_consecutive_cells(sc, n);
+        if (x == sc->NIL) {
+            /* If all fail, report failure */
+            sc->no_memory = 1;
+            return sc->sink;
+        }
     }
-    x=find_consecutive_cells(sc,n);
-    if (x == sc->NIL) {
-      /* If all fail, report failure */
-      sc->no_memory=1;
-      return sc->sink;
+    return (x);
+}
+
+static int
+count_consecutive_cells(pointer x, int needed) {
+    int n = 1;
+    while (cdr(x) == x + 1) {
+        x = cdr(x);
+        n++;
+        if (n > needed)
+            return n;
     }
-  }
-  return (x);
-}
-
-static int count_consecutive_cells(pointer x, int needed) {
- int n=1;
- while(cdr(x)==x+1) {
-     x=cdr(x);
-     n++;
-     if(n>needed) return n;
- }
- return n;
-}
-
-static pointer find_consecutive_cells(scheme *sc, int n) {
-  pointer *pp;
-  int cnt;
-  
-  pp=&sc->free_cell;
-  while(*pp!=sc->NIL) {
-    cnt=count_consecutive_cells(*pp,n);
-    if(cnt>=n) {
-      pointer x=*pp;
-      *pp=cdr(*pp+n-1);
-      sc->fcells -= n;
-      return x;
+    return n;
+}
+
+static pointer
+find_consecutive_cells(scheme* sc, int n) {
+    pointer* pp;
+    int      cnt;
+
+    pp = &sc->free_cell;
+    while (*pp != sc->NIL) {
+        cnt = count_consecutive_cells(*pp, n);
+        if (cnt >= n) {
+            pointer x = *pp;
+            *pp       = cdr(*pp + n - 1);
+            sc->fcells -= n;
+            return x;
+        }
+        pp = &cdr(*pp + cnt - 1);
     }
-    pp=&cdr(*pp+cnt-1);
-  }
-  return sc->NIL;
+    return sc->NIL;
 }
 
 /* get new cons cell */
-pointer _cons(scheme *sc, pointer a, pointer b, int immutable) {
-  pointer x = get_cell(sc,a, b);
-
-  typeflag(x) = T_PAIR;
-  if(immutable) {
-    setimmutable(x);
-  }
-  car(x) = a;
-  cdr(x) = b;
-  return (x);
-}
-
-/* ========== oblist implementation  ========== */ 
-
-#ifndef USE_OBJECT_LIST 
-
-static int hash_fn(const char *key, int table_size); 
-
-static pointer oblist_initial_value(scheme *sc) 
-{ 
-  return mk_vector(sc, 461); /* probably should be bigger */ 
-} 
-
-/* returns the new symbol */ 
-static pointer oblist_add_by_name(scheme *sc, const char *name) 
-{ 
-  pointer x; 
-  int location; 
-
-  x = immutable_cons(sc, mk_string(sc, name), sc->NIL); 
-  typeflag(x) = T_SYMBOL; 
-  setimmutable(car(x)); 
-
-  location = hash_fn(name, ivalue_unchecked(sc->oblist)); 
-  set_vector_elem(sc->oblist, location, 
-                  immutable_cons(sc, x, vector_elem(sc->oblist, location))); 
-  return x; 
-} 
-
-static INLINE pointer oblist_find_by_name(scheme *sc, const char *name) 
-{ 
-  int location; 
-  pointer x; 
-  char *s; 
-
-  location = hash_fn(name, ivalue_unchecked(sc->oblist)); 
-  for (x = vector_elem(sc->oblist, location); x != sc->NIL; x = cdr(x)) { 
-    s = symname(car(x)); 
-    /* case-insensitive, per R5RS section 2. */ 
-    if(stricmp(name, s) == 0) { 
-      return car(x); 
-    } 
-  } 
-  return sc->NIL; 
-} 
-
-static pointer oblist_all_symbols(scheme *sc) 
-{ 
-  int i; 
-  pointer x; 
-  pointer ob_list = sc->NIL; 
-
-  for (i = 0; i < ivalue_unchecked(sc->oblist); i++) { 
-    for (x  = vector_elem(sc->oblist, i); x != sc->NIL; x = cdr(x)) { 
-      ob_list = cons(sc, x, ob_list); 
-    } 
-  } 
-  return ob_list; 
-} 
-
-#else 
-
-static pointer oblist_initial_value(scheme *sc) 
-{ 
-  return sc->NIL; 
-} 
-
-static INLINE pointer oblist_find_by_name(scheme *sc, const char *name) 
-{ 
-     pointer x; 
-     char    *s; 
-
-     for (x = sc->oblist; x != sc->NIL; x = cdr(x)) { 
-        s = symname(car(x)); 
-        /* case-insensitive, per R5RS section 2. */ 
-        if(stricmp(name, s) == 0) { 
-          return car(x); 
-        } 
-     } 
-     return sc->NIL; 
-} 
-
-/* returns the new symbol */ 
-static pointer oblist_add_by_name(scheme *sc, const char *name) 
-{ 
-  pointer x; 
-
-  x = immutable_cons(sc, mk_string(sc, name), sc->NIL); 
-  typeflag(x) = T_SYMBOL; 
-  setimmutable(car(x)); 
-  sc->oblist = immutable_cons(sc, x, sc->oblist); 
-  return x; 
-} 
-static pointer oblist_all_symbols(scheme *sc) 
-{ 
-  return sc->oblist; 
-} 
-
-#endif 
-
-static pointer mk_port(scheme *sc, port *p) {
-  pointer x = get_cell(sc, sc->NIL, sc->NIL);
-  
-  typeflag(x) = T_PORT|T_ATOM;
-  x->_object._port=p;
-  return (x);
-}
-
-pointer mk_foreign_func(scheme *sc, foreign_func f) {
-  pointer x = get_cell(sc, sc->NIL, sc->NIL);
-  
-  typeflag(x) = (T_FOREIGN | T_ATOM);
-  x->_object._ff=f;
-  return (x);
-}
-
-INTERFACE pointer mk_character(scheme *sc, int c) {
-  pointer x = get_cell(sc,sc->NIL, sc->NIL);
-
-  typeflag(x) = (T_CHARACTER | T_ATOM);
-  ivalue_unchecked(x)= c;
-  set_integer(x);
-  return (x);
+pointer
+_cons(scheme* sc, pointer a, pointer b, int immutable) {
+    pointer x = get_cell(sc, a, b);
+
+    typeflag(x) = T_PAIR;
+    if (immutable) {
+        setimmutable(x);
+    }
+    car(x) = a;
+    cdr(x) = b;
+    return (x);
+}
+
+/* ========== oblist implementation  ========== */
+
+#ifndef USE_OBJECT_LIST
+
+static int hash_fn(const char* key, int table_size);
+
+static pointer
+oblist_initial_value(scheme* sc) {
+    return mk_vector(sc, 461); /* probably should be bigger */
+}
+
+/* returns the new symbol */
+static pointer
+oblist_add_by_name(scheme* sc, const char* name) {
+    pointer x;
+    int     location;
+
+    x           = immutable_cons(sc, mk_string(sc, name), sc->NIL);
+    typeflag(x) = T_SYMBOL;
+    setimmutable(car(x));
+
+    location = hash_fn(name, ivalue_unchecked(sc->oblist));
+    set_vector_elem(sc->oblist, location, immutable_cons(sc, x, vector_elem(sc->oblist, location)));
+    return x;
+}
+
+static INLINE pointer
+oblist_find_by_name(scheme* sc, const char* name) {
+    int     location;
+    pointer x;
+    char*   s;
+
+    location = hash_fn(name, ivalue_unchecked(sc->oblist));
+    for (x = vector_elem(sc->oblist, location); x != sc->NIL; x = cdr(x)) {
+        s = symname(car(x));
+        /* case-insensitive, per R5RS section 2. */
+        if (stricmp(name, s) == 0) {
+            return car(x);
+        }
+    }
+    return sc->NIL;
+}
+
+static pointer
+oblist_all_symbols(scheme* sc) {
+    int     i;
+    pointer x;
+    pointer ob_list = sc->NIL;
+
+    for (i = 0; i < ivalue_unchecked(sc->oblist); i++) {
+        for (x = vector_elem(sc->oblist, i); x != sc->NIL; x = cdr(x)) {
+            ob_list = cons(sc, x, ob_list);
+        }
+    }
+    return ob_list;
+}
+
+#else
+
+static pointer
+oblist_initial_value(scheme* sc) {
+    return sc->NIL;
+}
+
+static INLINE pointer
+oblist_find_by_name(scheme* sc, const char* name) {
+    pointer x;
+    char*   s;
+
+    for (x = sc->oblist; x != sc->NIL; x = cdr(x)) {
+        s = symname(car(x));
+        /* case-insensitive, per R5RS section 2. */
+        if (stricmp(name, s) == 0) {
+            return car(x);
+        }
+    }
+    return sc->NIL;
+}
+
+/* returns the new symbol */
+static pointer
+oblist_add_by_name(scheme* sc, const char* name) {
+    pointer x;
+
+    x           = immutable_cons(sc, mk_string(sc, name), sc->NIL);
+    typeflag(x) = T_SYMBOL;
+    setimmutable(car(x));
+    sc->oblist = immutable_cons(sc, x, sc->oblist);
+    return x;
+}
+
+static pointer
+oblist_all_symbols(scheme* sc) {
+    return sc->oblist;
+}
+
+#endif
+
+static pointer
+mk_port(scheme* sc, port* p) {
+    pointer x = get_cell(sc, sc->NIL, sc->NIL);
+
+    typeflag(x)      = T_PORT | T_ATOM;
+    x->_object._port = p;
+    return (x);
+}
+
+pointer
+mk_foreign_func(scheme* sc, foreign_func f) {
+    pointer x = get_cell(sc, sc->NIL, sc->NIL);
+
+    typeflag(x)    = (T_FOREIGN | T_ATOM);
+    x->_object._ff = f;
+    return (x);
+}
+
+INTERFACE pointer
+mk_character(scheme* sc, int c) {
+    pointer x = get_cell(sc, sc->NIL, sc->NIL);
+
+    typeflag(x)         = (T_CHARACTER | T_ATOM);
+    ivalue_unchecked(x) = c;
+    set_integer(x);
+    return (x);
 }
 
 /* get number atom (integer) */
-INTERFACE pointer mk_integer(scheme *sc, long num) {
-  pointer x = get_cell(sc,sc->NIL, sc->NIL);
+INTERFACE pointer
+mk_integer(scheme* sc, long num) {
+    pointer x = get_cell(sc, sc->NIL, sc->NIL);
 
-  typeflag(x) = (T_NUMBER | T_ATOM);
-  ivalue_unchecked(x)= num;
-  set_integer(x);
-  return (x);
+    typeflag(x)         = (T_NUMBER | T_ATOM);
+    ivalue_unchecked(x) = num;
+    set_integer(x);
+    return (x);
 }
 
-INTERFACE pointer mk_real(scheme *sc, double n) {
-  pointer x = get_cell(sc,sc->NIL, sc->NIL);
+INTERFACE pointer
+mk_real(scheme* sc, double n) {
+    pointer x = get_cell(sc, sc->NIL, sc->NIL);
 
-  typeflag(x) = (T_NUMBER | T_ATOM);
-  rvalue_unchecked(x)= n;
-  set_real(x);
-  return (x);
+    typeflag(x)         = (T_NUMBER | T_ATOM);
+    rvalue_unchecked(x) = n;
+    set_real(x);
+    return (x);
 }
 
-static pointer mk_number(scheme *sc, num n) {
- if(n.is_fixnum) {
-     return mk_integer(sc,n.value.ivalue);
- } else {
-     return mk_real(sc,n.value.rvalue);
- }
+static pointer
+mk_number(scheme* sc, num n) {
+    if (n.is_fixnum) {
+        return mk_integer(sc, n.value.ivalue);
+    } else {
+        return mk_real(sc, n.value.rvalue);
+    }
 }
 
 /* allocate name to string area */
-static char *store_string(scheme *sc, int len_str, const char *str, char fill) {
-     char *q;
-     
-     q=(char*)sc->malloc(len_str+1);
-     if(q==0) {
-          sc->no_memory=1;
-          return sc->strbuff;
-     }
-     if(str!=0) {
-          strcpy(q, str);
-     } else {
-          memset(q, fill, len_str);
-          q[len_str]=0;
-     }
-     return (q);
+static char*
+store_string(scheme* sc, int len_str, const char* str, char fill) {
+    char* q;
+
+    q = (char*)sc->malloc(len_str + 1);
+    if (q == 0) {
+        sc->no_memory = 1;
+        return sc->strbuff;
+    }
+    if (str != 0) {
+        strcpy(q, str);
+    } else {
+        memset(q, fill, len_str);
+        q[len_str] = 0;
+    }
+    return (q);
 }
 
 /* get new string */
-INTERFACE pointer mk_string(scheme *sc, const char *str) {
-     return mk_counted_string(sc,str,strlen(str));
+INTERFACE pointer
+mk_string(scheme* sc, const char* str) {
+    return mk_counted_string(sc, str, strlen(str));
 }
 
-INTERFACE pointer mk_counted_string(scheme *sc, const char *str, int len) {
-     pointer x = get_cell(sc, sc->NIL, sc->NIL);
+INTERFACE pointer
+mk_counted_string(scheme* sc, const char* str, int len) {
+    pointer x = get_cell(sc, sc->NIL, sc->NIL);
 
-     strvalue(x) = store_string(sc,len,str,0);
-     typeflag(x) = (T_STRING | T_ATOM);
-     strlength(x) = len;
-     return (x);
+    strvalue(x)  = store_string(sc, len, str, 0);
+    typeflag(x)  = (T_STRING | T_ATOM);
+    strlength(x) = len;
+    return (x);
 }
 
-static pointer mk_empty_string(scheme *sc, int len, char fill) {
-     pointer x = get_cell(sc, sc->NIL, sc->NIL);
+static pointer
+mk_empty_string(scheme* sc, int len, char fill) {
+    pointer x = get_cell(sc, sc->NIL, sc->NIL);
 
-     strvalue(x) = store_string(sc,len,0,fill);
-     typeflag(x) = (T_STRING | T_ATOM);
-     strlength(x) = len;
-     return (x);
+    strvalue(x)  = store_string(sc, len, 0, fill);
+    typeflag(x)  = (T_STRING | T_ATOM);
+    strlength(x) = len;
+    return (x);
+}
+
+INTERFACE static pointer
+mk_vector(scheme* sc, int len) {
+    pointer x           = get_consecutive_cells(sc, len / 2 + len % 2 + 1);
+    typeflag(x)         = (T_VECTOR | T_ATOM);
+    ivalue_unchecked(x) = len;
+    set_integer(x);
+    fill_vector(x, sc->NIL);
+    return x;
+}
+
+INTERFACE static void
+fill_vector(pointer vec, pointer obj) {
+    int i;
+    int num = ivalue(vec) / 2 + ivalue(vec) % 2;
+    for (i = 0; i < num; i++) {
+        typeflag(vec + 1 + i) = T_PAIR;
+        setimmutable(vec + 1 + i);
+        car(vec + 1 + i) = obj;
+        cdr(vec + 1 + i) = obj;
+    }
+}
+
+INTERFACE static pointer
+vector_elem(pointer vec, int ielem) {
+    int n = ielem / 2;
+    if (ielem % 2 == 0) {
+        return car(vec + 1 + n);
+    } else {
+        return cdr(vec + 1 + n);
+    }
+}
+
+INTERFACE static pointer
+set_vector_elem(pointer vec, int ielem, pointer a) {
+    int n = ielem / 2;
+    if (ielem % 2 == 0) {
+        return car(vec + 1 + n) = a;
+    } else {
+        return cdr(vec + 1 + n) = a;
+    }
+}
+
+/* get new symbol */
+INTERFACE pointer
+mk_symbol(scheme* sc, const char* name) {
+    pointer x;
+
+    /* first check oblist */
+    x = oblist_find_by_name(sc, name);
+    if (x != sc->NIL) {
+        return (x);
+    } else {
+        x = oblist_add_by_name(sc, name);
+        return (x);
+    }
+}
+
+INTERFACE pointer
+gensym(scheme* sc) {
+    pointer x;
+    char    name[40];
+
+    for (; sc->gensym_cnt < LONG_MAX; sc->gensym_cnt++) {
+        sprintf(name, "gensym-%ld", sc->gensym_cnt);
+
+        /* first check oblist */
+        x = oblist_find_by_name(sc, name);
+
+        if (x != sc->NIL) {
+            continue;
+        } else {
+            x = oblist_add_by_name(sc, name);
+            return (x);
+        }
+    }
+
+    return sc->NIL;
+}
+
+/* make symbol or number atom from string */
+static pointer
+mk_atom(scheme* sc, char* q) {
+    char c, *p;
+    int  has_dec_point = 0;
+    int  has_fp_exp    = 0;
+
+#if USE_COLON_HOOK
+    if ((p = strstr(q, "::")) != 0) {
+        *p = 0;
+        return cons(
+            sc, sc->COLON_HOOK,
+            cons(
+                sc, cons(sc, sc->QUOTE, cons(sc, mk_atom(sc, p + 2), sc->NIL)),
+                cons(sc, mk_symbol(sc, strlwr(q)), sc->NIL)
+            )
+        );
+    }
+#endif
+
+    p = q;
+    c = *p++;
+    if ((c == '+') || (c == '-')) {
+        c = *p++;
+        if (c == '.') {
+            has_dec_point = 1;
+            c             = *p++;
+        }
+        if (!isdigit((int)c)) {
+            return (mk_symbol(sc, strlwr(q)));
+        }
+    } else if (c == '.') {
+        has_dec_point = 1;
+        c             = *p++;
+        if (!isdigit((int)c)) {
+            return (mk_symbol(sc, strlwr(q)));
+        }
+    } else if (!isdigit((int)c)) {
+        return (mk_symbol(sc, strlwr(q)));
+    }
+
+    for (; (c = *p) != 0; ++p) {
+        if (!isdigit((int)c)) {
+            if (c == '.') {
+                if (!has_dec_point) {
+                    has_dec_point = 1;
+                    continue;
+                }
+            } else if ((c == 'e') || (c == 'E')) {
+                if (!has_fp_exp) {
+                    has_dec_point = 1; /* decimal point illegal
+                                          from now on */
+                    p++;
+                    if ((*p == '-') || (*p == '+') || isdigit((int)*p)) {
+                        continue;
+                    }
+                }
+            }
+            return (mk_symbol(sc, strlwr(q)));
+        }
+    }
+    if (has_dec_point) {
+        return mk_real(sc, atof(q));
+    }
+    return (mk_integer(sc, atol(q)));
+}
+
+/* make constant */
+static pointer
+mk_sharp_const(scheme* sc, char* name) {
+    long x;
+    char tmp[256];
+
+    if (!strcmp(name, "t"))
+        return (sc->T);
+    else if (!strcmp(name, "f"))
+        return (sc->F);
+    else if (*name == 'o') { /* #o (octal) */
+        sprintf(tmp, "0%s", name + 1);
+        sscanf(tmp, "%lo", &x);
+        return (mk_integer(sc, x));
+    } else if (*name == 'd') { /* #d (decimal) */
+        sscanf(name + 1, "%ld", &x);
+        return (mk_integer(sc, x));
+    } else if (*name == 'x') { /* #x (hex) */
+        sprintf(tmp, "0x%s", name + 1);
+        sscanf(tmp, "%lx", &x);
+        return (mk_integer(sc, x));
+    } else if (*name == 'b') { /* #b (binary) */
+        x = binary_decode(name + 1);
+        return (mk_integer(sc, x));
+    } else if (*name == '\\') { /* #\w (character) */
+        int c = 0;
+        if (stricmp(name + 1, "space") == 0) {
+            c = ' ';
+        } else if (stricmp(name + 1, "newline") == 0) {
+            c = '\n';
+        } else if (stricmp(name + 1, "return") == 0) {
+            c = '\r';
+        } else if (stricmp(name + 1, "tab") == 0) {
+            c = '\t';
+        } else if (name[1] == 'x' && name[2] != 0) {
+            int c1 = 0;
+            if (sscanf(name + 2, "%x", &c1) == 1 && c1 < 256) {
+                c = c1;
+            } else {
+                return sc->NIL;
+            }
+#if USE_ASCII_NAMES
+        } else if (is_ascii_name(name + 1, &c)) {
+            /* nothing */
+#endif
+        } else if (name[2] == 0) {
+            c = name[1];
+        } else {
+            return sc->NIL;
+        }
+        return mk_character(sc, c);
+    } else
+        return (sc->NIL);
+}
+
+/* ========== garbage collector ========== */
+
+/*--
+ *  We use algorithm E (Knuth, The Art of Computer Programming Vol.1,
+ *  sec. 2.3.5), the Schorr-Deutsch-Waite link-inversion algorithm,
+ *  for marking.
+ */
+static void
+mark(pointer a) {
+    pointer t, q, p;
+
+    t = (pointer)0;
+    p = a;
+E2:
+    setmark(p);
+    if (is_vector(p)) {
+        int i;
+        int num = ivalue_unchecked(p) / 2 + ivalue_unchecked(p) % 2;
+        for (i = 0; i < num; i++) {
+            /* Vector cells will be treated like ordinary cells */
+            mark(p + 1 + i);
+        }
+    }
+    if (is_atom(p))
+        goto E6;
+    /* E4: down car */
+    q = car(p);
+    if (q && !is_mark(q)) {
+        setatom(p); /* a note that we have moved car */
+        car(p) = t;
+        t      = p;
+        p      = q;
+        goto E2;
+    }
+E5:
+    q = cdr(p); /* down cdr */
+    if (q && !is_mark(q)) {
+        cdr(p) = t;
+        t      = p;
+        p      = q;
+        goto E2;
+    }
+E6: /* up.  Undo the link switching from steps E4 and E5. */
+    if (!t)
+        return;
+    q = t;
+    if (is_atom(q)) {
+        clratom(q);
+        t      = car(q);
+        car(q) = p;
+        p      = q;
+        goto E5;
+    } else {
+        t      = cdr(q);
+        cdr(q) = p;
+        p      = q;
+        goto E6;
+    }
+}
+
+/* garbage collection. parameter a, b is marked. */
+static void
+gc(scheme* sc, pointer a, pointer b) {
+    pointer p;
+    int     i;
+
+    if (sc->gc_verbose) {
+        putstr(sc, "gc...");
+    }
+
+    /* mark system globals */
+    mark(sc->oblist);
+    mark(sc->global_env);
+
+    /* mark current registers */
+    mark(sc->args);
+    mark(sc->envir);
+    mark(sc->code);
+    dump_stack_mark(sc);
+    mark(sc->value);
+    mark(sc->inport);
+    mark(sc->save_inport);
+    mark(sc->outport);
+    mark(sc->loadport);
+
+    /* mark variables a, b */
+    mark(a);
+    mark(b);
+
+    /* garbage collect */
+    clrmark(sc->NIL);
+    sc->fcells    = 0;
+    sc->free_cell = sc->NIL;
+    /* free-list is kept sorted by address so as to maintain consecutive
+       ranges, if possible, for use with vectors. Here we scan the cells
+       (which are also kept sorted by address) downwards to build the
+       free-list in sorted order.
+    */
+    for (i = sc->last_cell_seg; i >= 0; i--) {
+        p = sc->cell_seg[i] + CELL_SEGSIZE;
+        while (--p >= sc->cell_seg[i]) {
+            if (is_mark(p)) {
+                clrmark(p);
+            } else {
+                /* reclaim cell */
+                if (typeflag(p) != 0) {
+                    finalize_cell(sc, p);
+                    typeflag(p) = 0;
+                    car(p)      = sc->NIL;
+                }
+                ++sc->fcells;
+                cdr(p)        = sc->free_cell;
+                sc->free_cell = p;
+            }
+        }
+    }
+
+    if (sc->gc_verbose) {
+        char msg[80];
+        sprintf(msg, "done: %ld cells were recovered.\n", sc->fcells);
+        putstr(sc, msg);
+    }
+}
+
+static void
+finalize_cell(scheme* sc, pointer a) {
+    if (is_string(a)) {
+        sc->free(strvalue(a));
+    } else if (is_port(a)) {
+        if (a->_object._port->kind & port_file && a->_object._port->rep.stdio.closeit) {
+            port_close(sc, a, port_input | port_output);
+        }
+        sc->free(a->_object._port);
+    }
+}
+
+/* ========== Routines for Reading ========== */
+
+static int
+file_push(scheme* sc, const char* fname) {
+    FILE* fin = fopen(fname, "r");
+    if (fin != 0) {
+        sc->file_i++;
+        sc->load_stack[sc->file_i].kind              = port_file | port_input;
+        sc->load_stack[sc->file_i].rep.stdio.file    = fin;
+        sc->load_stack[sc->file_i].rep.stdio.closeit = 1;
+        sc->nesting_stack[sc->file_i]                = 0;
+        sc->loadport->_object._port                  = sc->load_stack + sc->file_i;
+    }
+    return fin != 0;
+}
+
+static void
+file_pop(scheme* sc) {
+    sc->nesting = sc->nesting_stack[sc->file_i];
+    if (sc->file_i != 0) {
+        port_close(sc, sc->loadport, port_input);
+        sc->file_i--;
+        sc->loadport->_object._port = sc->load_stack + sc->file_i;
+        if (file_interactive(sc)) {
+            putstr(sc, prompt);
+        }
+    }
+}
+
+static int
+file_interactive(scheme* sc) {
+    return sc->file_i == 0 && sc->load_stack[0].rep.stdio.file == stdin && sc->inport->_object._port->kind & port_file;
+}
+
+static port*
+port_rep_from_filename(scheme* sc, const char* fn, int prop) {
+    FILE* f;
+    char* rw;
+    port* pt;
+    if (prop == (port_input | port_output)) {
+        rw = "a+";
+    } else if (prop == port_output) {
+        rw = "w";
+    } else {
+        rw = "r";
+    }
+    f = fopen(fn, rw);
+    if (f == 0) {
+        return 0;
+    }
+    pt                    = port_rep_from_file(sc, f, prop);
+    pt->rep.stdio.closeit = 1;
+    return pt;
+}
+
+static pointer
+port_from_filename(scheme* sc, const char* fn, int prop) {
+    port* pt;
+    pt = port_rep_from_filename(sc, fn, prop);
+    if (pt == 0) {
+        return sc->NIL;
+    }
+    return mk_port(sc, pt);
+}
+
+static port*
+port_rep_from_file(scheme* sc, FILE* f, int prop) {
+    /*char *rw;*/
+    port* pt;
+    pt = (port*)sc->malloc(sizeof(port));
+    if (pt == 0) {
+        return 0;
+    }
+    /*
+    if(prop==(port_input|port_output)) {
+      rw="a+";
+    } else if(prop==port_output) {
+      rw="w";
+    } else {
+      rw="r";
+    }
+    */
+    pt->kind              = port_file | prop;
+    pt->rep.stdio.file    = f;
+    pt->rep.stdio.closeit = 0;
+    return pt;
+}
+
+static pointer
+port_from_file(scheme* sc, FILE* f, int prop) {
+    port* pt;
+    pt = port_rep_from_file(sc, f, prop);
+    if (pt == 0) {
+        return sc->NIL;
+    }
+    return mk_port(sc, pt);
+}
+
+static port*
+port_rep_from_string(scheme* sc, char* start, char* past_the_end, int prop) {
+    port* pt;
+    pt = (port*)sc->malloc(sizeof(port));
+    if (pt == 0) {
+        return 0;
+    }
+    pt->kind                    = port_string | prop;
+    pt->rep.string.start        = start;
+    pt->rep.string.curr         = start;
+    pt->rep.string.past_the_end = past_the_end;
+    return pt;
+}
+
+static pointer
+port_from_string(scheme* sc, char* start, char* past_the_end, int prop) {
+    port* pt;
+    pt = port_rep_from_string(sc, start, past_the_end, prop);
+    if (pt == 0) {
+        return sc->NIL;
+    }
+    return mk_port(sc, pt);
+}
+
+static void
+port_close(scheme* sc, pointer p, int flag) {
+    port* pt = p->_object._port;
+    pt->kind &= ~flag;
+    if ((pt->kind & (port_input | port_output)) == 0) {
+        if (pt->kind & port_file) {
+            fclose(pt->rep.stdio.file);
+        }
+        pt->kind = port_free;
+    }
+}
+
+/* get new character from input file */
+static int
+inchar(scheme* sc) {
+    int   c;
+    port* pt;
+again:
+    pt = sc->inport->_object._port;
+    c  = basic_inchar(pt);
+    if (c == EOF && sc->inport == sc->loadport && sc->file_i != 0) {
+        file_pop(sc);
+        if (sc->nesting != 0) {
+            return EOF;
+        }
+        goto again;
+    }
+    return c;
+}
+
+static int
+basic_inchar(port* pt) {
+    if (pt->kind & port_file) {
+        return fgetc(pt->rep.stdio.file);
+    } else {
+        if (*pt->rep.string.curr == 0 || pt->rep.string.curr == pt->rep.string.past_the_end) {
+            return EOF;
+        } else {
+            return *pt->rep.string.curr++;
+        }
+    }
+}
+
+/* back character to input buffer */
+static void
+backchar(scheme* sc, int c) {
+    port* pt;
+    if (c == EOF)
+        return;
+    pt = sc->inport->_object._port;
+    if (pt->kind & port_file) {
+        ungetc(c, pt->rep.stdio.file);
+    } else {
+        if (pt->rep.string.curr != pt->rep.string.start) {
+            --pt->rep.string.curr;
+        }
+    }
+}
+
+INTERFACE void
+putstr(scheme* sc, const char* s) {
+    port* pt = sc->outport->_object._port;
+    if (pt->kind & port_file) {
+        fputs(s, pt->rep.stdio.file);
+    } else {
+        for (; *s; s++) {
+            if (pt->rep.string.curr != pt->rep.string.past_the_end) {
+                *pt->rep.string.curr++ = *s;
+            }
+        }
+    }
+}
+
+static void
+putchars(scheme* sc, const char* s, int len) {
+    port* pt = sc->outport->_object._port;
+    if (pt->kind & port_file) {
+        /* use the return value here to eliminate a compiler warning */
+        if (fwrite(s, 1, len, pt->rep.stdio.file) == 0)
+            return;
+    } else {
+        for (; len; len--) {
+            if (pt->rep.string.curr != pt->rep.string.past_the_end) {
+                *pt->rep.string.curr++ = *s++;
+            }
+        }
+    }
+}
+
+INTERFACE void
+putcharacter(scheme* sc, int c) {
+    port* pt = sc->outport->_object._port;
+    if (pt->kind & port_file) {
+        fputc(c, pt->rep.stdio.file);
+    } else {
+        if (pt->rep.string.curr != pt->rep.string.past_the_end) {
+            *pt->rep.string.curr++ = c;
+        }
+    }
+}
+
+/* read characters up to delimiter, but cater to character constants */
+static char*
+readstr_upto(scheme* sc, char* delim) {
+    char* p = sc->strbuff;
+
+    while (!is_one_of(delim, (*p++ = inchar(sc))))
+        ;
+    if (p == sc->strbuff + 2 && p[-2] == '\\') {
+        *p = 0;
+    } else {
+        backchar(sc, p[-1]);
+        *--p = '\0';
+    }
+    return sc->strbuff;
+}
+
+/* read string expression "xxx...xxx" */
+static pointer
+readstrexp(scheme* sc) {
+    char* p = sc->strbuff;
+    int   c;
+    int   c1 = 0;
+
+    enum {
+        st_ok,
+        st_bsl,
+        st_x1,
+        st_x2
+    } state = st_ok;
+
+    for (;;) {
+        c = inchar(sc);
+        if (c == EOF || p - sc->strbuff > sizeof(sc->strbuff) - 1) {
+            return sc->F;
+        }
+        switch (state) {
+            case st_ok:
+                switch (c) {
+                    case '\\': state = st_bsl; break;
+                    case '"': *p = 0; return mk_counted_string(sc, sc->strbuff, p - sc->strbuff);
+                    default: *p++ = c; break;
+                }
+                break;
+            case st_bsl:
+                switch (c) {
+                    case 'x':
+                    case 'X':
+                        state = st_x1;
+                        c1    = 0;
+                        break;
+                    case 'n':
+                        *p++  = '\n';
+                        state = st_ok;
+                        break;
+                    case 't':
+                        *p++  = '\t';
+                        state = st_ok;
+                        break;
+                    case 'r':
+                        *p++  = '\r';
+                        state = st_ok;
+                        break;
+                    case '"':
+                        *p++  = '"';
+                        state = st_ok;
+                        break;
+                    default:
+                        *p++  = c;
+                        state = st_ok;
+                        break;
+                }
+                break;
+            case st_x1:
+            case st_x2:
+                c = toupper(c);
+                if (c >= '0' && c <= 'F') {
+                    if (c <= '9') {
+                        c1 = (c1 << 4) + c - '0';
+                    } else {
+                        c1 = (c1 << 4) + c - 'A' + 10;
+                    }
+                    if (state == st_x1) {
+                        state = st_x2;
+                    } else {
+                        *p++  = c1;
+                        state = st_ok;
+                    }
+                } else {
+                    return sc->F;
+                }
+                break;
+        }
+    }
+}
+
+/* check c is in chars */
+static INLINE int
+is_one_of(char* s, int c) {
+    if (c == EOF)
+        return 1;
+    while (*s)
+        if (*s++ == c)
+            return (1);
+    return (0);
+}
+
+/* skip white characters */
+static INLINE void
+skipspace(scheme* sc) {
+    int c;
+    while (isspace(c = inchar(sc)))
+        ;
+    if (c != EOF) {
+        backchar(sc, c);
+    }
+}
+
+/* get token */
+static int
+token(scheme* sc) {
+    int c;
+    skipspace(sc);
+    switch (c = inchar(sc)) {
+        case EOF: return (TOK_EOF);
+        case '(': return (TOK_LPAREN);
+        case ')': return (TOK_RPAREN);
+        case '.':
+            c = inchar(sc);
+            if (is_one_of(" \n\t", c)) {
+                return (TOK_DOT);
+            } else {
+                backchar(sc, c);
+                backchar(sc, '.');
+                return TOK_ATOM;
+            }
+        case '\'': return (TOK_QUOTE);
+        case ';': return (TOK_COMMENT);
+        case '"': return (TOK_DQUOTE);
+        case BACKQUOTE: return (TOK_BQUOTE);
+        case ',':
+            if ((c = inchar(sc)) == '@')
+                return (TOK_ATMARK);
+            else {
+                backchar(sc, c);
+                return (TOK_COMMA);
+            }
+        case '#':
+            c = inchar(sc);
+            if (c == '(') {
+                return (TOK_VEC);
+            } else if (c == '!') {
+                return TOK_COMMENT;
+            } else {
+                backchar(sc, c);
+                if (is_one_of(" tfodxb\\", c)) {
+                    return TOK_SHARP_CONST;
+                } else {
+                    return (TOK_SHARP);
+                }
+            }
+        default: backchar(sc, c); return (TOK_ATOM);
+    }
+}
+
+/* ========== Routines for Printing ========== */
+#define ok_abbrev(x) (is_pair(x) && cdr(x) == sc->NIL)
+
+static void
+printslashstring(scheme* sc, char* p, int len) {
+    int            i;
+    unsigned char* s = (unsigned char*)p;
+    putcharacter(sc, '"');
+    for (i = 0; i < len; i++) {
+        if (*s == 0xff || *s == '"' || *s < ' ' || *s == '\\') {
+            putcharacter(sc, '\\');
+            switch (*s) {
+                case '"': putcharacter(sc, '"'); break;
+                case '\n': putcharacter(sc, 'n'); break;
+                case '\t': putcharacter(sc, 't'); break;
+                case '\r': putcharacter(sc, 'r'); break;
+                case '\\': putcharacter(sc, '\\'); break;
+                default:
+                    {
+                        int d = *s / 16;
+                        putcharacter(sc, 'x');
+                        if (d < 10) {
+                            putcharacter(sc, d + '0');
+                        } else {
+                            putcharacter(sc, d - 10 + 'A');
+                        }
+                        d = *s % 16;
+                        if (d < 10) {
+                            putcharacter(sc, d + '0');
+                        } else {
+                            putcharacter(sc, d - 10 + 'A');
+                        }
+                    }
+            }
+        } else {
+            putcharacter(sc, *s);
+        }
+        s++;
+    }
+    putcharacter(sc, '"');
+}
+
+/* print atoms */
+static void
+printatom(scheme* sc, pointer l, int f) {
+    char* p;
+    int   len;
+    atom2str(sc, l, f, &p, &len);
+    putchars(sc, p, len);
+}
+
+/* Uses internal buffer unless string pointer is already available */
+static void
+atom2str(scheme* sc, pointer l, int f, char** pp, int* plen) {
+    char* p;
+
+    if (l == sc->NIL) {
+        p = "()";
+    } else if (l == sc->T) {
+        p = "#t";
+    } else if (l == sc->F) {
+        p = "#f";
+    } else if (l == sc->EOF_OBJ) {
+        p = "#<EOF>";
+    } else if (is_port(l)) {
+        p = sc->strbuff;
+        strcpy(p, "#<PORT>");
+    } else if (is_number(l)) {
+        p = sc->strbuff;
+        if (is_integer(l)) {
+            sprintf(p, "%ld", ivalue_unchecked(l));
+        } else {
+            sprintf(p, "%.10g", rvalue_unchecked(l));
+        }
+    } else if (is_string(l)) {
+        if (!f) {
+            p = strvalue(l);
+        } else { /* Hack, uses the fact that printing is needed */
+            *pp   = sc->strbuff;
+            *plen = 0;
+            printslashstring(sc, strvalue(l), strlength(l));
+            return;
+        }
+    } else if (is_character(l)) {
+        int c = charvalue(l);
+        p     = sc->strbuff;
+        if (!f) {
+            p[0] = c;
+            p[1] = 0;
+        } else {
+            switch (c) {
+                case ' ': sprintf(p, "#\\space"); break;
+                case '\n': sprintf(p, "#\\newline"); break;
+                case '\r': sprintf(p, "#\\return"); break;
+                case '\t': sprintf(p, "#\\tab"); break;
+                default:
+#if USE_ASCII_NAMES
+                    if (c == 127) {
+                        strcpy(p, "#\\del");
+                        break;
+                    } else if (c < 32) {
+                        strcpy(p, "#\\");
+                        strcat(p, charnames[c]);
+                        break;
+                    }
+#else
+                    if (c < 32) {
+                        sprintf(p, "#\\x%x", c);
+                        break;
+                    }
+#endif
+                    sprintf(p, "#\\%c", c);
+                    break;
+            }
+        }
+    } else if (is_symbol(l)) {
+        p = symname(l);
+    } else if (is_proc(l)) {
+        p = sc->strbuff;
+        sprintf(p, "#<%s PROCEDURE %ld>", procname(l), procnum(l));
+    } else if (is_macro(l)) {
+        p = "#<MACRO>";
+    } else if (is_closure(l)) {
+        p = "#<CLOSURE>";
+    } else if (is_promise(l)) {
+        p = "#<PROMISE>";
+    } else if (is_foreign(l)) {
+        p = sc->strbuff;
+        sprintf(p, "#<FOREIGN PROCEDURE %ld>", procnum(l));
+    } else if (is_continuation(l)) {
+        p = "#<CONTINUATION>";
+    } else {
+        p = "#<ERROR>";
+    }
+    *pp   = p;
+    *plen = strlen(p);
+}
+
+/* ========== Routines for Evaluation Cycle ========== */
+
+/* make closure. c is code. e is environment */
+static pointer
+mk_closure(scheme* sc, pointer c, pointer e) {
+    pointer x = get_cell(sc, c, e);
+
+    typeflag(x) = T_CLOSURE;
+    car(x)      = c;
+    cdr(x)      = e;
+    return (x);
+}
+
+/* make continuation. */
+static pointer
+mk_continuation(scheme* sc, pointer d) {
+    pointer x = get_cell(sc, sc->NIL, d);
+
+    typeflag(x)  = T_CONTINUATION;
+    cont_dump(x) = d;
+    return (x);
+}
+
+static pointer
+list_star(scheme* sc, pointer d) {
+    pointer p, q;
+    if (cdr(d) == sc->NIL) {
+        return car(d);
+    }
+    p = cons(sc, car(d), cdr(d));
+    q = p;
+    while (cdr(cdr(p)) != sc->NIL) {
+        d = cons(sc, car(p), cdr(p));
+        if (cdr(cdr(p)) != sc->NIL) {
+            p = cdr(d);
+        }
+    }
+    cdr(p) = car(cdr(p));
+    return q;
 }
 
-INTERFACE static pointer mk_vector(scheme *sc, int len) {
-     pointer x=get_consecutive_cells(sc,len/2+len%2+1);
-     typeflag(x) = (T_VECTOR | T_ATOM);
-     ivalue_unchecked(x)=len;
-     set_integer(x);
-     fill_vector(x,sc->NIL);
-     return x;
+/* reverse list -- produce new list */
+static pointer
+reverse(scheme* sc, pointer a) {
+    /* a must be checked by gc */
+    pointer p = sc->NIL;
+
+    for (; is_pair(a); a = cdr(a)) {
+        p = cons(sc, car(a), p);
+    }
+    return (p);
 }
 
-INTERFACE static void fill_vector(pointer vec, pointer obj) {
-     int i;
-     int num=ivalue(vec)/2+ivalue(vec)%2;
-     for(i=0; i<num; i++) {
-          typeflag(vec+1+i) = T_PAIR;
-          setimmutable(vec+1+i);
-          car(vec+1+i)=obj;
-          cdr(vec+1+i)=obj;
-     }
+/* reverse list --- in-place */
+static pointer
+reverse_in_place(scheme* sc, pointer term, pointer list) {
+    pointer p = list, result = term, q;
+
+    while (p != sc->NIL) {
+        q      = cdr(p);
+        cdr(p) = result;
+        result = p;
+        p      = q;
+    }
+    return (result);
 }
 
-INTERFACE static pointer vector_elem(pointer vec, int ielem) {
-     int n=ielem/2;
-     if(ielem%2==0) {
-          return car(vec+1+n);
-     } else {
-          return cdr(vec+1+n);
-     }
+/* append list -- produce new list */
+static pointer
+append(scheme* sc, pointer a, pointer b) {
+    pointer p = b, q;
+
+    if (a != sc->NIL) {
+        a = reverse(sc, a);
+        while (a != sc->NIL) {
+            q      = cdr(a);
+            cdr(a) = p;
+            p      = a;
+            a      = q;
+        }
+    }
+    return (p);
 }
 
-INTERFACE static pointer set_vector_elem(pointer vec, int ielem, pointer a) {
-     int n=ielem/2;
-     if(ielem%2==0) {
-          return car(vec+1+n)=a;
-     } else {
-          return cdr(vec+1+n)=a;
-     }
+/* equivalence of atoms */
+static int
+eqv(pointer a, pointer b) {
+    if (is_string(a)) {
+        if (is_string(b))
+            return (strvalue(a) == strvalue(b));
+        else
+            return (0);
+    } else if (is_number(a)) {
+        if (is_number(b))
+            return num_eq(nvalue(a), nvalue(b));
+        else
+            return (0);
+    } else if (is_character(a)) {
+        if (is_character(b))
+            return charvalue(a) == charvalue(b);
+        else
+            return (0);
+    } else if (is_port(a)) {
+        if (is_port(b))
+            return a == b;
+        else
+            return (0);
+    } else if (is_proc(a)) {
+        if (is_proc(b))
+            return procnum(a) == procnum(b);
+        else
+            return (0);
+    } else {
+        return (a == b);
+    }
 }
 
-/* get new symbol */
-INTERFACE pointer mk_symbol(scheme *sc, const char *name) { 
-     pointer x; 
-
-     /* first check oblist */ 
-     x = oblist_find_by_name(sc, name); 
-     if (x != sc->NIL) { 
-          return (x); 
-     } else { 
-          x = oblist_add_by_name(sc, name); 
-          return (x); 
-     } 
-} 
-
-INTERFACE pointer gensym(scheme *sc) { 
-     pointer x; 
-     char name[40]; 
-
-     for(; sc->gensym_cnt<LONG_MAX; sc->gensym_cnt++) { 
-          sprintf(name,"gensym-%ld",sc->gensym_cnt); 
-
-          /* first check oblist */ 
-          x = oblist_find_by_name(sc, name); 
-
-          if (x != sc->NIL) { 
-               continue; 
-          } else { 
-               x = oblist_add_by_name(sc, name); 
-               return (x); 
-          } 
-     } 
-
-     return sc->NIL; 
-} 
+/* true or false value macro */
+/* () is #t in R5RS */
+#define is_true(p)  ((p) != sc->F)
+#define is_false(p) ((p) == sc->F)
 
-/* make symbol or number atom from string */
-static pointer mk_atom(scheme *sc, char *q) {
-     char    c, *p;
-     int has_dec_point=0;
-     int has_fp_exp = 0;
+/* ========== Environment implementation  ========== */
 
-#if USE_COLON_HOOK
-     if((p=strstr(q,"::"))!=0) {
-          *p=0;
-          return cons(sc, sc->COLON_HOOK,
-                          cons(sc,
-                              cons(sc,
-                                   sc->QUOTE,
-                                   cons(sc, mk_atom(sc,p+2), sc->NIL)),
-                              cons(sc, mk_symbol(sc,strlwr(q)), sc->NIL)));
-     }
-#endif
+#if !defined(USE_ALIST_ENV) || !defined(USE_OBJECT_LIST)
 
-     p = q;
-     c = *p++; 
-     if ((c == '+') || (c == '-')) { 
-       c = *p++; 
-       if (c == '.') { 
-         has_dec_point=1; 
-	 c = *p++; 
-       } 
-       if (!isdigit((int) c)) { 
-	 return (mk_symbol(sc, strlwr(q))); 
-       } 
-     } else if (c == '.') { 
-       has_dec_point=1; 
-       c = *p++; 
-       if (!isdigit((int) c)) { 
-	 return (mk_symbol(sc, strlwr(q))); 
-       } 
-     } else if (!isdigit((int) c)) { 
-       return (mk_symbol(sc, strlwr(q))); 
-     }
-
-     for ( ; (c = *p) != 0; ++p) {
-          if (!isdigit((int) c)) {
-               if(c=='.') {
-                    if(!has_dec_point) {
-                         has_dec_point=1;
-                         continue;
-                    }
-               }
-               else if ((c == 'e') || (c == 'E')) {
-                       if(!has_fp_exp) {
-                          has_dec_point = 1; /* decimal point illegal
-                                                from now on */
-                          p++;
-                          if ((*p == '-') || (*p == '+') || isdigit((int) *p)) {
-                             continue;
-                          }
-                       }  
-               }    
-               return (mk_symbol(sc, strlwr(q)));
-          }
-     }
-     if(has_dec_point) {
-          return mk_real(sc,atof(q));
-     }
-     return (mk_integer(sc, atol(q)));
-}
+static int
+hash_fn(const char* key, int table_size) {
+    unsigned int hashed = 0;
+    const char*  c;
+    int          bits_per_int = sizeof(unsigned int) * 8;
 
-/* make constant */
-static pointer mk_sharp_const(scheme *sc, char *name) {
-     long    x;
-     char    tmp[256];
-
-     if (!strcmp(name, "t"))
-          return (sc->T);
-     else if (!strcmp(name, "f"))
-          return (sc->F);
-     else if (*name == 'o') {/* #o (octal) */
-          sprintf(tmp, "0%s", name+1);
-          sscanf(tmp, "%lo", &x);
-          return (mk_integer(sc, x));
-     } else if (*name == 'd') {    /* #d (decimal) */
-          sscanf(name+1, "%ld", &x);
-          return (mk_integer(sc, x));
-     } else if (*name == 'x') {    /* #x (hex) */
-          sprintf(tmp, "0x%s", name+1);
-          sscanf(tmp, "%lx", &x);
-          return (mk_integer(sc, x));
-     } else if (*name == 'b') {    /* #b (binary) */
-          x = binary_decode(name+1);
-          return (mk_integer(sc, x));
-     } else if (*name == '\\') { /* #\w (character) */
-          int c=0;
-          if(stricmp(name+1,"space")==0) {
-               c=' ';
-          } else if(stricmp(name+1,"newline")==0) {
-               c='\n';
-          } else if(stricmp(name+1,"return")==0) {
-               c='\r';
-          } else if(stricmp(name+1,"tab")==0) {
-               c='\t';
-     } else if(name[1]=='x' && name[2]!=0) {
-          int c1=0;
-          if(sscanf(name+2,"%x",&c1)==1 && c1<256) {
-               c=c1;
-          } else {
-               return sc->NIL;
-     }
-#if USE_ASCII_NAMES
-          } else if(is_ascii_name(name+1,&c)) {
-               /* nothing */
-#endif               
-          } else if(name[2]==0) {
-               c=name[1];
-          } else {
-               return sc->NIL;
-          }
-          return mk_character(sc,c);
-     } else
-          return (sc->NIL);
+    for (c = key; *c; c++) {
+        /* letters have about 5 bits in them */
+        hashed = (hashed << 5) | (hashed >> (bits_per_int - 5));
+        hashed ^= *c;
+    }
+    return hashed % table_size;
 }
+#endif
 
-/* ========== garbage collector ========== */
+#ifndef USE_ALIST_ENV
 
-/*--
- *  We use algorithm E (Knuth, The Art of Computer Programming Vol.1,
- *  sec. 2.3.5), the Schorr-Deutsch-Waite link-inversion algorithm, 
- *  for marking. 
+/*
+ * In this implementation, each frame of the environment may be
+ * a hash table: a vector of alists hashed by variable name.
+ * In practice, we use a vector only for the initial frame;
+ * subsequent frames are too small and transient for the lookup
+ * speed to out-weigh the cost of making a new vector.
  */
-static void mark(pointer a) {
-     pointer t, q, p;
-
-     t = (pointer) 0;
-     p = a;
-E2:  setmark(p);
-     if(is_vector(p)) {
-          int i;
-          int num=ivalue_unchecked(p)/2+ivalue_unchecked(p)%2;
-          for(i=0; i<num; i++) {
-               /* Vector cells will be treated like ordinary cells */
-               mark(p+1+i);
-          }
-     }
-     if (is_atom(p))
-          goto E6;
-     /* E4: down car */
-     q = car(p);
-     if (q && !is_mark(q)) {
-          setatom(p);  /* a note that we have moved car */ 
-          car(p) = t;
-          t = p;
-          p = q;
-          goto E2;
-     }
- E5:  q = cdr(p); /* down cdr */
-     if (q && !is_mark(q)) {
-          cdr(p) = t;
-          t = p;
-          p = q;
-          goto E2;
-     }
-E6:   /* up.  Undo the link switching from steps E4 and E5. */ 
-     if (!t)
-          return;
-     q = t;
-     if (is_atom(q)) {
-          clratom(q);
-          t = car(q);
-          car(q) = p;
-          p = q;
-          goto E5;
-     } else {
-          t = cdr(q);
-          cdr(q) = p;
-          p = q;
-          goto E6;
-     }
-}
-
-/* garbage collection. parameter a, b is marked. */
-static void gc(scheme *sc, pointer a, pointer b) {
-  pointer p;
-  int i;
-  
-  if(sc->gc_verbose) {
-    putstr(sc, "gc...");
-  }
-
-  /* mark system globals */
-  mark(sc->oblist);
-  mark(sc->global_env);
-
-  /* mark current registers */
-  mark(sc->args);
-  mark(sc->envir);
-  mark(sc->code);
-  dump_stack_mark(sc); 
-  mark(sc->value);
-  mark(sc->inport);
-  mark(sc->save_inport);
-  mark(sc->outport);
-  mark(sc->loadport);
-
-  /* mark variables a, b */
-  mark(a);
-  mark(b);
-
-  /* garbage collect */
-  clrmark(sc->NIL);
-  sc->fcells = 0;
-  sc->free_cell = sc->NIL;
-  /* free-list is kept sorted by address so as to maintain consecutive
-     ranges, if possible, for use with vectors. Here we scan the cells
-     (which are also kept sorted by address) downwards to build the
-     free-list in sorted order.
-  */
-  for (i = sc->last_cell_seg; i >= 0; i--) {
-    p = sc->cell_seg[i] + CELL_SEGSIZE;
-    while (--p >= sc->cell_seg[i]) {
-      if (is_mark(p)) {
-	clrmark(p);
-      } else {
-	/* reclaim cell */
-        if (typeflag(p) != 0) { 
-          finalize_cell(sc, p); 
-          typeflag(p) = 0; 
-          car(p) = sc->NIL; 
-        } 
-        ++sc->fcells; 
-        cdr(p) = sc->free_cell; 
-        sc->free_cell = p; 
-      }
-    }
-  }
-  
-  if (sc->gc_verbose) {
-    char msg[80];
-    sprintf(msg,"done: %ld cells were recovered.\n", sc->fcells);
-    putstr(sc,msg);
-  }
-}
-
-static void finalize_cell(scheme *sc, pointer a) {
-  if(is_string(a)) {
-    sc->free(strvalue(a));
-  } else if(is_port(a)) {
-    if(a->_object._port->kind&port_file 
-       && a->_object._port->rep.stdio.closeit) {
-      port_close(sc,a,port_input|port_output);
-    }
-    sc->free(a->_object._port);
-  }
-}
-
-/* ========== Routines for Reading ========== */
 
-static int file_push(scheme *sc, const char *fname) {
-  FILE *fin=fopen(fname,"r");
-  if(fin!=0) {
-    sc->file_i++;
-    sc->load_stack[sc->file_i].kind=port_file|port_input;
-    sc->load_stack[sc->file_i].rep.stdio.file=fin;
-    sc->load_stack[sc->file_i].rep.stdio.closeit=1;
-    sc->nesting_stack[sc->file_i]=0;
-    sc->loadport->_object._port=sc->load_stack+sc->file_i;
-  }
-  return fin!=0;
-}
-
-static void file_pop(scheme *sc) {
- sc->nesting=sc->nesting_stack[sc->file_i];
- if(sc->file_i!=0) {
-   port_close(sc,sc->loadport,port_input);
-   sc->file_i--;
-   sc->loadport->_object._port=sc->load_stack+sc->file_i;
-   if(file_interactive(sc)) {
-     putstr(sc,prompt);
-   }
- }
-}
-
-static int file_interactive(scheme *sc) {
- return sc->file_i==0 && sc->load_stack[0].rep.stdio.file==stdin
-     && sc->inport->_object._port->kind&port_file;
-}
-
-static port *port_rep_from_filename(scheme *sc, const char *fn, int prop) {
-  FILE *f;
-  char *rw;
-  port *pt;
-  if(prop==(port_input|port_output)) {
-    rw="a+";
-  } else if(prop==port_output) {
-    rw="w";
-  } else {
-    rw="r";
-  }
-  f=fopen(fn,rw);
-  if(f==0) {
-    return 0;
-  }
-  pt=port_rep_from_file(sc,f,prop);
-  pt->rep.stdio.closeit=1;
-  return pt;
-}
+static void
+new_frame_in_env(scheme* sc, pointer old_env) {
+    pointer new_frame;
 
-static pointer port_from_filename(scheme *sc, const char *fn, int prop) {
-  port *pt;
-  pt=port_rep_from_filename(sc,fn,prop);
-  if(pt==0) {
-    return sc->NIL;
-  }
-  return mk_port(sc,pt);
-}
+    /* The interaction-environment has about 300 variables in it. */
+    if (old_env == sc->NIL) {
+        new_frame = mk_vector(sc, 461);
+    } else {
+        new_frame = sc->NIL;
+    }
 
-static port *port_rep_from_file(scheme *sc, FILE *f, int prop) {
-  /*char *rw;*/
-  port *pt;
-  pt=(port*)sc->malloc(sizeof(port));
-  if(pt==0) {
-    return 0;
-  }
-  /*
-  if(prop==(port_input|port_output)) {
-    rw="a+";
-  } else if(prop==port_output) {
-    rw="w";
-  } else {
-    rw="r";
-  }
-  */
-  pt->kind=port_file|prop;
-  pt->rep.stdio.file=f;
-  pt->rep.stdio.closeit=0;
-  return pt;
-}
-
-static pointer port_from_file(scheme *sc, FILE *f, int prop) {
-  port *pt;
-  pt=port_rep_from_file(sc,f,prop);
-  if(pt==0) {
-    return sc->NIL;
-  }
-  return mk_port(sc,pt);
+    sc->envir = immutable_cons(sc, new_frame, old_env);
+    setenvironment(sc->envir);
 }
 
-static port *port_rep_from_string(scheme *sc, char *start, char *past_the_end, int prop) {
-  port *pt;
-  pt=(port*)sc->malloc(sizeof(port));
-  if(pt==0) {
-    return 0;
-  }
-  pt->kind=port_string|prop;
-  pt->rep.string.start=start;
-  pt->rep.string.curr=start;
-  pt->rep.string.past_the_end=past_the_end;
-  return pt;
-}
-
-static pointer port_from_string(scheme *sc, char *start, char *past_the_end, int prop) {
-  port *pt;
-  pt=port_rep_from_string(sc,start,past_the_end,prop);
-  if(pt==0) {
-    return sc->NIL;
-  }
-  return mk_port(sc,pt);
-}
+static INLINE void
+new_slot_spec_in_env(scheme* sc, pointer env, pointer variable, pointer value) {
+    pointer slot = immutable_cons(sc, variable, value);
 
-static void port_close(scheme *sc, pointer p, int flag) {
-  port *pt=p->_object._port;
-  pt->kind&=~flag;
-  if((pt->kind & (port_input|port_output))==0) {
-    if(pt->kind&port_file) {
-      fclose(pt->rep.stdio.file);
-    }
-    pt->kind=port_free;
-  }
-}
+    if (is_vector(car(env))) {
+        int location = hash_fn(symname(variable), ivalue_unchecked(car(env)));
 
-/* get new character from input file */
-static int inchar(scheme *sc) {
-  int c;
-  port *pt;
- again:
-  pt=sc->inport->_object._port;
-  c=basic_inchar(pt);
-  if(c==EOF && sc->inport==sc->loadport && sc->file_i!=0) {
-    file_pop(sc);
-    if(sc->nesting!=0) {
-      return EOF;
-    }
-    goto again;
-  }
-  return c;
-}
-
-static int basic_inchar(port *pt) {
-  if(pt->kind&port_file) {
-    return fgetc(pt->rep.stdio.file);
-  } else {
-    if(*pt->rep.string.curr==0
-       || pt->rep.string.curr==pt->rep.string.past_the_end) {
-      return EOF;
+        set_vector_elem(car(env), location, immutable_cons(sc, slot, vector_elem(car(env), location)));
     } else {
-      return *pt->rep.string.curr++;
+        car(env) = immutable_cons(sc, slot, car(env));
     }
-  }
 }
 
-/* back character to input buffer */
-static void backchar(scheme *sc, int c) {
-  port *pt;
-  if(c==EOF) return;
-  pt=sc->inport->_object._port;
-  if(pt->kind&port_file) {
-    ungetc(c,pt->rep.stdio.file);
-  } else {
-    if(pt->rep.string.curr!=pt->rep.string.start) {
-      --pt->rep.string.curr;
-    }
-  }
-}
-
-INTERFACE void putstr(scheme *sc, const char *s) {
-  port *pt=sc->outport->_object._port;
-  if(pt->kind&port_file) {
-    fputs(s,pt->rep.stdio.file);
-  } else {
-    for(;*s;s++) {
-      if(pt->rep.string.curr!=pt->rep.string.past_the_end) {
-	*pt->rep.string.curr++=*s;
-      }
+static pointer
+find_slot_in_env(scheme* sc, pointer env, pointer hdl, int all) {
+    pointer x = sc->NIL, y = sc->NIL;
+    int     location = 0;
+
+    for (x = env; x != sc->NIL; x = cdr(x)) {
+        if (is_vector(car(x))) {
+            location = hash_fn(symname(hdl), ivalue_unchecked(car(x)));
+            y        = vector_elem(car(x), location);
+        } else {
+            y = car(x);
+        }
+        for (; y != sc->NIL; y = cdr(y)) {
+            if (caar(y) == hdl) {
+                break;
+            }
+        }
+        if (y != sc->NIL) {
+            break;
+        }
+        if (!all) {
+            return sc->NIL;
+        }
     }
-  }
-}
-
-static void putchars(scheme *sc, const char *s, int len) {
-  port *pt=sc->outport->_object._port;
-  if(pt->kind&port_file) {
-    /* use the return value here to eliminate a compiler warning */
-    if (fwrite(s,1,len,pt->rep.stdio.file) == 0)
-    	return;
-  } else {
-    for(;len;len--) {
-      if(pt->rep.string.curr!=pt->rep.string.past_the_end) {
-	*pt->rep.string.curr++=*s++;
-      }
+    if (x != sc->NIL) {
+        return car(y);
     }
-  }
+    return sc->NIL;
 }
 
-INTERFACE void putcharacter(scheme *sc, int c) {
-  port *pt=sc->outport->_object._port;
-  if(pt->kind&port_file) {
-    fputc(c,pt->rep.stdio.file);
-  } else {
-    if(pt->rep.string.curr!=pt->rep.string.past_the_end) {
-      *pt->rep.string.curr++=c;
-    }
-  }
-}
+#else /* USE_ALIST_ENV */
 
-/* read characters up to delimiter, but cater to character constants */
-static char   *readstr_upto(scheme *sc, char *delim) {
-  char   *p = sc->strbuff;
+static INLINE void
+new_frame_in_env(scheme* sc, pointer old_env) {
+    sc->envir = immutable_cons(sc, sc->NIL, old_env);
+    setenvironment(sc->envir);
+}
 
-  while (!is_one_of(delim, (*p++ = inchar(sc))));
-  if(p==sc->strbuff+2 && p[-2]=='\\') {
-    *p=0;
-  } else {
-    backchar(sc,p[-1]);
-    *--p = '\0';
-  }
-  return sc->strbuff;
+static INLINE void
+new_slot_spec_in_env(scheme* sc, pointer env, pointer variable, pointer value) {
+    car(env) = immutable_cons(sc, immutable_cons(sc, variable, value), car(env));
 }
 
-/* read string expression "xxx...xxx" */
-static pointer readstrexp(scheme *sc) {
-  char *p = sc->strbuff;
-  int c;
-  int c1=0;
-  enum { st_ok, st_bsl, st_x1, st_x2} state=st_ok;
-  
-  for (;;) {
-    c=inchar(sc);
-    if(c==EOF || p-sc->strbuff>sizeof(sc->strbuff)-1) {
-      return sc->F;
+static pointer
+find_slot_in_env(scheme* sc, pointer env, pointer hdl, int all) {
+    pointer x, y;
+    for (x = env; x != sc->NIL; x = cdr(x)) {
+        for (y = car(x); y != sc->NIL; y = cdr(y)) {
+            if (caar(y) == hdl) {
+                break;
+            }
+        }
+        if (y != sc->NIL) {
+            break;
+        }
+        if (!all) {
+            return sc->NIL;
+        }
     }
-    switch(state) {
-    case st_ok:
-      switch(c) {
-      case '\\':
-	state=st_bsl;
-	break;
-      case '"':
-	*p=0;
-	return mk_counted_string(sc,sc->strbuff,p-sc->strbuff);
-      default:
-	*p++=c;
-	break;
-      }
-      break;
-    case st_bsl:
-      switch(c) {
-      case 'x':
-      case 'X':
-	state=st_x1;
-	c1=0;
-	break;
-      case 'n':
-	*p++='\n';
-	state=st_ok;
-	break;
-      case 't':
-	*p++='\t';
-	state=st_ok;
-	break;
-      case 'r':
-	*p++='\r';
-	state=st_ok;
-	break;
-      case '"':
-	*p++='"';
-	state=st_ok;
-	break;
-      default:
-	*p++=c;
-	state=st_ok;
-	break;
-      }
-      break;
-    case st_x1:
-    case st_x2:
-      c=toupper(c);
-      if(c>='0' && c<='F') {
-	if(c<='9') {
-	  c1=(c1<<4)+c-'0';
-	} else {
-	  c1=(c1<<4)+c-'A'+10;
-	}
-	if(state==st_x1) {
-	  state=st_x2;
-	} else {
-	  *p++=c1;
-	  state=st_ok;
-	}
-      } else {
-	return sc->F;
-      }
-      break;
+    if (x != sc->NIL) {
+        return car(y);
     }
-  }
+    return sc->NIL;
 }
 
-/* check c is in chars */
-static INLINE int is_one_of(char *s, int c) {
-     if(c==EOF) return 1;
-     while (*s)
-          if (*s++ == c)
-               return (1);
-     return (0);
+#endif /* USE_ALIST_ENV else */
+
+static INLINE void
+new_slot_in_env(scheme* sc, pointer variable, pointer value) {
+    new_slot_spec_in_env(sc, sc->envir, variable, value);
 }
 
-/* skip white characters */
-static INLINE void skipspace(scheme *sc) {
-     int c;
-     while (isspace(c=inchar(sc)))
-          ;
-     if(c!=EOF) {
-          backchar(sc,c);
-     }
+static INLINE void
+set_slot_in_env(scheme* sc, pointer slot, pointer value) {
+    cdr(slot) = value;
 }
 
-/* get token */
-static int token(scheme *sc) {
-     int c;
-     skipspace(sc);
-     switch (c=inchar(sc)) {
-     case EOF:
-          return (TOK_EOF);
-     case '(':
-          return (TOK_LPAREN);
-     case ')':
-          return (TOK_RPAREN);
-     case '.':
-          c=inchar(sc);
-          if(is_one_of(" \n\t",c)) {
-               return (TOK_DOT);
-          } else {
-               backchar(sc,c);
-	       backchar(sc,'.');
-               return TOK_ATOM;
-          }
-     case '\'':
-          return (TOK_QUOTE);
-     case ';':
-          return (TOK_COMMENT);
-     case '"':
-          return (TOK_DQUOTE);
-     case BACKQUOTE:
-          return (TOK_BQUOTE);
-     case ',':
-          if ((c=inchar(sc)) == '@')
-               return (TOK_ATMARK);
-          else {
-               backchar(sc,c);
-               return (TOK_COMMA);
-          }
-     case '#':
-          c=inchar(sc);
-          if (c == '(') {
-               return (TOK_VEC);
-          } else if(c == '!') {
-               return TOK_COMMENT;
-          } else {
-               backchar(sc,c);
-               if(is_one_of(" tfodxb\\",c)) {
-                    return TOK_SHARP_CONST;
-               } else {
-                    return (TOK_SHARP);
-               }
-          }
-     default:
-          backchar(sc,c);
-          return (TOK_ATOM);
-     }
+static INLINE pointer
+slot_value_in_env(pointer slot) {
+    return cdr(slot);
 }
 
-/* ========== Routines for Printing ========== */
-#define   ok_abbrev(x)   (is_pair(x) && cdr(x) == sc->NIL)
-
-static void printslashstring(scheme *sc, char *p, int len) {
-  int i;
-  unsigned char *s=(unsigned char*)p;
-  putcharacter(sc,'"');
-  for ( i=0; i<len; i++) {
-    if(*s==0xff || *s=='"' || *s<' ' || *s=='\\') {
-      putcharacter(sc,'\\');
-      switch(*s) {
-      case '"':
-	putcharacter(sc,'"');
-	break;
-      case '\n':
-	putcharacter(sc,'n');
-	break;
-      case '\t':
-	putcharacter(sc,'t');
-	break;
-      case '\r':
-	putcharacter(sc,'r');
-	break;
-      case '\\':
-	putcharacter(sc,'\\');
-	break;
-      default: { 
-	  int d=*s/16;
-	  putcharacter(sc,'x');
-	  if(d<10) {
-	    putcharacter(sc,d+'0');
-	  } else {
-	    putcharacter(sc,d-10+'A');
-	  }
-	  d=*s%16;
-	  if(d<10) {
-	    putcharacter(sc,d+'0');
-	  } else {
-	    putcharacter(sc,d-10+'A');
-	  }
-	}
-      }
+/* ========== Evaluation Cycle ========== */
+
+static pointer
+_Error_1(scheme* sc, const char* s, pointer a) {
+#if USE_ERROR_HOOK
+    pointer x;
+    pointer hdl = sc->ERROR_HOOK;
+
+    x = find_slot_in_env(sc, sc->envir, hdl, 1);
+    if (x != sc->NIL) {
+        if (a != 0) {
+            sc->code = cons(sc, cons(sc, sc->QUOTE, cons(sc, (a), sc->NIL)), sc->NIL);
+        } else {
+            sc->code = sc->NIL;
+        }
+        sc->code = cons(sc, mk_string(sc, (s)), sc->code);
+        setimmutable(car(sc->code));
+        sc->code = cons(sc, slot_value_in_env(x), sc->code);
+        sc->op   = (int)OP_EVAL;
+        return sc->T;
+    }
+#endif
+
+    if (a != 0) {
+        sc->args = cons(sc, (a), sc->NIL);
     } else {
-      putcharacter(sc,*s);
+        sc->args = sc->NIL;
     }
-    s++; 
-  }
-  putcharacter(sc,'"');
+    sc->args = cons(sc, mk_string(sc, (s)), sc->args);
+    setimmutable(car(sc->args));
+    sc->op = (int)OP_ERR0;
+    return sc->T;
 }
 
+#define Error_1(sc, s, a) return _Error_1(sc, s, a)
+#define Error_0(sc, s)    return _Error_1(sc, s, 0)
 
-/* print atoms */
-static void printatom(scheme *sc, pointer l, int f) {
-  char *p;
-  int len;
-  atom2str(sc,l,f,&p,&len);
-  putchars(sc,p,len);
-}
-
+/* Too small to turn into function */
+#define BEGIN do {
+#define END \
+    }       \
+    while (0)
+#define s_goto(sc, a)  \
+    BEGIN              \
+    sc->op = (int)(a); \
+    return sc->T;      \
+    END
+
+#define s_return(sc, a) return _s_return(sc, a)
+
+#ifndef USE_SCHEME_STACK
+
+/* this structure holds all the interpreter's registers */
+struct dump_stack_frame {
+    enum scheme_opcodes op;
+    pointer             args;
+    pointer             envir;
+    pointer             code;
+};
 
-/* Uses internal buffer unless string pointer is already available */
-static void atom2str(scheme *sc, pointer l, int f, char **pp, int *plen) {
-     char *p;
-
-     if (l == sc->NIL) {
-          p = "()";
-     } else if (l == sc->T) {
-          p = "#t";
-     } else if (l == sc->F) {
-          p = "#f";
-     } else if (l == sc->EOF_OBJ) {
-          p = "#<EOF>";
-     } else if (is_port(l)) {
-          p = sc->strbuff;
-          strcpy(p, "#<PORT>");
-     } else if (is_number(l)) {
-          p = sc->strbuff;
-          if(is_integer(l)) {
-               sprintf(p, "%ld", ivalue_unchecked(l));
-          } else {
-               sprintf(p, "%.10g", rvalue_unchecked(l));
-          }
-     } else if (is_string(l)) {
-          if (!f) {
-               p = strvalue(l);
-          } else { /* Hack, uses the fact that printing is needed */
-               *pp=sc->strbuff;
-	       *plen=0;
-               printslashstring(sc, strvalue(l), strlength(l));
-	       return;
-          }
-     } else if (is_character(l)) {
-          int c=charvalue(l);
-          p = sc->strbuff;
-          if (!f) {
-               p[0]=c;
-               p[1]=0;
-          } else {
-               switch(c) {
-               case ' ':
-                    sprintf(p,"#\\space"); break;
-               case '\n':
-                    sprintf(p,"#\\newline"); break;
-               case '\r':
-                    sprintf(p,"#\\return"); break;
-               case '\t':
-                    sprintf(p,"#\\tab"); break;
-               default:
-#if USE_ASCII_NAMES
-                    if(c==127) {
-                         strcpy(p,"#\\del"); break;
-                    } else if(c<32) {
-                         strcpy(p,"#\\"); strcat(p,charnames[c]); break;
-                    }
-#else
-		    if(c<32) {
-		      sprintf(p,"#\\x%x",c); break;
-		    }
-#endif
-                    sprintf(p,"#\\%c",c); break;
-               }
-          }
-     } else if (is_symbol(l)) {
-          p = symname(l);
-     } else if (is_proc(l)) {
-          p = sc->strbuff;
-          sprintf(p, "#<%s PROCEDURE %ld>", procname(l),procnum(l));
-     } else if (is_macro(l)) {
-          p = "#<MACRO>";
-     } else if (is_closure(l)) {
-          p = "#<CLOSURE>";
-     } else if (is_promise(l)) {
-          p = "#<PROMISE>";
-     } else if (is_foreign(l)) {
-          p = sc->strbuff;
-          sprintf(p, "#<FOREIGN PROCEDURE %ld>", procnum(l));
-     } else if (is_continuation(l)) {
-          p = "#<CONTINUATION>";
-     } else {
-          p = "#<ERROR>";
-     }
-     *pp=p;
-     *plen=strlen(p);
-}
-/* ========== Routines for Evaluation Cycle ========== */
+#define STACK_GROWTH 3
 
-/* make closure. c is code. e is environment */
-static pointer mk_closure(scheme *sc, pointer c, pointer e) {
-     pointer x = get_cell(sc, c, e);
+static void
+s_save(scheme* sc, enum scheme_opcodes op, pointer args, pointer code) {
+    long                     nframes = (long)sc->dump;
+    struct dump_stack_frame* next_frame;
 
-     typeflag(x) = T_CLOSURE;
-     car(x) = c;
-     cdr(x) = e;
-     return (x);
+    /* enough room for the next frame? */
+    if (nframes >= sc->dump_size) {
+        sc->dump_size += STACK_GROWTH;
+        /* alas there is no sc->realloc */
+        sc->dump_base = realloc(sc->dump_base, sizeof(struct dump_stack_frame) * sc->dump_size);
+    }
+    next_frame        = (struct dump_stack_frame*)sc->dump_base + nframes;
+    next_frame->op    = op;
+    next_frame->args  = args;
+    next_frame->envir = sc->envir;
+    next_frame->code  = code;
+    sc->dump          = (pointer)(nframes + 1L);
 }
 
-/* make continuation. */
-static pointer mk_continuation(scheme *sc, pointer d) {
-     pointer x = get_cell(sc, sc->NIL, d);
-
-     typeflag(x) = T_CONTINUATION;
-     cont_dump(x) = d;
-     return (x);
-}
-
-static pointer list_star(scheme *sc, pointer d) {
-  pointer p, q;
-  if(cdr(d)==sc->NIL) {
-    return car(d);
-  }
-  p=cons(sc,car(d),cdr(d));
-  q=p;
-  while(cdr(cdr(p))!=sc->NIL) {
-    d=cons(sc,car(p),cdr(p));
-    if(cdr(cdr(p))!=sc->NIL) {
-      p=cdr(d);
+static pointer
+_s_return(scheme* sc, pointer a) {
+    long                     nframes = (long)sc->dump;
+    struct dump_stack_frame* frame;
+
+    sc->value = (a);
+    if (nframes <= 0) {
+        return sc->NIL;
     }
-  }
-  cdr(p)=car(cdr(p));
-  return q;
+    nframes--;
+    frame     = (struct dump_stack_frame*)sc->dump_base + nframes;
+    sc->op    = frame->op;
+    sc->args  = frame->args;
+    sc->envir = frame->envir;
+    sc->code  = frame->code;
+    sc->dump  = (pointer)nframes;
+    return sc->T;
 }
 
-/* reverse list -- produce new list */
-static pointer reverse(scheme *sc, pointer a) {
-/* a must be checked by gc */
-     pointer p = sc->NIL;
+static INLINE void
+dump_stack_reset(scheme* sc) {
+    /* in this implementation, sc->dump is the number of frames on the stack */
+    sc->dump = (pointer)0;
+}
 
-     for ( ; is_pair(a); a = cdr(a)) {
-          p = cons(sc, car(a), p);
-     }
-     return (p);
+static INLINE void
+dump_stack_initialize(scheme* sc) {
+    sc->dump_size = 0;
+    sc->dump_base = NULL;
+    dump_stack_reset(sc);
 }
 
-/* reverse list --- in-place */
-static pointer reverse_in_place(scheme *sc, pointer term, pointer list) {
-     pointer p = list, result = term, q;
+static void
+dump_stack_free(scheme* sc) {
+    free(sc->dump_base);
+    sc->dump_base = NULL;
+    sc->dump      = (pointer)0;
+    sc->dump_size = 0;
+}
 
-     while (p != sc->NIL) {
-          q = cdr(p);
-          cdr(p) = result;
-          result = p;
-          p = q;
-     }
-     return (result);
+static INLINE void
+dump_stack_mark(scheme* sc) {
+    long nframes = (long)sc->dump;
+    int  i;
+    for (i = 0; i < nframes; i++) {
+        struct dump_stack_frame* frame;
+        frame = (struct dump_stack_frame*)sc->dump_base + i;
+        mark(frame->args);
+        mark(frame->envir);
+        mark(frame->code);
+    }
 }
 
-/* append list -- produce new list */
-static pointer append(scheme *sc, pointer a, pointer b) {
-     pointer p = b, q;
+#else
 
-     if (a != sc->NIL) {
-          a = reverse(sc, a);
-          while (a != sc->NIL) {
-               q = cdr(a);
-               cdr(a) = p;
-               p = a;
-               a = q;
-          }
-     }
-     return (p);
+static INLINE void
+dump_stack_reset(scheme* sc) {
+    sc->dump = sc->NIL;
 }
 
-/* equivalence of atoms */
-static int eqv(pointer a, pointer b) {
-     if (is_string(a)) {
-          if (is_string(b))
-               return (strvalue(a) == strvalue(b));
-          else
-               return (0);
-     } else if (is_number(a)) {
-          if (is_number(b))
-               return num_eq(nvalue(a),nvalue(b));
-          else
-               return (0);
-     } else if (is_character(a)) {
-          if (is_character(b))
-               return charvalue(a)==charvalue(b);
-          else
-               return (0);
-     } else if (is_port(a)) {
-          if (is_port(b))
-               return a==b;
-          else
-               return (0);
-     } else if (is_proc(a)) {
-          if (is_proc(b))
-               return procnum(a)==procnum(b);
-          else
-               return (0);
-     } else {
-          return (a == b);
-     }
+static INLINE void
+dump_stack_initialize(scheme* sc) {
+    dump_stack_reset(sc);
 }
 
-/* true or false value macro */
-/* () is #t in R5RS */
-#define is_true(p)       ((p) != sc->F)
-#define is_false(p)      ((p) == sc->F)
-
-/* ========== Environment implementation  ========== */ 
-
-#if !defined(USE_ALIST_ENV) || !defined(USE_OBJECT_LIST) 
-
-static int hash_fn(const char *key, int table_size) 
-{ 
-  unsigned int hashed = 0; 
-  const char *c; 
-  int bits_per_int = sizeof(unsigned int)*8; 
-
-  for (c = key; *c; c++) { 
-    /* letters have about 5 bits in them */ 
-    hashed = (hashed<<5) | (hashed>>(bits_per_int-5)); 
-    hashed ^= *c; 
-  } 
-  return hashed % table_size; 
-} 
-#endif 
-
-#ifndef USE_ALIST_ENV 
-
-/* 
- * In this implementation, each frame of the environment may be 
- * a hash table: a vector of alists hashed by variable name. 
- * In practice, we use a vector only for the initial frame; 
- * subsequent frames are too small and transient for the lookup 
- * speed to out-weigh the cost of making a new vector. 
- */ 
-
-static void new_frame_in_env(scheme *sc, pointer old_env) 
-{ 
-  pointer new_frame; 
-
-  /* The interaction-environment has about 300 variables in it. */ 
-  if (old_env == sc->NIL) { 
-    new_frame = mk_vector(sc, 461); 
-  } else { 
-    new_frame = sc->NIL; 
-  } 
-
-  sc->envir = immutable_cons(sc, new_frame, old_env); 
-  setenvironment(sc->envir); 
-} 
-
-static INLINE void new_slot_spec_in_env(scheme *sc, pointer env, 
-                                        pointer variable, pointer value) 
-{ 
-  pointer slot = immutable_cons(sc, variable, value); 
-
-  if (is_vector(car(env))) { 
-    int location = hash_fn(symname(variable), ivalue_unchecked(car(env))); 
-
-    set_vector_elem(car(env), location, 
-                    immutable_cons(sc, slot, vector_elem(car(env), location))); 
-  } else { 
-    car(env) = immutable_cons(sc, slot, car(env)); 
-  } 
-} 
-
-static pointer find_slot_in_env(scheme *sc, pointer env, pointer hdl, int all) 
-{ 
-  pointer x = sc->NIL, y = sc->NIL; 
-  int location = 0; 
-
-  for (x = env; x != sc->NIL; x = cdr(x)) { 
-    if (is_vector(car(x))) { 
-      location = hash_fn(symname(hdl), ivalue_unchecked(car(x))); 
-      y = vector_elem(car(x), location); 
-    } else { 
-      y = car(x); 
-    } 
-    for ( ; y != sc->NIL; y = cdr(y)) { 
-              if (caar(y) == hdl) { 
-                   break; 
-              } 
-         } 
-         if (y != sc->NIL) { 
-              break; 
-         } 
-         if(!all) { 
-           return sc->NIL; 
-         } 
-    } 
-    if (x != sc->NIL) { 
-          return car(y); 
-    } 
-    return sc->NIL; 
-} 
-
-#else /* USE_ALIST_ENV */ 
-
-static INLINE void new_frame_in_env(scheme *sc, pointer old_env) 
-{ 
-  sc->envir = immutable_cons(sc, sc->NIL, old_env); 
-  setenvironment(sc->envir); 
-} 
-
-static INLINE void new_slot_spec_in_env(scheme *sc, pointer env, 
-                                        pointer variable, pointer value) 
-{ 
-  car(env) = immutable_cons(sc, immutable_cons(sc, variable, value), car(env)); 
-} 
-
-static pointer find_slot_in_env(scheme *sc, pointer env, pointer hdl, int all) 
-{ 
-    pointer x,y; 
-    for (x = env; x != sc->NIL; x = cdr(x)) { 
-         for (y = car(x); y != sc->NIL; y = cdr(y)) { 
-              if (caar(y) == hdl) { 
-                   break; 
-              } 
-         } 
-         if (y != sc->NIL) { 
-              break; 
-         } 
-         if(!all) { 
-           return sc->NIL; 
-         } 
-    } 
-    if (x != sc->NIL) { 
-          return car(y); 
-    } 
-    return sc->NIL; 
-} 
-
-#endif /* USE_ALIST_ENV else */ 
-
-static INLINE void new_slot_in_env(scheme *sc, pointer variable, pointer value) 
-{ 
-  new_slot_spec_in_env(sc, sc->envir, variable, value); 
-} 
-
-static INLINE void set_slot_in_env(scheme *sc, pointer slot, pointer value) 
-{ 
-  cdr(slot) = value; 
-} 
-
-static INLINE pointer slot_value_in_env(pointer slot) 
-{ 
-  return cdr(slot); 
-} 
-
-/* ========== Evaluation Cycle ========== */
-
+static void
+dump_stack_free(scheme* sc) {
+    sc->dump = sc->NIL;
+}
 
-static pointer _Error_1(scheme *sc, const char *s, pointer a) {
-#if USE_ERROR_HOOK
-     pointer x;
-     pointer hdl=sc->ERROR_HOOK;
+static pointer
+_s_return(scheme* sc, pointer a) {
+    sc->value = (a);
+    if (sc->dump == sc->NIL)
+        return sc->NIL;
+    sc->op    = ivalue(car(sc->dump));
+    sc->args  = cadr(sc->dump);
+    sc->envir = caddr(sc->dump);
+    sc->code  = cadddr(sc->dump);
+    sc->dump  = cddddr(sc->dump);
+    return sc->T;
+}
 
-     x=find_slot_in_env(sc,sc->envir,hdl,1);
-    if (x != sc->NIL) {
-         if(a!=0) {
-               sc->code = cons(sc, cons(sc, sc->QUOTE, cons(sc,(a), sc->NIL)), sc->NIL);
-         } else {
-               sc->code = sc->NIL;
-         }
-         sc->code = cons(sc, mk_string(sc, (s)), sc->code);
-         setimmutable(car(sc->code));
-         sc->code = cons(sc, slot_value_in_env(x), sc->code); 
-         sc->op = (int)OP_EVAL;
-         return sc->T;
-    }
-#endif
+static void
+s_save(scheme* sc, enum scheme_opcodes op, pointer args, pointer code) {
+    sc->dump = cons(sc, sc->envir, cons(sc, (code), sc->dump));
+    sc->dump = cons(sc, (args), sc->dump);
+    sc->dump = cons(sc, mk_integer(sc, (long)(op)), sc->dump);
+}
 
-    if(a!=0) {
-          sc->args = cons(sc, (a), sc->NIL);
-    } else {
-          sc->args = sc->NIL;
-    }
-    sc->args = cons(sc, mk_string(sc, (s)), sc->args);
-    setimmutable(car(sc->args));
-    sc->op = (int)OP_ERR0;
-    return sc->T;
+static INLINE void
+dump_stack_mark(scheme* sc) {
+    mark(sc->dump);
 }
-#define Error_1(sc,s, a) return _Error_1(sc,s,a)
-#define Error_0(sc,s)    return _Error_1(sc,s,0)
+#endif
 
-/* Too small to turn into function */
-# define  BEGIN     do {
-# define  END  } while (0)
-#define s_goto(sc,a) BEGIN                                  \
-    sc->op = (int)(a);                                      \
-    return sc->T; END
-
-#define s_return(sc,a) return _s_return(sc,a) 
-
-#ifndef USE_SCHEME_STACK 
-
-/* this structure holds all the interpreter's registers */ 
-struct dump_stack_frame { 
-  enum scheme_opcodes op; 
-  pointer args; 
-  pointer envir; 
-  pointer code; 
-}; 
-
-#define STACK_GROWTH 3 
-
-static void s_save(scheme *sc, enum scheme_opcodes op, pointer args, pointer code) 
-{ 
-  long nframes = (long)sc->dump; 
-  struct dump_stack_frame *next_frame; 
-
-  /* enough room for the next frame? */ 
-  if (nframes >= sc->dump_size) { 
-    sc->dump_size += STACK_GROWTH; 
-    /* alas there is no sc->realloc */ 
-    sc->dump_base = realloc(sc->dump_base, 
-                            sizeof(struct dump_stack_frame) * sc->dump_size); 
-  } 
-  next_frame = (struct dump_stack_frame *)sc->dump_base + nframes; 
-  next_frame->op = op; 
-  next_frame->args = args; 
-  next_frame->envir = sc->envir; 
-  next_frame->code = code; 
-  sc->dump = (pointer)(nframes+1L); 
-} 
-
-static pointer _s_return(scheme *sc, pointer a) 
-{ 
-  long nframes = (long)sc->dump; 
-  struct dump_stack_frame *frame; 
-
-  sc->value = (a); 
-  if (nframes <= 0) { 
-    return sc->NIL; 
-  } 
-  nframes--; 
-  frame = (struct dump_stack_frame *)sc->dump_base + nframes; 
-  sc->op = frame->op; 
-  sc->args = frame->args; 
-  sc->envir = frame->envir; 
-  sc->code = frame->code; 
-  sc->dump = (pointer)nframes; 
-  return sc->T; 
-} 
-
-static INLINE void dump_stack_reset(scheme *sc) 
-{ 
-  /* in this implementation, sc->dump is the number of frames on the stack */ 
-  sc->dump = (pointer)0; 
-} 
-
-static INLINE void dump_stack_initialize(scheme *sc) 
-{ 
-  sc->dump_size = 0; 
-  sc->dump_base = NULL; 
-  dump_stack_reset(sc); 
-} 
-
-static void dump_stack_free(scheme *sc) 
-{ 
-  free(sc->dump_base); 
-  sc->dump_base = NULL; 
-  sc->dump = (pointer)0; 
-  sc->dump_size = 0; 
-} 
-
-static INLINE void dump_stack_mark(scheme *sc) 
-{ 
-  long nframes = (long)sc->dump;
-  int i;
-  for(i=0; i<nframes; i++) {
-    struct dump_stack_frame *frame;
-    frame = (struct dump_stack_frame *)sc->dump_base + i;
-    mark(frame->args);
-    mark(frame->envir);
-    mark(frame->code);
-  } 
-} 
-
-#else 
-
-static INLINE void dump_stack_reset(scheme *sc) 
-{ 
-  sc->dump = sc->NIL; 
-} 
-
-static INLINE void dump_stack_initialize(scheme *sc) 
-{ 
-  dump_stack_reset(sc); 
-} 
-
-static void dump_stack_free(scheme *sc) 
-{ 
-  sc->dump = sc->NIL; 
-} 
-
-static pointer _s_return(scheme *sc, pointer a) { 
-    sc->value = (a); 
-    if(sc->dump==sc->NIL) return sc->NIL; 
-    sc->op = ivalue(car(sc->dump)); 
-    sc->args = cadr(sc->dump); 
-    sc->envir = caddr(sc->dump); 
-    sc->code = cadddr(sc->dump); 
-    sc->dump = cddddr(sc->dump); 
-    return sc->T; 
-} 
-
-static void s_save(scheme *sc, enum scheme_opcodes op, pointer args, pointer code) { 
-    sc->dump = cons(sc, sc->envir, cons(sc, (code), sc->dump)); 
-    sc->dump = cons(sc, (args), sc->dump); 
-    sc->dump = cons(sc, mk_integer(sc, (long)(op)), sc->dump); 
-} 
-
-static INLINE void dump_stack_mark(scheme *sc) 
-{ 
-  mark(sc->dump); 
-} 
-#endif 
-
-#define s_retbool(tf)    s_return(sc,(tf) ? sc->T : sc->F)
-
-static pointer opexe_0(scheme *sc, enum scheme_opcodes op) {
-     pointer x, y;
-
-     switch (op) {
-     case OP_LOAD:       /* load */
-          if(file_interactive(sc)) {
-               fprintf(sc->outport->_object._port->rep.stdio.file, 
-		       "Loading %s\n", strvalue(car(sc->args)));
-          }
-          if (!file_push(sc,strvalue(car(sc->args)))) {
-               Error_1(sc,"unable to open", car(sc->args));
-          }
-          s_goto(sc,OP_T0LVL);
-
-     case OP_T0LVL: /* top level */
-          if(file_interactive(sc)) {
-               putstr(sc,"\n");
-          }
-          sc->nesting=0;
-          dump_stack_reset(sc); 
-          sc->envir = sc->global_env;
-	  sc->save_inport=sc->inport;
-          sc->inport = sc->loadport;
-	  s_save(sc,OP_T0LVL, sc->NIL, sc->NIL);
-          s_save(sc,OP_VALUEPRINT, sc->NIL, sc->NIL);
-          s_save(sc,OP_T1LVL, sc->NIL, sc->NIL);
-          if (file_interactive(sc)) {
-              putstr(sc,prompt);
-          }
-          s_goto(sc,OP_READ_INTERNAL);
-
-     case OP_T1LVL: /* top level */
-          sc->code = sc->value;
-          sc->inport=sc->save_inport;
-          s_goto(sc,OP_EVAL);
-
-     case OP_READ_INTERNAL:       /* internal read */
-          sc->tok = token(sc);
-          if(sc->tok==TOK_EOF) {
-               if(sc->inport==sc->loadport) {
-                    sc->args=sc->NIL;
-                    s_goto(sc,OP_QUIT);
-               } else {
-                    s_return(sc,sc->EOF_OBJ);
-               }
-          }
-          s_goto(sc,OP_RDSEXPR);
-
-     case OP_GENSYM:
-          s_return(sc, gensym(sc));
-
-     case OP_VALUEPRINT: /* print evaluation result */
-          /* OP_VALUEPRINT is always pushed, because when changing from
-             non-interactive to interactive mode, it needs to be
-             already on the stack */
-       if(sc->tracing) {
-	 putstr(sc,"\nGives: ");
-       }
-       if(file_interactive(sc)) {
-	 sc->print_flag = 1;
-	 sc->args = sc->value;
-	 s_goto(sc,OP_P0LIST);
-       } else {
-	 s_return(sc,sc->value);
-       }
-
-     case OP_EVAL:       /* main part of evaluation */
+#define s_retbool(tf) s_return(sc, (tf) ? sc->T : sc->F)
+
+static pointer
+opexe_0(scheme* sc, enum scheme_opcodes op) {
+    pointer x, y;
+
+    switch (op) {
+        case OP_LOAD: /* load */
+            if (file_interactive(sc)) {
+                fprintf(sc->outport->_object._port->rep.stdio.file, "Loading %s\n", strvalue(car(sc->args)));
+            }
+            if (!file_push(sc, strvalue(car(sc->args)))) {
+                Error_1(sc, "unable to open", car(sc->args));
+            }
+            s_goto(sc, OP_T0LVL);
+
+        case OP_T0LVL: /* top level */
+            if (file_interactive(sc)) {
+                putstr(sc, "\n");
+            }
+            sc->nesting = 0;
+            dump_stack_reset(sc);
+            sc->envir       = sc->global_env;
+            sc->save_inport = sc->inport;
+            sc->inport      = sc->loadport;
+            s_save(sc, OP_T0LVL, sc->NIL, sc->NIL);
+            s_save(sc, OP_VALUEPRINT, sc->NIL, sc->NIL);
+            s_save(sc, OP_T1LVL, sc->NIL, sc->NIL);
+            if (file_interactive(sc)) {
+                putstr(sc, prompt);
+            }
+            s_goto(sc, OP_READ_INTERNAL);
+
+        case OP_T1LVL: /* top level */
+            sc->code   = sc->value;
+            sc->inport = sc->save_inport;
+            s_goto(sc, OP_EVAL);
+
+        case OP_READ_INTERNAL: /* internal read */
+            sc->tok = token(sc);
+            if (sc->tok == TOK_EOF) {
+                if (sc->inport == sc->loadport) {
+                    sc->args = sc->NIL;
+                    s_goto(sc, OP_QUIT);
+                } else {
+                    s_return(sc, sc->EOF_OBJ);
+                }
+            }
+            s_goto(sc, OP_RDSEXPR);
+
+        case OP_GENSYM: s_return(sc, gensym(sc));
+
+        case OP_VALUEPRINT: /* print evaluation result */
+                            /* OP_VALUEPRINT is always pushed, because when changing from
+                               non-interactive to interactive mode, it needs to be
+                               already on the stack */
+            if (sc->tracing) {
+                putstr(sc, "\nGives: ");
+            }
+            if (file_interactive(sc)) {
+                sc->print_flag = 1;
+                sc->args       = sc->value;
+                s_goto(sc, OP_P0LIST);
+            } else {
+                s_return(sc, sc->value);
+            }
+
+        case OP_EVAL: /* main part of evaluation */
 #if USE_TRACING
-       if(sc->tracing) {
-	 /*s_save(sc,OP_VALUEPRINT,sc->NIL,sc->NIL);*/
-	 s_save(sc,OP_REAL_EVAL,sc->args,sc->code);
-	 sc->args=sc->code;
-	 putstr(sc,"\nEval: ");
-	 s_goto(sc,OP_P0LIST);
-       }
-       /* fall through */
-     case OP_REAL_EVAL:
+            if (sc->tracing) {
+                /*s_save(sc,OP_VALUEPRINT,sc->NIL,sc->NIL);*/
+                s_save(sc, OP_REAL_EVAL, sc->args, sc->code);
+                sc->args = sc->code;
+                putstr(sc, "\nEval: ");
+                s_goto(sc, OP_P0LIST);
+            }
+            /* fall through */
+        case OP_REAL_EVAL:
 #endif
-          if (is_symbol(sc->code)) {    /* symbol */
-               x=find_slot_in_env(sc,sc->envir,sc->code,1);
-               if (x != sc->NIL) {
-                    s_return(sc,slot_value_in_env(x)); 
-               } else {
-                    Error_1(sc,"eval: unbound variable:", sc->code);
-               }
-          } else if (is_pair(sc->code)) {
-               if (is_syntax(x = car(sc->code))) {     /* SYNTAX */
+            if (is_symbol(sc->code)) { /* symbol */
+                x = find_slot_in_env(sc, sc->envir, sc->code, 1);
+                if (x != sc->NIL) {
+                    s_return(sc, slot_value_in_env(x));
+                } else {
+                    Error_1(sc, "eval: unbound variable:", sc->code);
+                }
+            } else if (is_pair(sc->code)) {
+                if (is_syntax(x = car(sc->code))) { /* SYNTAX */
                     sc->code = cdr(sc->code);
-                    s_goto(sc,syntaxnum(x));
-               } else {/* first, eval top element and eval arguments */
-                    s_save(sc,OP_E0ARGS, sc->NIL, sc->code);
+                    s_goto(sc, syntaxnum(x));
+                } else { /* first, eval top element and eval arguments */
+                    s_save(sc, OP_E0ARGS, sc->NIL, sc->code);
                     /* If no macros => s_save(sc,OP_E1ARGS, sc->NIL, cdr(sc->code));*/
                     sc->code = car(sc->code);
-                    s_goto(sc,OP_EVAL);
-               }
-          } else {
-               s_return(sc,sc->code);
-          }
-
-     case OP_E0ARGS:     /* eval arguments */
-          if (is_macro(sc->value)) {    /* macro expansion */
-               s_save(sc,OP_DOMACRO, sc->NIL, sc->NIL);
-               sc->args = cons(sc,sc->code, sc->NIL);
-               sc->code = sc->value;
-               s_goto(sc,OP_APPLY);
-          } else {
-               sc->code = cdr(sc->code);
-               s_goto(sc,OP_E1ARGS);
-          }
-
-     case OP_E1ARGS:     /* eval arguments */
-          sc->args = cons(sc, sc->value, sc->args);
-          if (is_pair(sc->code)) { /* continue */
-               s_save(sc,OP_E1ARGS, sc->args, cdr(sc->code));
-               sc->code = car(sc->code);
-               sc->args = sc->NIL;
-               s_goto(sc,OP_EVAL);
-          } else {  /* end */
-               sc->args = reverse_in_place(sc, sc->NIL, sc->args); 
-               sc->code = car(sc->args);
-               sc->args = cdr(sc->args);
-               s_goto(sc,OP_APPLY);
-          }
+                    s_goto(sc, OP_EVAL);
+                }
+            } else {
+                s_return(sc, sc->code);
+            }
+
+        case OP_E0ARGS:                /* eval arguments */
+            if (is_macro(sc->value)) { /* macro expansion */
+                s_save(sc, OP_DOMACRO, sc->NIL, sc->NIL);
+                sc->args = cons(sc, sc->code, sc->NIL);
+                sc->code = sc->value;
+                s_goto(sc, OP_APPLY);
+            } else {
+                sc->code = cdr(sc->code);
+                s_goto(sc, OP_E1ARGS);
+            }
+
+        case OP_E1ARGS: /* eval arguments */
+            sc->args = cons(sc, sc->value, sc->args);
+            if (is_pair(sc->code)) { /* continue */
+                s_save(sc, OP_E1ARGS, sc->args, cdr(sc->code));
+                sc->code = car(sc->code);
+                sc->args = sc->NIL;
+                s_goto(sc, OP_EVAL);
+            } else { /* end */
+                sc->args = reverse_in_place(sc, sc->NIL, sc->args);
+                sc->code = car(sc->args);
+                sc->args = cdr(sc->args);
+                s_goto(sc, OP_APPLY);
+            }
 
 #if USE_TRACING
-     case OP_TRACING: {
-       int tr=sc->tracing;
-       sc->tracing=ivalue(car(sc->args));
-       s_return(sc,mk_integer(sc,tr));
-     }
+        case OP_TRACING:
+            {
+                int tr      = sc->tracing;
+                sc->tracing = ivalue(car(sc->args));
+                s_return(sc, mk_integer(sc, tr));
+            }
 #endif
 
-     case OP_APPLY:      /* apply 'code' to 'args' */
+        case OP_APPLY: /* apply 'code' to 'args' */
 #if USE_TRACING
-       if(sc->tracing) {
-	 s_save(sc,OP_REAL_APPLY,sc->args,sc->code);
-	 sc->print_flag = 1;
-	 /*	 sc->args=cons(sc,sc->code,sc->args);*/
-         putstr(sc,"\nApply to: ");
-	 s_goto(sc,OP_P0LIST);
-       }
-       /* fall through */
-     case OP_REAL_APPLY:
+            if (sc->tracing) {
+                s_save(sc, OP_REAL_APPLY, sc->args, sc->code);
+                sc->print_flag = 1;
+                /*	 sc->args=cons(sc,sc->code,sc->args);*/
+                putstr(sc, "\nApply to: ");
+                s_goto(sc, OP_P0LIST);
+            }
+            /* fall through */
+        case OP_REAL_APPLY:
 #endif
-          if (is_proc(sc->code)) {
-               s_goto(sc,procnum(sc->code));   /* PROCEDURE */
-          } else if (is_foreign(sc->code)) {
-               x=sc->code->_object._ff(sc,sc->args);
-               s_return(sc,x);
-          } else if (is_closure(sc->code) || is_macro(sc->code) 
-		     || is_promise(sc->code)) { /* CLOSURE */
-	    /* Should not accept promise */
-               /* make environment */
-               new_frame_in_env(sc, closure_env(sc->code)); 
-               for (x = car(closure_code(sc->code)), y = sc->args;
-                    is_pair(x); x = cdr(x), y = cdr(y)) {
+            if (is_proc(sc->code)) {
+                s_goto(sc, procnum(sc->code)); /* PROCEDURE */
+            } else if (is_foreign(sc->code)) {
+                x = sc->code->_object._ff(sc, sc->args);
+                s_return(sc, x);
+            } else if (is_closure(sc->code) || is_macro(sc->code) || is_promise(sc->code)) { /* CLOSURE */
+                /* Should not accept promise */
+                /* make environment */
+                new_frame_in_env(sc, closure_env(sc->code));
+                for (x = car(closure_code(sc->code)), y = sc->args; is_pair(x); x = cdr(x), y = cdr(y)) {
                     if (y == sc->NIL) {
-                         Error_0(sc,"not enough arguments");
+                        Error_0(sc, "not enough arguments");
                     } else {
-                         new_slot_in_env(sc, car(x), car(y)); 
+                        new_slot_in_env(sc, car(x), car(y));
                     }
-               }
-               if (x == sc->NIL) {
+                }
+                if (x == sc->NIL) {
                     /*--
                      * if (y != sc->NIL) {
                      *   Error_0(sc,"too many arguments");
                      * }
                      */
-               } else if (is_symbol(x))
-                    new_slot_in_env(sc, x, y); 
-               else {
-                    Error_1(sc,"syntax error in closure: not a symbol:", x); 
-               }
-               sc->code = cdr(closure_code(sc->code));
-               sc->args = sc->NIL;
-               s_goto(sc,OP_BEGIN);
-          } else if (is_continuation(sc->code)) { /* CONTINUATION */
-               sc->dump = cont_dump(sc->code);
-               s_return(sc,sc->args != sc->NIL ? car(sc->args) : sc->NIL);
-          } else {
-               Error_0(sc,"illegal function");
-          }
-
-     case OP_DOMACRO:    /* do macro */
-          sc->code = sc->value;
-          s_goto(sc,OP_EVAL);
-
-     case OP_LAMBDA:     /* lambda */
-          s_return(sc,mk_closure(sc, sc->code, sc->envir));
-
-     case OP_MKCLOSURE: /* make-closure */
-       x=car(sc->args);
-       if(car(x)==sc->LAMBDA) {
-	 x=cdr(x);
-       }
-       if(cdr(sc->args)==sc->NIL) {
-	 y=sc->envir;
-       } else {
-	 y=cadr(sc->args);
-       }
-       s_return(sc,mk_closure(sc, x, y));
-
-     case OP_QUOTE:      /* quote */
-          x=car(sc->code);
-          s_return(sc,car(sc->code));
-
-     case OP_DEF0:  /* define */
-          if (is_pair(car(sc->code))) {
-               x = caar(sc->code);
-               sc->code = cons(sc, sc->LAMBDA, cons(sc, cdar(sc->code), cdr(sc->code)));
-          } else {
-               x = car(sc->code);
-               sc->code = cadr(sc->code);
-          }
-          if (!is_symbol(x)) {
-               Error_0(sc,"variable is not a symbol");
-          }
-          s_save(sc,OP_DEF1, sc->NIL, x);
-          s_goto(sc,OP_EVAL);
-
-     case OP_DEF1:  /* define */
-       x=find_slot_in_env(sc,sc->envir,sc->code,0);
-          if (x != sc->NIL) {
-               set_slot_in_env(sc, x, sc->value); 
-          } else {
-               new_slot_in_env(sc, sc->code, sc->value); 
-          }
-          s_return(sc,sc->code);
-
-
-     case OP_DEFP:  /* defined? */
-          x=sc->envir;
-          if(cdr(sc->args)!=sc->NIL) {
-               x=cadr(sc->args);
-          }
-          s_retbool(find_slot_in_env(sc,x,car(sc->args),1)!=sc->NIL);
-
-     case OP_SET0:       /* set! */
-          s_save(sc,OP_SET1, sc->NIL, car(sc->code));
-          sc->code = cadr(sc->code);
-          s_goto(sc,OP_EVAL);
-
-     case OP_SET1:       /* set! */
-       y=find_slot_in_env(sc,sc->envir,sc->code,1);
-          if (y != sc->NIL) {
-               set_slot_in_env(sc, y, sc->value); 
-               s_return(sc,sc->value);
-          } else {
-               Error_1(sc,"set!: unbound variable:", sc->code); 
-          }
-
-
-     case OP_BEGIN:      /* begin */
-          if (!is_pair(sc->code)) {
-               s_return(sc,sc->code);
-          }
-          if (cdr(sc->code) != sc->NIL) {
-               s_save(sc,OP_BEGIN, sc->NIL, cdr(sc->code));
-          }
-          sc->code = car(sc->code);
-          s_goto(sc,OP_EVAL);
-
-     case OP_IF0:        /* if */
-          s_save(sc,OP_IF1, sc->NIL, cdr(sc->code));
-          sc->code = car(sc->code);
-          s_goto(sc,OP_EVAL);
-
-     case OP_IF1:        /* if */
-          if (is_true(sc->value))
-               sc->code = car(sc->code);
-          else
-               sc->code = cadr(sc->code);  /* (if #f 1) ==> () because
-                               * car(sc->NIL) = sc->NIL */
-          s_goto(sc,OP_EVAL);
-
-     case OP_LET0:       /* let */
-          sc->args = sc->NIL;
-          sc->value = sc->code;
-          sc->code = is_symbol(car(sc->code)) ? cadr(sc->code) : car(sc->code);
-          s_goto(sc,OP_LET1);
-
-     case OP_LET1:       /* let (calculate parameters) */
-          sc->args = cons(sc, sc->value, sc->args);
-          if (is_pair(sc->code)) { /* continue */
-               s_save(sc,OP_LET1, sc->args, cdr(sc->code));
-               sc->code = cadar(sc->code);
-               sc->args = sc->NIL;
-               s_goto(sc,OP_EVAL);
-          } else {  /* end */
-               sc->args = reverse_in_place(sc, sc->NIL, sc->args);
-               sc->code = car(sc->args);
-               sc->args = cdr(sc->args);
-               s_goto(sc,OP_LET2);
-          }
-
-     case OP_LET2:       /* let */
-          new_frame_in_env(sc, sc->envir); 
-          for (x = is_symbol(car(sc->code)) ? cadr(sc->code) : car(sc->code), y = sc->args;
-               y != sc->NIL; x = cdr(x), y = cdr(y)) {
-               new_slot_in_env(sc, caar(x), car(y)); 
-          }
-          if (is_symbol(car(sc->code))) {    /* named let */
-               for (x = cadr(sc->code), sc->args = sc->NIL; x != sc->NIL; x = cdr(x)) {
+                } else if (is_symbol(x))
+                    new_slot_in_env(sc, x, y);
+                else {
+                    Error_1(sc, "syntax error in closure: not a symbol:", x);
+                }
+                sc->code = cdr(closure_code(sc->code));
+                sc->args = sc->NIL;
+                s_goto(sc, OP_BEGIN);
+            } else if (is_continuation(sc->code)) { /* CONTINUATION */
+                sc->dump = cont_dump(sc->code);
+                s_return(sc, sc->args != sc->NIL ? car(sc->args) : sc->NIL);
+            } else {
+                Error_0(sc, "illegal function");
+            }
+
+        case OP_DOMACRO: /* do macro */ sc->code = sc->value; s_goto(sc, OP_EVAL);
+
+        case OP_LAMBDA: /* lambda */ s_return(sc, mk_closure(sc, sc->code, sc->envir));
+
+        case OP_MKCLOSURE: /* make-closure */
+            x = car(sc->args);
+            if (car(x) == sc->LAMBDA) {
+                x = cdr(x);
+            }
+            if (cdr(sc->args) == sc->NIL) {
+                y = sc->envir;
+            } else {
+                y = cadr(sc->args);
+            }
+            s_return(sc, mk_closure(sc, x, y));
+
+        case OP_QUOTE: /* quote */ x = car(sc->code); s_return(sc, car(sc->code));
+
+        case OP_DEF0: /* define */
+            if (is_pair(car(sc->code))) {
+                x        = caar(sc->code);
+                sc->code = cons(sc, sc->LAMBDA, cons(sc, cdar(sc->code), cdr(sc->code)));
+            } else {
+                x        = car(sc->code);
+                sc->code = cadr(sc->code);
+            }
+            if (!is_symbol(x)) {
+                Error_0(sc, "variable is not a symbol");
+            }
+            s_save(sc, OP_DEF1, sc->NIL, x);
+            s_goto(sc, OP_EVAL);
+
+        case OP_DEF1: /* define */
+            x = find_slot_in_env(sc, sc->envir, sc->code, 0);
+            if (x != sc->NIL) {
+                set_slot_in_env(sc, x, sc->value);
+            } else {
+                new_slot_in_env(sc, sc->code, sc->value);
+            }
+            s_return(sc, sc->code);
+
+        case OP_DEFP: /* defined? */
+            x = sc->envir;
+            if (cdr(sc->args) != sc->NIL) {
+                x = cadr(sc->args);
+            }
+            s_retbool(find_slot_in_env(sc, x, car(sc->args), 1) != sc->NIL);
+
+        case OP_SET0: /* set! */
+            s_save(sc, OP_SET1, sc->NIL, car(sc->code));
+            sc->code = cadr(sc->code);
+            s_goto(sc, OP_EVAL);
+
+        case OP_SET1: /* set! */
+            y = find_slot_in_env(sc, sc->envir, sc->code, 1);
+            if (y != sc->NIL) {
+                set_slot_in_env(sc, y, sc->value);
+                s_return(sc, sc->value);
+            } else {
+                Error_1(sc, "set!: unbound variable:", sc->code);
+            }
+
+        case OP_BEGIN: /* begin */
+            if (!is_pair(sc->code)) {
+                s_return(sc, sc->code);
+            }
+            if (cdr(sc->code) != sc->NIL) {
+                s_save(sc, OP_BEGIN, sc->NIL, cdr(sc->code));
+            }
+            sc->code = car(sc->code);
+            s_goto(sc, OP_EVAL);
+
+        case OP_IF0: /* if */
+            s_save(sc, OP_IF1, sc->NIL, cdr(sc->code));
+            sc->code = car(sc->code);
+            s_goto(sc, OP_EVAL);
+
+        case OP_IF1: /* if */
+            if (is_true(sc->value))
+                sc->code = car(sc->code);
+            else
+                sc->code = cadr(sc->code); /* (if #f 1) ==> () because
+                                            * car(sc->NIL) = sc->NIL */
+            s_goto(sc, OP_EVAL);
+
+        case OP_LET0: /* let */
+            sc->args  = sc->NIL;
+            sc->value = sc->code;
+            sc->code  = is_symbol(car(sc->code)) ? cadr(sc->code) : car(sc->code);
+            s_goto(sc, OP_LET1);
+
+        case OP_LET1: /* let (calculate parameters) */
+            sc->args = cons(sc, sc->value, sc->args);
+            if (is_pair(sc->code)) { /* continue */
+                s_save(sc, OP_LET1, sc->args, cdr(sc->code));
+                sc->code = cadar(sc->code);
+                sc->args = sc->NIL;
+                s_goto(sc, OP_EVAL);
+            } else { /* end */
+                sc->args = reverse_in_place(sc, sc->NIL, sc->args);
+                sc->code = car(sc->args);
+                sc->args = cdr(sc->args);
+                s_goto(sc, OP_LET2);
+            }
+
+        case OP_LET2: /* let */
+            new_frame_in_env(sc, sc->envir);
+            for (x = is_symbol(car(sc->code)) ? cadr(sc->code) : car(sc->code), y = sc->args; y != sc->NIL;
+                 x = cdr(x), y = cdr(y)) {
+                new_slot_in_env(sc, caar(x), car(y));
+            }
+            if (is_symbol(car(sc->code))) { /* named let */
+                for (x = cadr(sc->code), sc->args = sc->NIL; x != sc->NIL; x = cdr(x)) {
 
                     sc->args = cons(sc, caar(x), sc->args);
-               }
-               x = mk_closure(sc, cons(sc, reverse_in_place(sc, sc->NIL, sc->args), cddr(sc->code)), sc->envir); 
-               new_slot_in_env(sc, car(sc->code), x); 
-               sc->code = cddr(sc->code);
-               sc->args = sc->NIL;
-          } else {
-               sc->code = cdr(sc->code);
-               sc->args = sc->NIL;
-          }
-          s_goto(sc,OP_BEGIN);
-
-     case OP_LET0AST:    /* let* */
-          if (car(sc->code) == sc->NIL) {
-               new_frame_in_env(sc, sc->envir); 
-               sc->code = cdr(sc->code);
-               s_goto(sc,OP_BEGIN);
-          }
-          s_save(sc,OP_LET1AST, cdr(sc->code), car(sc->code));
-          sc->code = cadaar(sc->code);
-          s_goto(sc,OP_EVAL);
-
-     case OP_LET1AST:    /* let* (make new frame) */
-          new_frame_in_env(sc, sc->envir); 
-          s_goto(sc,OP_LET2AST);
-
-     case OP_LET2AST:    /* let* (calculate parameters) */
-          new_slot_in_env(sc, caar(sc->code), sc->value); 
-          sc->code = cdr(sc->code);
-          if (is_pair(sc->code)) { /* continue */
-               s_save(sc,OP_LET2AST, sc->args, sc->code);
-               sc->code = cadar(sc->code);
-               sc->args = sc->NIL;
-               s_goto(sc,OP_EVAL);
-          } else {  /* end */
-               sc->code = sc->args;
-               sc->args = sc->NIL;
-               s_goto(sc,OP_BEGIN);
-          }
-     default:
-          sprintf(sc->strbuff, "%d: illegal operator", sc->op);
-          Error_0(sc,sc->strbuff);
-     }
-     return sc->T;
-}
-
-static pointer opexe_1(scheme *sc, enum scheme_opcodes op) {
-     pointer x, y;
-
-     switch (op) {
-     case OP_LET0REC:    /* letrec */
-          new_frame_in_env(sc, sc->envir); 
-          sc->args = sc->NIL;
-          sc->value = sc->code;
-          sc->code = car(sc->code);
-          s_goto(sc,OP_LET1REC);
-
-     case OP_LET1REC:    /* letrec (calculate parameters) */
-          sc->args = cons(sc, sc->value, sc->args);
-          if (is_pair(sc->code)) { /* continue */
-               s_save(sc,OP_LET1REC, sc->args, cdr(sc->code));
-               sc->code = cadar(sc->code);
-               sc->args = sc->NIL;
-               s_goto(sc,OP_EVAL);
-          } else {  /* end */
-               sc->args = reverse_in_place(sc, sc->NIL, sc->args); 
-               sc->code = car(sc->args);
-               sc->args = cdr(sc->args);
-               s_goto(sc,OP_LET2REC);
-          }
-
-     case OP_LET2REC:    /* letrec */
-          for (x = car(sc->code), y = sc->args; y != sc->NIL; x = cdr(x), y = cdr(y)) {
-               new_slot_in_env(sc, caar(x), car(y)); 
-          }
-          sc->code = cdr(sc->code);
-          sc->args = sc->NIL;
-          s_goto(sc,OP_BEGIN);
-
-     case OP_COND0:      /* cond */
-          if (!is_pair(sc->code)) {
-               Error_0(sc,"syntax error in cond");
-          }
-          s_save(sc,OP_COND1, sc->NIL, sc->code);
-          sc->code = caar(sc->code);
-          s_goto(sc,OP_EVAL);
-
-     case OP_COND1:      /* cond */
-          if (is_true(sc->value)) {
-               if ((sc->code = cdar(sc->code)) == sc->NIL) {
-                    s_return(sc,sc->value);
-               }
-               if(car(sc->code)==sc->FEED_TO) {
-                    if(!is_pair(cdr(sc->code))) {
-                         Error_0(sc,"syntax error in cond");
+                }
+                x = mk_closure(sc, cons(sc, reverse_in_place(sc, sc->NIL, sc->args), cddr(sc->code)), sc->envir);
+                new_slot_in_env(sc, car(sc->code), x);
+                sc->code = cddr(sc->code);
+                sc->args = sc->NIL;
+            } else {
+                sc->code = cdr(sc->code);
+                sc->args = sc->NIL;
+            }
+            s_goto(sc, OP_BEGIN);
+
+        case OP_LET0AST: /* let* */
+            if (car(sc->code) == sc->NIL) {
+                new_frame_in_env(sc, sc->envir);
+                sc->code = cdr(sc->code);
+                s_goto(sc, OP_BEGIN);
+            }
+            s_save(sc, OP_LET1AST, cdr(sc->code), car(sc->code));
+            sc->code = cadaar(sc->code);
+            s_goto(sc, OP_EVAL);
+
+        case OP_LET1AST: /* let* (make new frame) */ new_frame_in_env(sc, sc->envir); s_goto(sc, OP_LET2AST);
+
+        case OP_LET2AST: /* let* (calculate parameters) */
+            new_slot_in_env(sc, caar(sc->code), sc->value);
+            sc->code = cdr(sc->code);
+            if (is_pair(sc->code)) { /* continue */
+                s_save(sc, OP_LET2AST, sc->args, sc->code);
+                sc->code = cadar(sc->code);
+                sc->args = sc->NIL;
+                s_goto(sc, OP_EVAL);
+            } else { /* end */
+                sc->code = sc->args;
+                sc->args = sc->NIL;
+                s_goto(sc, OP_BEGIN);
+            }
+        default: sprintf(sc->strbuff, "%d: illegal operator", sc->op); Error_0(sc, sc->strbuff);
+    }
+    return sc->T;
+}
+
+static pointer
+opexe_1(scheme* sc, enum scheme_opcodes op) {
+    pointer x, y;
+
+    switch (op) {
+        case OP_LET0REC: /* letrec */
+            new_frame_in_env(sc, sc->envir);
+            sc->args  = sc->NIL;
+            sc->value = sc->code;
+            sc->code  = car(sc->code);
+            s_goto(sc, OP_LET1REC);
+
+        case OP_LET1REC: /* letrec (calculate parameters) */
+            sc->args = cons(sc, sc->value, sc->args);
+            if (is_pair(sc->code)) { /* continue */
+                s_save(sc, OP_LET1REC, sc->args, cdr(sc->code));
+                sc->code = cadar(sc->code);
+                sc->args = sc->NIL;
+                s_goto(sc, OP_EVAL);
+            } else { /* end */
+                sc->args = reverse_in_place(sc, sc->NIL, sc->args);
+                sc->code = car(sc->args);
+                sc->args = cdr(sc->args);
+                s_goto(sc, OP_LET2REC);
+            }
+
+        case OP_LET2REC: /* letrec */
+            for (x = car(sc->code), y = sc->args; y != sc->NIL; x = cdr(x), y = cdr(y)) {
+                new_slot_in_env(sc, caar(x), car(y));
+            }
+            sc->code = cdr(sc->code);
+            sc->args = sc->NIL;
+            s_goto(sc, OP_BEGIN);
+
+        case OP_COND0: /* cond */
+            if (!is_pair(sc->code)) {
+                Error_0(sc, "syntax error in cond");
+            }
+            s_save(sc, OP_COND1, sc->NIL, sc->code);
+            sc->code = caar(sc->code);
+            s_goto(sc, OP_EVAL);
+
+        case OP_COND1: /* cond */
+            if (is_true(sc->value)) {
+                if ((sc->code = cdar(sc->code)) == sc->NIL) {
+                    s_return(sc, sc->value);
+                }
+                if (car(sc->code) == sc->FEED_TO) {
+                    if (!is_pair(cdr(sc->code))) {
+                        Error_0(sc, "syntax error in cond");
                     }
-                    x=cons(sc, sc->QUOTE, cons(sc, sc->value, sc->NIL));
-                    sc->code=cons(sc,cadr(sc->code),cons(sc,x,sc->NIL));
-                    s_goto(sc,OP_EVAL);
-               }
-               s_goto(sc,OP_BEGIN);
-          } else {
-               if ((sc->code = cdr(sc->code)) == sc->NIL) {
-                    s_return(sc,sc->NIL);
-               } else {
-                    s_save(sc,OP_COND1, sc->NIL, sc->code);
+                    x        = cons(sc, sc->QUOTE, cons(sc, sc->value, sc->NIL));
+                    sc->code = cons(sc, cadr(sc->code), cons(sc, x, sc->NIL));
+                    s_goto(sc, OP_EVAL);
+                }
+                s_goto(sc, OP_BEGIN);
+            } else {
+                if ((sc->code = cdr(sc->code)) == sc->NIL) {
+                    s_return(sc, sc->NIL);
+                } else {
+                    s_save(sc, OP_COND1, sc->NIL, sc->code);
                     sc->code = caar(sc->code);
-                    s_goto(sc,OP_EVAL);
-               }
-          }
-
-     case OP_DELAY:      /* delay */
-          x = mk_closure(sc, cons(sc, sc->NIL, sc->code), sc->envir);
-          typeflag(x)=T_PROMISE;
-          s_return(sc,x);
-
-     case OP_AND0:       /* and */
-          if (sc->code == sc->NIL) {
-               s_return(sc,sc->T);
-          }
-          s_save(sc,OP_AND1, sc->NIL, cdr(sc->code));
-          sc->code = car(sc->code);
-          s_goto(sc,OP_EVAL);
-
-     case OP_AND1:       /* and */
-          if (is_false(sc->value)) {
-               s_return(sc,sc->value);
-          } else if (sc->code == sc->NIL) {
-               s_return(sc,sc->value);
-          } else {
-               s_save(sc,OP_AND1, sc->NIL, cdr(sc->code));
-               sc->code = car(sc->code);
-               s_goto(sc,OP_EVAL);
-          }
-
-     case OP_OR0:        /* or */
-          if (sc->code == sc->NIL) {
-               s_return(sc,sc->F);
-          }
-          s_save(sc,OP_OR1, sc->NIL, cdr(sc->code));
-          sc->code = car(sc->code);
-          s_goto(sc,OP_EVAL);
-
-     case OP_OR1:        /* or */
-          if (is_true(sc->value)) {
-               s_return(sc,sc->value);
-          } else if (sc->code == sc->NIL) {
-               s_return(sc,sc->value);
-          } else {
-               s_save(sc,OP_OR1, sc->NIL, cdr(sc->code));
-               sc->code = car(sc->code);
-               s_goto(sc,OP_EVAL);
-          }
-
-     case OP_C0STREAM:   /* cons-stream */
-          s_save(sc,OP_C1STREAM, sc->NIL, cdr(sc->code));
-          sc->code = car(sc->code);
-          s_goto(sc,OP_EVAL);
-
-     case OP_C1STREAM:   /* cons-stream */
-          sc->args = sc->value;  /* save sc->value to register sc->args for gc */
-          x = mk_closure(sc, cons(sc, sc->NIL, sc->code), sc->envir);
-          typeflag(x)=T_PROMISE;
-          s_return(sc,cons(sc, sc->args, x));
-
-     case OP_MACRO0:     /* macro */
-          if (is_pair(car(sc->code))) {
-               x = caar(sc->code);
-               sc->code = cons(sc, sc->LAMBDA, cons(sc, cdar(sc->code), cdr(sc->code)));
-          } else {
-               x = car(sc->code);
-               sc->code = cadr(sc->code);
-          }
-          if (!is_symbol(x)) {
-               Error_0(sc,"variable is not a symbol");
-          }
-          s_save(sc,OP_MACRO1, sc->NIL, x);
-          s_goto(sc,OP_EVAL);
-
-     case OP_MACRO1:     /* macro */
-          typeflag(sc->value) = T_MACRO;
-          x = find_slot_in_env(sc, sc->envir, sc->code, 0); 
-          if (x != sc->NIL) {
-               set_slot_in_env(sc, x, sc->value); 
-          } else {
-               new_slot_in_env(sc, sc->code, sc->value); 
-          }
-          s_return(sc,sc->code);
-
-     case OP_CASE0:      /* case */
-          s_save(sc,OP_CASE1, sc->NIL, cdr(sc->code));
-          sc->code = car(sc->code);
-          s_goto(sc,OP_EVAL);
-
-     case OP_CASE1:      /* case */
-          for (x = sc->code; x != sc->NIL; x = cdr(x)) {
-               if (!is_pair(y = caar(x))) {
+                    s_goto(sc, OP_EVAL);
+                }
+            }
+
+        case OP_DELAY: /* delay */
+            x           = mk_closure(sc, cons(sc, sc->NIL, sc->code), sc->envir);
+            typeflag(x) = T_PROMISE;
+            s_return(sc, x);
+
+        case OP_AND0: /* and */
+            if (sc->code == sc->NIL) {
+                s_return(sc, sc->T);
+            }
+            s_save(sc, OP_AND1, sc->NIL, cdr(sc->code));
+            sc->code = car(sc->code);
+            s_goto(sc, OP_EVAL);
+
+        case OP_AND1: /* and */
+            if (is_false(sc->value)) {
+                s_return(sc, sc->value);
+            } else if (sc->code == sc->NIL) {
+                s_return(sc, sc->value);
+            } else {
+                s_save(sc, OP_AND1, sc->NIL, cdr(sc->code));
+                sc->code = car(sc->code);
+                s_goto(sc, OP_EVAL);
+            }
+
+        case OP_OR0: /* or */
+            if (sc->code == sc->NIL) {
+                s_return(sc, sc->F);
+            }
+            s_save(sc, OP_OR1, sc->NIL, cdr(sc->code));
+            sc->code = car(sc->code);
+            s_goto(sc, OP_EVAL);
+
+        case OP_OR1: /* or */
+            if (is_true(sc->value)) {
+                s_return(sc, sc->value);
+            } else if (sc->code == sc->NIL) {
+                s_return(sc, sc->value);
+            } else {
+                s_save(sc, OP_OR1, sc->NIL, cdr(sc->code));
+                sc->code = car(sc->code);
+                s_goto(sc, OP_EVAL);
+            }
+
+        case OP_C0STREAM: /* cons-stream */
+            s_save(sc, OP_C1STREAM, sc->NIL, cdr(sc->code));
+            sc->code = car(sc->code);
+            s_goto(sc, OP_EVAL);
+
+        case OP_C1STREAM:            /* cons-stream */
+            sc->args    = sc->value; /* save sc->value to register sc->args for gc */
+            x           = mk_closure(sc, cons(sc, sc->NIL, sc->code), sc->envir);
+            typeflag(x) = T_PROMISE;
+            s_return(sc, cons(sc, sc->args, x));
+
+        case OP_MACRO0: /* macro */
+            if (is_pair(car(sc->code))) {
+                x        = caar(sc->code);
+                sc->code = cons(sc, sc->LAMBDA, cons(sc, cdar(sc->code), cdr(sc->code)));
+            } else {
+                x        = car(sc->code);
+                sc->code = cadr(sc->code);
+            }
+            if (!is_symbol(x)) {
+                Error_0(sc, "variable is not a symbol");
+            }
+            s_save(sc, OP_MACRO1, sc->NIL, x);
+            s_goto(sc, OP_EVAL);
+
+        case OP_MACRO1: /* macro */
+            typeflag(sc->value) = T_MACRO;
+            x                   = find_slot_in_env(sc, sc->envir, sc->code, 0);
+            if (x != sc->NIL) {
+                set_slot_in_env(sc, x, sc->value);
+            } else {
+                new_slot_in_env(sc, sc->code, sc->value);
+            }
+            s_return(sc, sc->code);
+
+        case OP_CASE0: /* case */
+            s_save(sc, OP_CASE1, sc->NIL, cdr(sc->code));
+            sc->code = car(sc->code);
+            s_goto(sc, OP_EVAL);
+
+        case OP_CASE1: /* case */
+            for (x = sc->code; x != sc->NIL; x = cdr(x)) {
+                if (!is_pair(y = caar(x))) {
                     break;
-               }
-               for ( ; y != sc->NIL; y = cdr(y)) {
+                }
+                for (; y != sc->NIL; y = cdr(y)) {
                     if (eqv(car(y), sc->value)) {
-                         break;
+                        break;
                     }
-               }
-               if (y != sc->NIL) {
+                }
+                if (y != sc->NIL) {
                     break;
-               }
-          }
-          if (x != sc->NIL) {
-               if (is_pair(caar(x))) {
+                }
+            }
+            if (x != sc->NIL) {
+                if (is_pair(caar(x))) {
                     sc->code = cdar(x);
-                    s_goto(sc,OP_BEGIN);
-               } else {/* else */
-                    s_save(sc,OP_CASE2, sc->NIL, cdar(x));
+                    s_goto(sc, OP_BEGIN);
+                } else { /* else */
+                    s_save(sc, OP_CASE2, sc->NIL, cdar(x));
                     sc->code = caar(x);
-                    s_goto(sc,OP_EVAL);
-               }
-          } else {
-               s_return(sc,sc->NIL);
-          }
-
-     case OP_CASE2:      /* case */
-          if (is_true(sc->value)) {
-               s_goto(sc,OP_BEGIN);
-          } else {
-               s_return(sc,sc->NIL);
-          }
-
-     case OP_PAPPLY:     /* apply */
-          sc->code = car(sc->args);
-	  sc->args = list_star(sc,cdr(sc->args));
-          /*sc->args = cadr(sc->args);*/
-          s_goto(sc,OP_APPLY);
-
-     case OP_PEVAL: /* eval */
-          if(cdr(sc->args)!=sc->NIL) {
-               sc->envir=cadr(sc->args);
-          }
-          sc->code = car(sc->args);
-          s_goto(sc,OP_EVAL);
-
-     case OP_CONTINUATION:    /* call-with-current-continuation */
-          sc->code = car(sc->args);
-          sc->args = cons(sc, mk_continuation(sc, sc->dump), sc->NIL);
-          s_goto(sc,OP_APPLY);
-
-     default:
-          sprintf(sc->strbuff, "%d: illegal operator", sc->op);
-          Error_0(sc,sc->strbuff);
-     }
-     return sc->T;
-}
-
-static pointer opexe_2(scheme *sc, enum scheme_opcodes op) {
-     pointer x;
-     num v;
+                    s_goto(sc, OP_EVAL);
+                }
+            } else {
+                s_return(sc, sc->NIL);
+            }
+
+        case OP_CASE2: /* case */
+            if (is_true(sc->value)) {
+                s_goto(sc, OP_BEGIN);
+            } else {
+                s_return(sc, sc->NIL);
+            }
+
+        case OP_PAPPLY: /* apply */
+            sc->code = car(sc->args);
+            sc->args = list_star(sc, cdr(sc->args));
+            /*sc->args = cadr(sc->args);*/
+            s_goto(sc, OP_APPLY);
+
+        case OP_PEVAL: /* eval */
+            if (cdr(sc->args) != sc->NIL) {
+                sc->envir = cadr(sc->args);
+            }
+            sc->code = car(sc->args);
+            s_goto(sc, OP_EVAL);
+
+        case OP_CONTINUATION: /* call-with-current-continuation */
+            sc->code = car(sc->args);
+            sc->args = cons(sc, mk_continuation(sc, sc->dump), sc->NIL);
+            s_goto(sc, OP_APPLY);
+
+        default: sprintf(sc->strbuff, "%d: illegal operator", sc->op); Error_0(sc, sc->strbuff);
+    }
+    return sc->T;
+}
+
+static pointer
+opexe_2(scheme* sc, enum scheme_opcodes op) {
+    pointer x;
+    num     v;
 #if USE_MATH
-     double dd;
+    double dd;
 #endif
 
-     switch (op) {
+    switch (op) {
 #if USE_MATH
-     case OP_INEX2EX:    /* inexact->exact */
-          x=car(sc->args);
-          if(is_integer(x)) {
-               s_return(sc,x);
-          } else if(modf(rvalue_unchecked(x),&dd)==0.0) {
-               s_return(sc,mk_integer(sc,ivalue(x)));
-          } else {
-               Error_1(sc,"inexact->exact: not integral:",x);
-          }
-
-     case OP_EXP:
-          x=car(sc->args);
-          s_return(sc, mk_real(sc, exp(rvalue(x))));
-
-     case OP_LOG:
-          x=car(sc->args);
-          s_return(sc, mk_real(sc, log(rvalue(x))));
-
-     case OP_SIN:
-          x=car(sc->args);
-          s_return(sc, mk_real(sc, sin(rvalue(x))));
-
-     case OP_COS:
-          x=car(sc->args);
-          s_return(sc, mk_real(sc, cos(rvalue(x))));
-
-     case OP_TAN:
-          x=car(sc->args);
-          s_return(sc, mk_real(sc, tan(rvalue(x))));
-
-     case OP_ASIN:
-          x=car(sc->args);
-          s_return(sc, mk_real(sc, asin(rvalue(x))));
-
-     case OP_ACOS:
-          x=car(sc->args);
-          s_return(sc, mk_real(sc, acos(rvalue(x))));
-
-     case OP_ATAN:
-          x=car(sc->args);
-          if(cdr(sc->args)==sc->NIL) {
-               s_return(sc, mk_real(sc, atan(rvalue(x))));
-          } else {
-               pointer y=cadr(sc->args);
-               s_return(sc, mk_real(sc, atan2(rvalue(x),rvalue(y))));
-          }
-
-     case OP_SQRT:
-          x=car(sc->args);
-          s_return(sc, mk_real(sc, sqrt(rvalue(x))));
-
-     case OP_EXPT:
-          x=car(sc->args);
-          if(cdr(sc->args)==sc->NIL) {
-               Error_0(sc,"expt: needs two arguments");
-          } else {
-               pointer y=cadr(sc->args);
-               s_return(sc, mk_real(sc, pow(rvalue(x),rvalue(y))));
-          }
-
-     case OP_FLOOR:
-          x=car(sc->args);
-	  s_return(sc, mk_real(sc, floor(rvalue(x))));
-
-     case OP_CEILING:
-          x=car(sc->args);
-	  s_return(sc, mk_real(sc, ceil(rvalue(x))));
-
-     case OP_TRUNCATE : {
-	  double rvalue_of_x ;
-          x=car(sc->args);
-	  rvalue_of_x = rvalue(x) ;
-	  if (rvalue_of_x > 0) {
-	    s_return(sc, mk_real(sc, floor(rvalue_of_x)));
-	  } else {
-	    s_return(sc, mk_real(sc, ceil(rvalue_of_x)));
-	  }
-     }
-
-     case OP_ROUND:
-       x=car(sc->args);
-       s_return(sc, mk_real(sc, round_per_R5RS(rvalue(x))));
+        case OP_INEX2EX: /* inexact->exact */
+            x = car(sc->args);
+            if (is_integer(x)) {
+                s_return(sc, x);
+            } else if (modf(rvalue_unchecked(x), &dd) == 0.0) {
+                s_return(sc, mk_integer(sc, ivalue(x)));
+            } else {
+                Error_1(sc, "inexact->exact: not integral:", x);
+            }
+
+        case OP_EXP: x = car(sc->args); s_return(sc, mk_real(sc, exp(rvalue(x))));
+
+        case OP_LOG: x = car(sc->args); s_return(sc, mk_real(sc, log(rvalue(x))));
+
+        case OP_SIN: x = car(sc->args); s_return(sc, mk_real(sc, sin(rvalue(x))));
+
+        case OP_COS: x = car(sc->args); s_return(sc, mk_real(sc, cos(rvalue(x))));
+
+        case OP_TAN: x = car(sc->args); s_return(sc, mk_real(sc, tan(rvalue(x))));
+
+        case OP_ASIN: x = car(sc->args); s_return(sc, mk_real(sc, asin(rvalue(x))));
+
+        case OP_ACOS: x = car(sc->args); s_return(sc, mk_real(sc, acos(rvalue(x))));
+
+        case OP_ATAN:
+            x = car(sc->args);
+            if (cdr(sc->args) == sc->NIL) {
+                s_return(sc, mk_real(sc, atan(rvalue(x))));
+            } else {
+                pointer y = cadr(sc->args);
+                s_return(sc, mk_real(sc, atan2(rvalue(x), rvalue(y))));
+            }
+
+        case OP_SQRT: x = car(sc->args); s_return(sc, mk_real(sc, sqrt(rvalue(x))));
+
+        case OP_EXPT:
+            x = car(sc->args);
+            if (cdr(sc->args) == sc->NIL) {
+                Error_0(sc, "expt: needs two arguments");
+            } else {
+                pointer y = cadr(sc->args);
+                s_return(sc, mk_real(sc, pow(rvalue(x), rvalue(y))));
+            }
+
+        case OP_FLOOR: x = car(sc->args); s_return(sc, mk_real(sc, floor(rvalue(x))));
+
+        case OP_CEILING: x = car(sc->args); s_return(sc, mk_real(sc, ceil(rvalue(x))));
+
+        case OP_TRUNCATE:
+            {
+                double rvalue_of_x;
+                x           = car(sc->args);
+                rvalue_of_x = rvalue(x);
+                if (rvalue_of_x > 0) {
+                    s_return(sc, mk_real(sc, floor(rvalue_of_x)));
+                } else {
+                    s_return(sc, mk_real(sc, ceil(rvalue_of_x)));
+                }
+            }
+
+        case OP_ROUND: x = car(sc->args); s_return(sc, mk_real(sc, round_per_R5RS(rvalue(x))));
 #endif
 
-     case OP_ADD:        /* + */
-       v=num_zero;
-       for (x = sc->args; x != sc->NIL; x = cdr(x)) {
-	 v=num_add(v,nvalue(car(x)));
-       }
-       s_return(sc,mk_number(sc, v));
-
-     case OP_MUL:        /* * */
-       v=num_one;
-       for (x = sc->args; x != sc->NIL; x = cdr(x)) {
-	 v=num_mul(v,nvalue(car(x)));
-       }
-       s_return(sc,mk_number(sc, v));
-
-     case OP_SUB:        /* - */
-       if(cdr(sc->args)==sc->NIL) {
-	 x=sc->args;
-	 v=num_zero;
-       } else {
-	 x = cdr(sc->args);
-	 v = nvalue(car(sc->args));
-       }
-       for (; x != sc->NIL; x = cdr(x)) {
-	 v=num_sub(v,nvalue(car(x)));
-       }
-       s_return(sc,mk_number(sc, v));
-
-     case OP_DIV:        /* / */
-       if(cdr(sc->args)==sc->NIL) {
-	 x=sc->args;
-	 v=num_one;
-       } else {
-	 x = cdr(sc->args);
-	 v = nvalue(car(sc->args));
-       }
-       for (; x != sc->NIL; x = cdr(x)) {
-	 if (!is_zero_double(rvalue(car(x))))
-	   v=num_div(v,nvalue(car(x)));
-	 else {
-	   Error_0(sc,"/: division by zero");
-	 }
-       }
-       s_return(sc,mk_number(sc, v));
-
-     case OP_INTDIV:        /* quotient */
-          if(cdr(sc->args)==sc->NIL) {
-               x=sc->args;
-               v=num_one;
-          } else {
-               x = cdr(sc->args);
-               v = nvalue(car(sc->args));
-          }
-          for (; x != sc->NIL; x = cdr(x)) {
-               if (ivalue(car(x)) != 0)
-                    v=num_intdiv(v,nvalue(car(x)));
-               else {
-                    Error_0(sc,"quotient: division by zero");
-               }
-          }
-          s_return(sc,mk_number(sc, v));
-
-     case OP_REM:        /* remainder */
-          v = nvalue(car(sc->args));
-          if (ivalue(cadr(sc->args)) != 0)
-               v=num_rem(v,nvalue(cadr(sc->args)));
-          else {
-               Error_0(sc,"remainder: division by zero");
-          }
-          s_return(sc,mk_number(sc, v));
-
-     case OP_MOD:        /* modulo */
-          v = nvalue(car(sc->args));
-          if (ivalue(cadr(sc->args)) != 0)
-               v=num_mod(v,nvalue(cadr(sc->args)));
-          else {
-               Error_0(sc,"modulo: division by zero");
-          }
-          s_return(sc,mk_number(sc, v));
-
-     case OP_CAR:        /* car */
-       s_return(sc,caar(sc->args));
-
-     case OP_CDR:        /* cdr */
-       s_return(sc,cdar(sc->args));
-
-     case OP_CONS:       /* cons */
-          cdr(sc->args) = cadr(sc->args);
-          s_return(sc,sc->args);
-
-     case OP_SETCAR:     /* set-car! */
-       if(!is_immutable(car(sc->args))) {
-	 caar(sc->args) = cadr(sc->args);
-	 s_return(sc,car(sc->args));
-       } else {
-	 Error_0(sc,"set-car!: unable to alter immutable pair");
-       }
-
-     case OP_SETCDR:     /* set-cdr! */
-       if(!is_immutable(car(sc->args))) {
-	 cdar(sc->args) = cadr(sc->args);
-	 s_return(sc,car(sc->args));
-       } else {
-	 Error_0(sc,"set-cdr!: unable to alter immutable pair");
-       }
-
-     case OP_CHAR2INT: { /* char->integer */
-          char c;
-          c=(char)ivalue(car(sc->args));
-          s_return(sc,mk_integer(sc,(unsigned char)c));
-     }
-
-     case OP_INT2CHAR: { /* integer->char */
-          unsigned char c;
-          c=(unsigned char)ivalue(car(sc->args));
-          s_return(sc,mk_character(sc,(char)c));
-     }
-
-     case OP_CHARUPCASE: {
-          unsigned char c;
-          c=(unsigned char)ivalue(car(sc->args));
-          c=toupper(c);
-          s_return(sc,mk_character(sc,(char)c));
-     }
-
-     case OP_CHARDNCASE: {
-          unsigned char c;
-          c=(unsigned char)ivalue(car(sc->args));
-          c=tolower(c);
-          s_return(sc,mk_character(sc,(char)c));
-     }
-
-     case OP_STR2SYM:  /* string->symbol */
-          s_return(sc,mk_symbol(sc,strvalue(car(sc->args))));
-
-     case OP_STR2ATOM: /* string->atom */ {
-       char *s=strvalue(car(sc->args));
-       if(*s=='#') {
-	 s_return(sc, mk_sharp_const(sc, s+1));
-       } else {
-	 s_return(sc, mk_atom(sc, s));
-       }
-     }
-
-     case OP_SYM2STR: /* symbol->string */
-          x=mk_string(sc,symname(car(sc->args)));
-          setimmutable(x);
-          s_return(sc,x);
-     case OP_ATOM2STR: /* atom->string */
-       x=car(sc->args);
-       if(is_number(x) || is_character(x) || is_string(x) || is_symbol(x)) {
-	 char *p;
-	 int len;
-	 atom2str(sc,x,0,&p,&len);
-	 s_return(sc,mk_counted_string(sc,p,len));
-       } else {
-	 Error_1(sc, "atom->string: not an atom:", x);
-       }
-
-     case OP_MKSTRING: { /* make-string */
-          int fill=' ';
-          int len;
-
-          len=ivalue(car(sc->args));
-
-          if(cdr(sc->args)!=sc->NIL) {
-               fill=charvalue(cadr(sc->args));
-          }
-          s_return(sc,mk_empty_string(sc,len,(char)fill));
-     }
-
-     case OP_STRLEN:  /* string-length */
-          s_return(sc,mk_integer(sc,strlength(car(sc->args))));
-
-     case OP_STRREF: { /* string-ref */
-          char *str;
-          int index;
-
-          str=strvalue(car(sc->args));
-
-          index=ivalue(cadr(sc->args));
-
-          if(index>=strlength(car(sc->args))) {
-               Error_1(sc,"string-ref: out of bounds:",cadr(sc->args));
-          }
-
-          s_return(sc,mk_character(sc,((unsigned char*)str)[index]));
-     }
-
-     case OP_STRSET: { /* string-set! */
-          char *str;
-          int index;
-          int c;
-
-          if(is_immutable(car(sc->args))) {
-               Error_1(sc,"string-set!: unable to alter immutable string:",car(sc->args));
-          }
-          str=strvalue(car(sc->args));
-
-          index=ivalue(cadr(sc->args));
-          if(index>=strlength(car(sc->args))) {
-               Error_1(sc,"string-set!: out of bounds:",cadr(sc->args));
-          }
-
-          c=charvalue(caddr(sc->args));
-
-          str[index]=(char)c;
-          s_return(sc,car(sc->args));
-     }
-
-     case OP_STRAPPEND: { /* string-append */
-       /* in 1.29 string-append was in Scheme in init.scm but was too slow */
-       int len = 0;
-       pointer newstr;
-       char *pos;
-
-       /* compute needed length for new string */
-       for (x = sc->args; x != sc->NIL; x = cdr(x)) {
-          len += strlength(car(x));
-       }
-       newstr = mk_empty_string(sc, len, ' ');
-       /* store the contents of the argument strings into the new string */
-       for (pos = strvalue(newstr), x = sc->args; x != sc->NIL;
-           pos += strlength(car(x)), x = cdr(x)) {
-           memcpy(pos, strvalue(car(x)), strlength(car(x)));
-       }
-       s_return(sc, newstr);
-     }
-
-     case OP_SUBSTR: { /* substring */
-          char *str;
-          int index0;
-          int index1;
-          int len;
-
-          str=strvalue(car(sc->args));
-
-          index0=ivalue(cadr(sc->args));
-
-          if(index0>strlength(car(sc->args))) {
-               Error_1(sc,"substring: start out of bounds:",cadr(sc->args));
-          }
-
-          if(cddr(sc->args)!=sc->NIL) {
-               index1=ivalue(caddr(sc->args));
-               if(index1>strlength(car(sc->args)) || index1<index0) {
-                    Error_1(sc,"substring: end out of bounds:",caddr(sc->args));
-               }
-          } else {
-               index1=strlength(car(sc->args));
-          }
-
-          len=index1-index0;
-          x=mk_empty_string(sc,len,' ');
-          memcpy(strvalue(x),str+index0,len);
-          strvalue(x)[len]=0;
-
-          s_return(sc,x);
-     }
-
-     case OP_VECTOR: {   /* vector */
-          int i;
-          pointer vec;
-          int len=list_length(sc,sc->args);
-          if(len<0) {
-               Error_1(sc,"vector: not a proper list:",sc->args);
-          }
-          vec=mk_vector(sc,len);
-          for (x = sc->args, i = 0; is_pair(x); x = cdr(x), i++) {
-               set_vector_elem(vec,i,car(x));
-          }
-          s_return(sc,vec);
-     }
-
-     case OP_MKVECTOR: { /* make-vector */
-          pointer fill=sc->NIL;
-          int len;
-          pointer vec;
-
-          len=ivalue(car(sc->args));
-
-          if(cdr(sc->args)!=sc->NIL) {
-               fill=cadr(sc->args);
-          }
-          vec=mk_vector(sc,len);
-          if(fill!=sc->NIL) {
-               fill_vector(vec,fill);
-          }
-          s_return(sc,vec);
-     }
-
-     case OP_VECLEN:  /* vector-length */
-          s_return(sc,mk_integer(sc,ivalue(car(sc->args))));
-
-     case OP_VECREF: { /* vector-ref */
-          int index;
-
-          index=ivalue(cadr(sc->args));
-
-          if(index>=ivalue(car(sc->args))) {
-               Error_1(sc,"vector-ref: out of bounds:",cadr(sc->args));
-          }
-
-          s_return(sc,vector_elem(car(sc->args),index));
-     }
-
-     case OP_VECSET: {   /* vector-set! */
-          int index;
-
-          if(is_immutable(car(sc->args))) {
-               Error_1(sc,"vector-set!: unable to alter immutable vector:",car(sc->args));
-          }
-
-          index=ivalue(cadr(sc->args));
-          if(index>=ivalue(car(sc->args))) {
-               Error_1(sc,"vector-set!: out of bounds:",cadr(sc->args));
-          }
-
-          set_vector_elem(car(sc->args),index,caddr(sc->args));
-          s_return(sc,car(sc->args));
-     }
-
-     default:
-          sprintf(sc->strbuff, "%d: illegal operator", sc->op);
-          Error_0(sc,sc->strbuff);
-     }
-     return sc->T;
-}
-
-static int list_length(scheme *sc, pointer a) {
-     int v=0;
-     pointer x;
-     for (x = a, v = 0; is_pair(x); x = cdr(x)) {
-          ++v;
-     }
-     if(x==sc->NIL) {
-          return v;
-     }
-     return -1;
-}
-
-static pointer opexe_3(scheme *sc, enum scheme_opcodes op) {
-     pointer x;
-     num v;
-     int (*comp_func)(num,num)=0;
-
-     switch (op) {
-     case OP_NOT:        /* not */
-          s_retbool(is_false(car(sc->args)));
-     case OP_BOOLP:       /* boolean? */
-          s_retbool(car(sc->args) == sc->F || car(sc->args) == sc->T);
-     case OP_EOFOBJP:       /* boolean? */
-          s_retbool(car(sc->args) == sc->EOF_OBJ);
-     case OP_NULLP:       /* null? */
-          s_retbool(car(sc->args) == sc->NIL);
-     case OP_NUMEQ:      /* = */
-     case OP_LESS:       /* < */
-     case OP_GRE:        /* > */
-     case OP_LEQ:        /* <= */
-     case OP_GEQ:        /* >= */
-          switch(op) {
-               case OP_NUMEQ: comp_func=num_eq; break;
-               case OP_LESS:  comp_func=num_lt; break;
-               case OP_GRE:   comp_func=num_gt; break;
-               case OP_LEQ:   comp_func=num_le; break;
-               case OP_GEQ:   comp_func=num_ge; break;
-	       default:
-		   ;
-          }
-          x=sc->args;
-          v=nvalue(car(x));
-          x=cdr(x);
-
-          for (; x != sc->NIL; x = cdr(x)) {
-               if(!comp_func(v,nvalue(car(x)))) {
+        case OP_ADD: /* + */
+            v = num_zero;
+            for (x = sc->args; x != sc->NIL; x = cdr(x)) {
+                v = num_add(v, nvalue(car(x)));
+            }
+            s_return(sc, mk_number(sc, v));
+
+        case OP_MUL: /* * */
+            v = num_one;
+            for (x = sc->args; x != sc->NIL; x = cdr(x)) {
+                v = num_mul(v, nvalue(car(x)));
+            }
+            s_return(sc, mk_number(sc, v));
+
+        case OP_SUB: /* - */
+            if (cdr(sc->args) == sc->NIL) {
+                x = sc->args;
+                v = num_zero;
+            } else {
+                x = cdr(sc->args);
+                v = nvalue(car(sc->args));
+            }
+            for (; x != sc->NIL; x = cdr(x)) {
+                v = num_sub(v, nvalue(car(x)));
+            }
+            s_return(sc, mk_number(sc, v));
+
+        case OP_DIV: /* / */
+            if (cdr(sc->args) == sc->NIL) {
+                x = sc->args;
+                v = num_one;
+            } else {
+                x = cdr(sc->args);
+                v = nvalue(car(sc->args));
+            }
+            for (; x != sc->NIL; x = cdr(x)) {
+                if (!is_zero_double(rvalue(car(x))))
+                    v = num_div(v, nvalue(car(x)));
+                else {
+                    Error_0(sc, "/: division by zero");
+                }
+            }
+            s_return(sc, mk_number(sc, v));
+
+        case OP_INTDIV: /* quotient */
+            if (cdr(sc->args) == sc->NIL) {
+                x = sc->args;
+                v = num_one;
+            } else {
+                x = cdr(sc->args);
+                v = nvalue(car(sc->args));
+            }
+            for (; x != sc->NIL; x = cdr(x)) {
+                if (ivalue(car(x)) != 0)
+                    v = num_intdiv(v, nvalue(car(x)));
+                else {
+                    Error_0(sc, "quotient: division by zero");
+                }
+            }
+            s_return(sc, mk_number(sc, v));
+
+        case OP_REM: /* remainder */
+            v = nvalue(car(sc->args));
+            if (ivalue(cadr(sc->args)) != 0)
+                v = num_rem(v, nvalue(cadr(sc->args)));
+            else {
+                Error_0(sc, "remainder: division by zero");
+            }
+            s_return(sc, mk_number(sc, v));
+
+        case OP_MOD: /* modulo */
+            v = nvalue(car(sc->args));
+            if (ivalue(cadr(sc->args)) != 0)
+                v = num_mod(v, nvalue(cadr(sc->args)));
+            else {
+                Error_0(sc, "modulo: division by zero");
+            }
+            s_return(sc, mk_number(sc, v));
+
+        case OP_CAR: /* car */ s_return(sc, caar(sc->args));
+
+        case OP_CDR: /* cdr */ s_return(sc, cdar(sc->args));
+
+        case OP_CONS: /* cons */ cdr(sc->args) = cadr(sc->args); s_return(sc, sc->args);
+
+        case OP_SETCAR: /* set-car! */
+            if (!is_immutable(car(sc->args))) {
+                caar(sc->args) = cadr(sc->args);
+                s_return(sc, car(sc->args));
+            } else {
+                Error_0(sc, "set-car!: unable to alter immutable pair");
+            }
+
+        case OP_SETCDR: /* set-cdr! */
+            if (!is_immutable(car(sc->args))) {
+                cdar(sc->args) = cadr(sc->args);
+                s_return(sc, car(sc->args));
+            } else {
+                Error_0(sc, "set-cdr!: unable to alter immutable pair");
+            }
+
+        case OP_CHAR2INT:
+            { /* char->integer */
+                char c;
+                c = (char)ivalue(car(sc->args));
+                s_return(sc, mk_integer(sc, (unsigned char)c));
+            }
+
+        case OP_INT2CHAR:
+            { /* integer->char */
+                unsigned char c;
+                c = (unsigned char)ivalue(car(sc->args));
+                s_return(sc, mk_character(sc, (char)c));
+            }
+
+        case OP_CHARUPCASE:
+            {
+                unsigned char c;
+                c = (unsigned char)ivalue(car(sc->args));
+                c = toupper(c);
+                s_return(sc, mk_character(sc, (char)c));
+            }
+
+        case OP_CHARDNCASE:
+            {
+                unsigned char c;
+                c = (unsigned char)ivalue(car(sc->args));
+                c = tolower(c);
+                s_return(sc, mk_character(sc, (char)c));
+            }
+
+        case OP_STR2SYM: /* string->symbol */ s_return(sc, mk_symbol(sc, strvalue(car(sc->args))));
+
+        case OP_STR2ATOM: /* string->atom */
+            {
+                char* s = strvalue(car(sc->args));
+                if (*s == '#') {
+                    s_return(sc, mk_sharp_const(sc, s + 1));
+                } else {
+                    s_return(sc, mk_atom(sc, s));
+                }
+            }
+
+        case OP_SYM2STR: /* symbol->string */
+            x = mk_string(sc, symname(car(sc->args)));
+            setimmutable(x);
+            s_return(sc, x);
+        case OP_ATOM2STR: /* atom->string */
+            x = car(sc->args);
+            if (is_number(x) || is_character(x) || is_string(x) || is_symbol(x)) {
+                char* p;
+                int   len;
+                atom2str(sc, x, 0, &p, &len);
+                s_return(sc, mk_counted_string(sc, p, len));
+            } else {
+                Error_1(sc, "atom->string: not an atom:", x);
+            }
+
+        case OP_MKSTRING:
+            { /* make-string */
+                int fill = ' ';
+                int len;
+
+                len = ivalue(car(sc->args));
+
+                if (cdr(sc->args) != sc->NIL) {
+                    fill = charvalue(cadr(sc->args));
+                }
+                s_return(sc, mk_empty_string(sc, len, (char)fill));
+            }
+
+        case OP_STRLEN: /* string-length */ s_return(sc, mk_integer(sc, strlength(car(sc->args))));
+
+        case OP_STRREF:
+            { /* string-ref */
+                char* str;
+                int   index;
+
+                str = strvalue(car(sc->args));
+
+                index = ivalue(cadr(sc->args));
+
+                if (index >= strlength(car(sc->args))) {
+                    Error_1(sc, "string-ref: out of bounds:", cadr(sc->args));
+                }
+
+                s_return(sc, mk_character(sc, ((unsigned char*)str)[index]));
+            }
+
+        case OP_STRSET:
+            { /* string-set! */
+                char* str;
+                int   index;
+                int   c;
+
+                if (is_immutable(car(sc->args))) {
+                    Error_1(sc, "string-set!: unable to alter immutable string:", car(sc->args));
+                }
+                str = strvalue(car(sc->args));
+
+                index = ivalue(cadr(sc->args));
+                if (index >= strlength(car(sc->args))) {
+                    Error_1(sc, "string-set!: out of bounds:", cadr(sc->args));
+                }
+
+                c = charvalue(caddr(sc->args));
+
+                str[index] = (char)c;
+                s_return(sc, car(sc->args));
+            }
+
+        case OP_STRAPPEND:
+            { /* string-append */
+                /* in 1.29 string-append was in Scheme in init.scm but was too slow */
+                int     len = 0;
+                pointer newstr;
+                char*   pos;
+
+                /* compute needed length for new string */
+                for (x = sc->args; x != sc->NIL; x = cdr(x)) {
+                    len += strlength(car(x));
+                }
+                newstr = mk_empty_string(sc, len, ' ');
+                /* store the contents of the argument strings into the new string */
+                for (pos = strvalue(newstr), x = sc->args; x != sc->NIL; pos += strlength(car(x)), x = cdr(x)) {
+                    memcpy(pos, strvalue(car(x)), strlength(car(x)));
+                }
+                s_return(sc, newstr);
+            }
+
+        case OP_SUBSTR:
+            { /* substring */
+                char* str;
+                int   index0;
+                int   index1;
+                int   len;
+
+                str = strvalue(car(sc->args));
+
+                index0 = ivalue(cadr(sc->args));
+
+                if (index0 > strlength(car(sc->args))) {
+                    Error_1(sc, "substring: start out of bounds:", cadr(sc->args));
+                }
+
+                if (cddr(sc->args) != sc->NIL) {
+                    index1 = ivalue(caddr(sc->args));
+                    if (index1 > strlength(car(sc->args)) || index1 < index0) {
+                        Error_1(sc, "substring: end out of bounds:", caddr(sc->args));
+                    }
+                } else {
+                    index1 = strlength(car(sc->args));
+                }
+
+                len = index1 - index0;
+                x   = mk_empty_string(sc, len, ' ');
+                memcpy(strvalue(x), str + index0, len);
+                strvalue(x)[len] = 0;
+
+                s_return(sc, x);
+            }
+
+        case OP_VECTOR:
+            { /* vector */
+                int     i;
+                pointer vec;
+                int     len = list_length(sc, sc->args);
+                if (len < 0) {
+                    Error_1(sc, "vector: not a proper list:", sc->args);
+                }
+                vec = mk_vector(sc, len);
+                for (x = sc->args, i = 0; is_pair(x); x = cdr(x), i++) {
+                    set_vector_elem(vec, i, car(x));
+                }
+                s_return(sc, vec);
+            }
+
+        case OP_MKVECTOR:
+            { /* make-vector */
+                pointer fill = sc->NIL;
+                int     len;
+                pointer vec;
+
+                len = ivalue(car(sc->args));
+
+                if (cdr(sc->args) != sc->NIL) {
+                    fill = cadr(sc->args);
+                }
+                vec = mk_vector(sc, len);
+                if (fill != sc->NIL) {
+                    fill_vector(vec, fill);
+                }
+                s_return(sc, vec);
+            }
+
+        case OP_VECLEN: /* vector-length */ s_return(sc, mk_integer(sc, ivalue(car(sc->args))));
+
+        case OP_VECREF:
+            { /* vector-ref */
+                int index;
+
+                index = ivalue(cadr(sc->args));
+
+                if (index >= ivalue(car(sc->args))) {
+                    Error_1(sc, "vector-ref: out of bounds:", cadr(sc->args));
+                }
+
+                s_return(sc, vector_elem(car(sc->args), index));
+            }
+
+        case OP_VECSET:
+            { /* vector-set! */
+                int index;
+
+                if (is_immutable(car(sc->args))) {
+                    Error_1(sc, "vector-set!: unable to alter immutable vector:", car(sc->args));
+                }
+
+                index = ivalue(cadr(sc->args));
+                if (index >= ivalue(car(sc->args))) {
+                    Error_1(sc, "vector-set!: out of bounds:", cadr(sc->args));
+                }
+
+                set_vector_elem(car(sc->args), index, caddr(sc->args));
+                s_return(sc, car(sc->args));
+            }
+
+        default: sprintf(sc->strbuff, "%d: illegal operator", sc->op); Error_0(sc, sc->strbuff);
+    }
+    return sc->T;
+}
+
+static int
+list_length(scheme* sc, pointer a) {
+    int     v = 0;
+    pointer x;
+    for (x = a, v = 0; is_pair(x); x = cdr(x)) {
+        ++v;
+    }
+    if (x == sc->NIL) {
+        return v;
+    }
+    return -1;
+}
+
+static pointer
+opexe_3(scheme* sc, enum scheme_opcodes op) {
+    pointer x;
+    num     v;
+    int (*comp_func)(num, num) = 0;
+
+    switch (op) {
+        case OP_NOT: /* not */ s_retbool(is_false(car(sc->args)));
+        case OP_BOOLP: /* boolean? */ s_retbool(car(sc->args) == sc->F || car(sc->args) == sc->T);
+        case OP_EOFOBJP: /* boolean? */ s_retbool(car(sc->args) == sc->EOF_OBJ);
+        case OP_NULLP: /* null? */ s_retbool(car(sc->args) == sc->NIL);
+        case OP_NUMEQ: /* = */
+        case OP_LESS:  /* < */
+        case OP_GRE:   /* > */
+        case OP_LEQ:   /* <= */
+        case OP_GEQ:   /* >= */
+            switch (op) {
+                case OP_NUMEQ: comp_func = num_eq; break;
+                case OP_LESS: comp_func = num_lt; break;
+                case OP_GRE: comp_func = num_gt; break;
+                case OP_LEQ: comp_func = num_le; break;
+                case OP_GEQ: comp_func = num_ge; break;
+                default:;
+            }
+            x = sc->args;
+            v = nvalue(car(x));
+            x = cdr(x);
+
+            for (; x != sc->NIL; x = cdr(x)) {
+                if (!comp_func(v, nvalue(car(x)))) {
                     s_retbool(0);
-               }
-	       v=nvalue(car(x));
-          }
-          s_retbool(1);
-     case OP_SYMBOLP:     /* symbol? */
-          s_retbool(is_symbol(car(sc->args)));
-     case OP_NUMBERP:     /* number? */
-          s_retbool(is_number(car(sc->args)));
-     case OP_STRINGP:     /* string? */
-          s_retbool(is_string(car(sc->args)));
-     case OP_INTEGERP:     /* integer? */
-          s_retbool(is_integer(car(sc->args)));
-     case OP_REALP:     /* real? */
-          s_retbool(is_number(car(sc->args))); /* All numbers are real */
-     case OP_CHARP:     /* char? */
-          s_retbool(is_character(car(sc->args)));
+                }
+                v = nvalue(car(x));
+            }
+            s_retbool(1);
+        case OP_SYMBOLP: /* symbol? */ s_retbool(is_symbol(car(sc->args)));
+        case OP_NUMBERP: /* number? */ s_retbool(is_number(car(sc->args)));
+        case OP_STRINGP: /* string? */ s_retbool(is_string(car(sc->args)));
+        case OP_INTEGERP: /* integer? */ s_retbool(is_integer(car(sc->args)));
+        case OP_REALP: /* real? */ s_retbool(is_number(car(sc->args))); /* All numbers are real */
+        case OP_CHARP: /* char? */ s_retbool(is_character(car(sc->args)));
 #if USE_CHAR_CLASSIFIERS
-     case OP_CHARAP:     /* char-alphabetic? */
-          s_retbool(Cisalpha(ivalue(car(sc->args))));
-     case OP_CHARNP:     /* char-numeric? */
-          s_retbool(Cisdigit(ivalue(car(sc->args))));
-     case OP_CHARWP:     /* char-whitespace? */
-          s_retbool(Cisspace(ivalue(car(sc->args))));
-     case OP_CHARUP:     /* char-upper-case? */
-          s_retbool(Cisupper(ivalue(car(sc->args))));
-     case OP_CHARLP:     /* char-lower-case? */
-          s_retbool(Cislower(ivalue(car(sc->args))));
+        case OP_CHARAP: /* char-alphabetic? */ s_retbool(Cisalpha(ivalue(car(sc->args))));
+        case OP_CHARNP: /* char-numeric? */ s_retbool(Cisdigit(ivalue(car(sc->args))));
+        case OP_CHARWP: /* char-whitespace? */ s_retbool(Cisspace(ivalue(car(sc->args))));
+        case OP_CHARUP: /* char-upper-case? */ s_retbool(Cisupper(ivalue(car(sc->args))));
+        case OP_CHARLP: /* char-lower-case? */ s_retbool(Cislower(ivalue(car(sc->args))));
 #endif
-     case OP_PORTP:     /* port? */
-          s_retbool(is_port(car(sc->args)));
-     case OP_INPORTP:     /* input-port? */
-          s_retbool(is_inport(car(sc->args)));
-     case OP_OUTPORTP:     /* output-port? */
-          s_retbool(is_outport(car(sc->args)));
-     case OP_PROCP:       /* procedure? */
-          /*--
-              * continuation should be procedure by the example
-              * (call-with-current-continuation procedure?) ==> #t
-                 * in R^3 report sec. 6.9
-              */
-          s_retbool(is_proc(car(sc->args)) || is_closure(car(sc->args))
-                 || is_continuation(car(sc->args)) || is_foreign(car(sc->args)));
-     case OP_PAIRP:       /* pair? */
-          s_retbool(is_pair(car(sc->args)));
-     case OP_LISTP: {     /* list? */
-          pointer slow, fast;
-          slow = fast = car(sc->args);
-          while (1) {
-             if (!is_pair(fast)) s_retbool(fast == sc->NIL);
-             fast = cdr(fast);
-             if (!is_pair(fast)) s_retbool(fast == sc->NIL);
-             fast = cdr(fast);
-             slow = cdr(slow);
-             if (fast == slow) {
-                  /* the fast pointer has looped back around and caught up
-                     with the slow pointer, hence the structure is circular,
-                     not of finite length, and therefore not a list */
-                  s_retbool(0);
-             }
-          }
-     }
-     case OP_ENVP:        /* environment? */
-          s_retbool(is_environment(car(sc->args)));
-     case OP_VECTORP:     /* vector? */
-          s_retbool(is_vector(car(sc->args)));
-     case OP_EQ:         /* eq? */
-          s_retbool(car(sc->args) == cadr(sc->args));
-     case OP_EQV:        /* eqv? */
-          s_retbool(eqv(car(sc->args), cadr(sc->args)));
-     default:
-          sprintf(sc->strbuff, "%d: illegal operator", sc->op);
-          Error_0(sc,sc->strbuff);
-     }
-     return sc->T;
-}
-
-static pointer opexe_4(scheme *sc, enum scheme_opcodes op) {
-     pointer x, y;
-
-     switch (op) {
-     case OP_FORCE:      /* force */
-          sc->code = car(sc->args);
-          if (is_promise(sc->code)) {
-               /* Should change type to closure here */
-               s_save(sc, OP_SAVE_FORCED, sc->NIL, sc->code);
-               sc->args = sc->NIL;
-               s_goto(sc,OP_APPLY);
-          } else {
-               s_return(sc,sc->code);
-          }
-
-     case OP_SAVE_FORCED:     /* Save forced value replacing promise */
-          memcpy(sc->code,sc->value,sizeof(struct cell));
-          s_return(sc,sc->value);
-
-     case OP_WRITE:      /* write */
-     case OP_DISPLAY:    /* display */
-     case OP_WRITE_CHAR: /* write-char */
-          if(is_pair(cdr(sc->args))) {
-               if(cadr(sc->args)!=sc->outport) {
-                    x=cons(sc,sc->outport,sc->NIL);
-                    s_save(sc,OP_SET_OUTPORT, x, sc->NIL);
-                    sc->outport=cadr(sc->args);
-               }
-          }
-          sc->args = car(sc->args);
-          if(op==OP_WRITE) {
-               sc->print_flag = 1;
-          } else {
-               sc->print_flag = 0;
-          }
-          s_goto(sc,OP_P0LIST);
-
-     case OP_NEWLINE:    /* newline */
-          if(is_pair(sc->args)) {
-               if(car(sc->args)!=sc->outport) {
-                    x=cons(sc,sc->outport,sc->NIL);
-                    s_save(sc,OP_SET_OUTPORT, x, sc->NIL);
-                    sc->outport=car(sc->args);
-               }
-          }
-          putstr(sc, "\n");
-          s_return(sc,sc->T);
-
-     case OP_ERR0:  /* error */
-          sc->retcode=-1;
-          if (!is_string(car(sc->args))) {
-               sc->args=cons(sc,mk_string(sc," -- "),sc->args);
-               setimmutable(car(sc->args));
-          }
-          putstr(sc, "Error: ");
-          putstr(sc, strvalue(car(sc->args)));
-          sc->args = cdr(sc->args);
-          s_goto(sc,OP_ERR1);
-
-     case OP_ERR1:  /* error */
-          putstr(sc, " ");
-          if (sc->args != sc->NIL) {
-               s_save(sc,OP_ERR1, cdr(sc->args), sc->NIL);
-               sc->args = car(sc->args);
-               sc->print_flag = 1;
-               s_goto(sc,OP_P0LIST);
-          } else {
-               putstr(sc, "\n");
-               if(sc->interactive_repl) {
-                    s_goto(sc,OP_T0LVL);
-               } else {
+        case OP_PORTP: /* port? */ s_retbool(is_port(car(sc->args)));
+        case OP_INPORTP: /* input-port? */ s_retbool(is_inport(car(sc->args)));
+        case OP_OUTPORTP: /* output-port? */ s_retbool(is_outport(car(sc->args)));
+        case OP_PROCP: /* procedure? */
+            /*--
+             * continuation should be procedure by the example
+             * (call-with-current-continuation procedure?) ==> #t
+             * in R^3 report sec. 6.9
+             */
+            s_retbool(
+                is_proc(car(sc->args)) || is_closure(car(sc->args)) || is_continuation(car(sc->args))
+                || is_foreign(car(sc->args))
+            );
+        case OP_PAIRP: /* pair? */ s_retbool(is_pair(car(sc->args)));
+        case OP_LISTP:
+            { /* list? */
+                pointer slow, fast;
+                slow = fast = car(sc->args);
+                while (1) {
+                    if (!is_pair(fast))
+                        s_retbool(fast == sc->NIL);
+                    fast = cdr(fast);
+                    if (!is_pair(fast))
+                        s_retbool(fast == sc->NIL);
+                    fast = cdr(fast);
+                    slow = cdr(slow);
+                    if (fast == slow) {
+                        /* the fast pointer has looped back around and caught up
+                           with the slow pointer, hence the structure is circular,
+                           not of finite length, and therefore not a list */
+                        s_retbool(0);
+                    }
+                }
+            }
+        case OP_ENVP: /* environment? */ s_retbool(is_environment(car(sc->args)));
+        case OP_VECTORP: /* vector? */ s_retbool(is_vector(car(sc->args)));
+        case OP_EQ: /* eq? */ s_retbool(car(sc->args) == cadr(sc->args));
+        case OP_EQV: /* eqv? */ s_retbool(eqv(car(sc->args), cadr(sc->args)));
+        default: sprintf(sc->strbuff, "%d: illegal operator", sc->op); Error_0(sc, sc->strbuff);
+    }
+    return sc->T;
+}
+
+static pointer
+opexe_4(scheme* sc, enum scheme_opcodes op) {
+    pointer x, y;
+
+    switch (op) {
+        case OP_FORCE: /* force */
+            sc->code = car(sc->args);
+            if (is_promise(sc->code)) {
+                /* Should change type to closure here */
+                s_save(sc, OP_SAVE_FORCED, sc->NIL, sc->code);
+                sc->args = sc->NIL;
+                s_goto(sc, OP_APPLY);
+            } else {
+                s_return(sc, sc->code);
+            }
+
+        case OP_SAVE_FORCED: /* Save forced value replacing promise */
+            memcpy(sc->code, sc->value, sizeof(struct cell));
+            s_return(sc, sc->value);
+
+        case OP_WRITE:      /* write */
+        case OP_DISPLAY:    /* display */
+        case OP_WRITE_CHAR: /* write-char */
+            if (is_pair(cdr(sc->args))) {
+                if (cadr(sc->args) != sc->outport) {
+                    x = cons(sc, sc->outport, sc->NIL);
+                    s_save(sc, OP_SET_OUTPORT, x, sc->NIL);
+                    sc->outport = cadr(sc->args);
+                }
+            }
+            sc->args = car(sc->args);
+            if (op == OP_WRITE) {
+                sc->print_flag = 1;
+            } else {
+                sc->print_flag = 0;
+            }
+            s_goto(sc, OP_P0LIST);
+
+        case OP_NEWLINE: /* newline */
+            if (is_pair(sc->args)) {
+                if (car(sc->args) != sc->outport) {
+                    x = cons(sc, sc->outport, sc->NIL);
+                    s_save(sc, OP_SET_OUTPORT, x, sc->NIL);
+                    sc->outport = car(sc->args);
+                }
+            }
+            putstr(sc, "\n");
+            s_return(sc, sc->T);
+
+        case OP_ERR0: /* error */
+            sc->retcode = -1;
+            if (!is_string(car(sc->args))) {
+                sc->args = cons(sc, mk_string(sc, " -- "), sc->args);
+                setimmutable(car(sc->args));
+            }
+            putstr(sc, "Error: ");
+            putstr(sc, strvalue(car(sc->args)));
+            sc->args = cdr(sc->args);
+            s_goto(sc, OP_ERR1);
+
+        case OP_ERR1: /* error */
+            putstr(sc, " ");
+            if (sc->args != sc->NIL) {
+                s_save(sc, OP_ERR1, cdr(sc->args), sc->NIL);
+                sc->args       = car(sc->args);
+                sc->print_flag = 1;
+                s_goto(sc, OP_P0LIST);
+            } else {
+                putstr(sc, "\n");
+                if (sc->interactive_repl) {
+                    s_goto(sc, OP_T0LVL);
+                } else {
                     return sc->NIL;
-               }
-          }
-
-     case OP_REVERSE:    /* reverse */
-          s_return(sc,reverse(sc, car(sc->args)));
-
-     case OP_LIST_STAR: /* list* */
-       s_return(sc,list_star(sc,sc->args));
-
-     case OP_APPEND:     /* append */
-          if(sc->args==sc->NIL) {
-               s_return(sc,sc->NIL);
-          }
-          x=car(sc->args);
-          if(cdr(sc->args)==sc->NIL) {
-	    s_return(sc,sc->args);
-	  }
-          for (y = cdr(sc->args); y != sc->NIL; y = cdr(y)) {
-               x=append(sc,x,car(y));
-          }
-          s_return(sc,x);
+                }
+            }
+
+        case OP_REVERSE: /* reverse */ s_return(sc, reverse(sc, car(sc->args)));
+
+        case OP_LIST_STAR: /* list* */ s_return(sc, list_star(sc, sc->args));
+
+        case OP_APPEND: /* append */
+            if (sc->args == sc->NIL) {
+                s_return(sc, sc->NIL);
+            }
+            x = car(sc->args);
+            if (cdr(sc->args) == sc->NIL) {
+                s_return(sc, sc->args);
+            }
+            for (y = cdr(sc->args); y != sc->NIL; y = cdr(y)) {
+                x = append(sc, x, car(y));
+            }
+            s_return(sc, x);
 
 #if USE_PLIST
-     case OP_PUT:        /* put */
-          if (!hasprop(car(sc->args)) || !hasprop(cadr(sc->args))) {
-               Error_0(sc,"illegal use of put");
-          }
-          for (x = symprop(car(sc->args)), y = cadr(sc->args); x != sc->NIL; x = cdr(x)) {
-               if (caar(x) == y) {
+        case OP_PUT: /* put */
+            if (!hasprop(car(sc->args)) || !hasprop(cadr(sc->args))) {
+                Error_0(sc, "illegal use of put");
+            }
+            for (x = symprop(car(sc->args)), y = cadr(sc->args); x != sc->NIL; x = cdr(x)) {
+                if (caar(x) == y) {
                     break;
-               }
-          }
-          if (x != sc->NIL)
-               cdar(x) = caddr(sc->args);
-          else
-               symprop(car(sc->args)) = cons(sc, cons(sc, y, caddr(sc->args)),
-                                symprop(car(sc->args)));
-          s_return(sc,sc->T);
-
-     case OP_GET:        /* get */
-          if (!hasprop(car(sc->args)) || !hasprop(cadr(sc->args))) {
-               Error_0(sc,"illegal use of get");
-          }
-          for (x = symprop(car(sc->args)), y = cadr(sc->args); x != sc->NIL; x = cdr(x)) {
-               if (caar(x) == y) {
+                }
+            }
+            if (x != sc->NIL)
+                cdar(x) = caddr(sc->args);
+            else
+                symprop(car(sc->args)) = cons(sc, cons(sc, y, caddr(sc->args)), symprop(car(sc->args)));
+            s_return(sc, sc->T);
+
+        case OP_GET: /* get */
+            if (!hasprop(car(sc->args)) || !hasprop(cadr(sc->args))) {
+                Error_0(sc, "illegal use of get");
+            }
+            for (x = symprop(car(sc->args)), y = cadr(sc->args); x != sc->NIL; x = cdr(x)) {
+                if (caar(x) == y) {
                     break;
-               }
-          }
-          if (x != sc->NIL) {
-               s_return(sc,cdar(x));
-          } else {
-               s_return(sc,sc->NIL);
-          }
-#endif /* USE_PLIST */
-     case OP_QUIT:       /* quit */
-          if(is_pair(sc->args)) {
-               sc->retcode=ivalue(car(sc->args));
-          }
-          return (sc->NIL);
-
-     case OP_GC:         /* gc */
-          gc(sc, sc->NIL, sc->NIL);
-          s_return(sc,sc->T);
-
-     case OP_GCVERB:          /* gc-verbose */
-     {    int  was = sc->gc_verbose;
-          
-          sc->gc_verbose = (car(sc->args) != sc->F);
-          s_retbool(was);
-     }
-
-     case OP_NEWSEGMENT: /* new-segment */
-          if (!is_pair(sc->args) || !is_number(car(sc->args))) {
-               Error_0(sc,"new-segment: argument must be a number");
-          }
-          alloc_cellseg(sc, (int) ivalue(car(sc->args)));
-          s_return(sc,sc->T);
-
-     case OP_OBLIST: /* oblist */
-          s_return(sc, oblist_all_symbols(sc)); 
-
-     case OP_CURR_INPORT: /* current-input-port */
-          s_return(sc,sc->inport);
-
-     case OP_CURR_OUTPORT: /* current-output-port */
-          s_return(sc,sc->outport);
-
-     case OP_OPEN_INFILE: /* open-input-file */
-     case OP_OPEN_OUTFILE: /* open-output-file */
-     case OP_OPEN_INOUTFILE: /* open-input-output-file */ {
-          int prop=0;
-          pointer p;
-          switch(op) {
-               case OP_OPEN_INFILE:     prop=port_input; break;
-               case OP_OPEN_OUTFILE:    prop=port_output; break;
-               case OP_OPEN_INOUTFILE: prop=port_input|port_output; break;
-	       default: 
-		   ;
-          }
-          p=port_from_filename(sc,strvalue(car(sc->args)),prop);
-          if(p==sc->NIL) {
-               s_return(sc,sc->F);
-          }
-          s_return(sc,p);
-     }
-     
+                }
+            }
+            if (x != sc->NIL) {
+                s_return(sc, cdar(x));
+            } else {
+                s_return(sc, sc->NIL);
+            }
+#endif                /* USE_PLIST */
+        case OP_QUIT: /* quit */
+            if (is_pair(sc->args)) {
+                sc->retcode = ivalue(car(sc->args));
+            }
+            return (sc->NIL);
+
+        case OP_GC: /* gc */ gc(sc, sc->NIL, sc->NIL); s_return(sc, sc->T);
+
+        case OP_GCVERB: /* gc-verbose */
+            {
+                int was = sc->gc_verbose;
+
+                sc->gc_verbose = (car(sc->args) != sc->F);
+                s_retbool(was);
+            }
+
+        case OP_NEWSEGMENT: /* new-segment */
+            if (!is_pair(sc->args) || !is_number(car(sc->args))) {
+                Error_0(sc, "new-segment: argument must be a number");
+            }
+            alloc_cellseg(sc, (int)ivalue(car(sc->args)));
+            s_return(sc, sc->T);
+
+        case OP_OBLIST: /* oblist */ s_return(sc, oblist_all_symbols(sc));
+
+        case OP_CURR_INPORT: /* current-input-port */ s_return(sc, sc->inport);
+
+        case OP_CURR_OUTPORT: /* current-output-port */ s_return(sc, sc->outport);
+
+        case OP_OPEN_INFILE:    /* open-input-file */
+        case OP_OPEN_OUTFILE:   /* open-output-file */
+        case OP_OPEN_INOUTFILE: /* open-input-output-file */
+            {
+                int     prop = 0;
+                pointer p;
+                switch (op) {
+                    case OP_OPEN_INFILE: prop = port_input; break;
+                    case OP_OPEN_OUTFILE: prop = port_output; break;
+                    case OP_OPEN_INOUTFILE: prop = port_input | port_output; break;
+                    default:;
+                }
+                p = port_from_filename(sc, strvalue(car(sc->args)), prop);
+                if (p == sc->NIL) {
+                    s_return(sc, sc->F);
+                }
+                s_return(sc, p);
+            }
+
 #if USE_STRING_PORTS
-     case OP_OPEN_INSTRING: /* open-input-string */
-     case OP_OPEN_OUTSTRING: /* open-output-string */
-     case OP_OPEN_INOUTSTRING: /* open-input-output-string */ {
-          int prop=0;
-          pointer p;
-          switch(op) {
-               case OP_OPEN_INSTRING:     prop=port_input; break;
-               case OP_OPEN_OUTSTRING:    prop=port_output; break;
-               case OP_OPEN_INOUTSTRING:  prop=port_input|port_output; break;
-	       default:
-		   ;
-          }
-          p=port_from_string(sc, strvalue(car(sc->args)),
-	             strvalue(car(sc->args))+strlength(car(sc->args)), prop);
-          if(p==sc->NIL) {
-               s_return(sc,sc->F);
-          }
-          s_return(sc,p);
-     }
+        case OP_OPEN_INSTRING:    /* open-input-string */
+        case OP_OPEN_OUTSTRING:   /* open-output-string */
+        case OP_OPEN_INOUTSTRING: /* open-input-output-string */
+            {
+                int     prop = 0;
+                pointer p;
+                switch (op) {
+                    case OP_OPEN_INSTRING: prop = port_input; break;
+                    case OP_OPEN_OUTSTRING: prop = port_output; break;
+                    case OP_OPEN_INOUTSTRING: prop = port_input | port_output; break;
+                    default:;
+                }
+                p = port_from_string(
+                    sc, strvalue(car(sc->args)), strvalue(car(sc->args)) + strlength(car(sc->args)), prop
+                );
+                if (p == sc->NIL) {
+                    s_return(sc, sc->F);
+                }
+                s_return(sc, p);
+            }
 #endif
 
-     case OP_CLOSE_INPORT: /* close-input-port */
-          port_close(sc,car(sc->args),port_input);
-          s_return(sc,sc->T);
-
-     case OP_CLOSE_OUTPORT: /* close-output-port */
-          port_close(sc,car(sc->args),port_output);
-          s_return(sc,sc->T);
-
-     case OP_INT_ENV: /* interaction-environment */
-          s_return(sc,sc->global_env);
-
-     case OP_CURR_ENV: /* current-environment */
-          s_return(sc,sc->envir);
-     default:
-	 ;
-     }
-     return sc->T;
-}
-
-static pointer opexe_5(scheme *sc, enum scheme_opcodes op) {
-     pointer x;
-
-     if(sc->nesting!=0) {
-          int n=sc->nesting;
-          sc->nesting=0;
-          sc->retcode=-1;
-          Error_1(sc,"unmatched parentheses:",mk_integer(sc,n));
-     }
-
-     switch (op) {
-     /* ========== reading part ========== */
-     case OP_READ:
-          if(!is_pair(sc->args)) {
-               s_goto(sc,OP_READ_INTERNAL);
-          }
-          if(!is_inport(car(sc->args))) {
-               Error_1(sc,"read: not an input port:",car(sc->args));
-          }
-          if(car(sc->args)==sc->inport) {
-               s_goto(sc,OP_READ_INTERNAL);
-          }
-          x=sc->inport;
-          sc->inport=car(sc->args);
-          x=cons(sc,x,sc->NIL);
-          s_save(sc,OP_SET_INPORT, x, sc->NIL);
-          s_goto(sc,OP_READ_INTERNAL);
-
-     case OP_READ_CHAR: /* read-char */
-     case OP_PEEK_CHAR: /* peek-char */ {
-          int c;
-          if(is_pair(sc->args)) {
-               if(car(sc->args)!=sc->inport) {
-                    x=sc->inport;
-                    x=cons(sc,x,sc->NIL);
-                    s_save(sc,OP_SET_INPORT, x, sc->NIL);
-                    sc->inport=car(sc->args);
-               }
-          }
-          c=inchar(sc);
-          if(c==EOF) {
-               s_return(sc,sc->EOF_OBJ);
-          }
-          if(sc->op==OP_PEEK_CHAR) {
-               backchar(sc,c);
-          }
-          s_return(sc,mk_character(sc,c));
-     }
-
-     case OP_CHAR_READY: /* char-ready? */ {
-          pointer p=sc->inport;
-          int res;
-          if(is_pair(sc->args)) {
-               p=car(sc->args);
-          }
-          res=p->_object._port->kind&port_string;
-          s_retbool(res);
-     }
-
-     case OP_SET_INPORT: /* set-input-port */
-          sc->inport=car(sc->args);
-          s_return(sc,sc->value);
-
-     case OP_SET_OUTPORT: /* set-output-port */
-          sc->outport=car(sc->args);
-          s_return(sc,sc->value);
-
-     case OP_RDSEXPR:
-          switch (sc->tok) {
-          case TOK_EOF:
-               if(sc->inport==sc->loadport) {
-                    sc->args=sc->NIL;
-                    s_goto(sc,OP_QUIT);
-               } else {
-                    s_return(sc,sc->EOF_OBJ);
-               }
-          case TOK_COMMENT: {
-               int c;
-               while ((c=inchar(sc)) != '\n' && c!=EOF)
-                    ;
-               sc->tok = token(sc);
-               s_goto(sc,OP_RDSEXPR);
-          }
-          case TOK_VEC:
-               s_save(sc,OP_RDVEC,sc->NIL,sc->NIL);
-               /* fall through */
-          case TOK_LPAREN:
-               sc->tok = token(sc);
-               if (sc->tok == TOK_RPAREN) {
-                    s_return(sc,sc->NIL);
-               } else if (sc->tok == TOK_DOT) {
-                    Error_0(sc,"syntax error: illegal dot expression");
-               } else {
-                    sc->nesting_stack[sc->file_i]++;
-                    s_save(sc,OP_RDLIST, sc->NIL, sc->NIL);
-                    s_goto(sc,OP_RDSEXPR);
-               }
-          case TOK_QUOTE:
-               s_save(sc,OP_RDQUOTE, sc->NIL, sc->NIL);
-               sc->tok = token(sc);
-               s_goto(sc,OP_RDSEXPR);
-          case TOK_BQUOTE:
-               sc->tok = token(sc);
-	       if(sc->tok==TOK_VEC) {
-		 s_save(sc,OP_RDQQUOTEVEC, sc->NIL, sc->NIL);
-		 sc->tok=TOK_LPAREN;
-		 s_goto(sc,OP_RDSEXPR);
-	       } else {
-		 s_save(sc,OP_RDQQUOTE, sc->NIL, sc->NIL);
-	       }
-               s_goto(sc,OP_RDSEXPR);
-          case TOK_COMMA:
-               s_save(sc,OP_RDUNQUOTE, sc->NIL, sc->NIL);
-               sc->tok = token(sc);
-               s_goto(sc,OP_RDSEXPR);
-          case TOK_ATMARK:
-               s_save(sc,OP_RDUQTSP, sc->NIL, sc->NIL);
-               sc->tok = token(sc);
-               s_goto(sc,OP_RDSEXPR);
-          case TOK_ATOM:
-               s_return(sc,mk_atom(sc, readstr_upto(sc, "();\t\n\r ")));
-          case TOK_DQUOTE:
-               x=readstrexp(sc);
-	       if(x==sc->F) {
-		 Error_0(sc,"Error reading string");
-	       }
-               setimmutable(x);
-               s_return(sc,x);
-          case TOK_SHARP: {
-               pointer f=find_slot_in_env(sc,sc->envir,sc->SHARP_HOOK,1);
-               if(f==sc->NIL) {
-                    Error_0(sc,"undefined sharp expression");
-               } else {
-                    sc->code=cons(sc,slot_value_in_env(f),sc->NIL); 
-                    s_goto(sc,OP_EVAL);
-               }
-          }
-          case TOK_SHARP_CONST:
-               if ((x = mk_sharp_const(sc, readstr_upto(sc, "();\t\n\r "))) == sc->NIL) {
-                    Error_0(sc,"undefined sharp expression");
-               } else {
-                    s_return(sc,x);
-               }
-          default:
-               Error_0(sc,"syntax error: illegal token");
-          }
-          break;
-
-     case OP_RDLIST: {
-          sc->args = cons(sc, sc->value, sc->args);
-          sc->tok = token(sc);
-          if (sc->tok == TOK_COMMENT) {
-               int c;
-               while ((c=inchar(sc)) != '\n' && c!=EOF)
+        case OP_CLOSE_INPORT: /* close-input-port */ port_close(sc, car(sc->args), port_input); s_return(sc, sc->T);
+
+        case OP_CLOSE_OUTPORT: /* close-output-port */ port_close(sc, car(sc->args), port_output); s_return(sc, sc->T);
+
+        case OP_INT_ENV: /* interaction-environment */ s_return(sc, sc->global_env);
+
+        case OP_CURR_ENV: /* current-environment */ s_return(sc, sc->envir);
+        default:;
+    }
+    return sc->T;
+}
+
+static pointer
+opexe_5(scheme* sc, enum scheme_opcodes op) {
+    pointer x;
+
+    if (sc->nesting != 0) {
+        int n       = sc->nesting;
+        sc->nesting = 0;
+        sc->retcode = -1;
+        Error_1(sc, "unmatched parentheses:", mk_integer(sc, n));
+    }
+
+    switch (op) {
+        /* ========== reading part ========== */
+        case OP_READ:
+            if (!is_pair(sc->args)) {
+                s_goto(sc, OP_READ_INTERNAL);
+            }
+            if (!is_inport(car(sc->args))) {
+                Error_1(sc, "read: not an input port:", car(sc->args));
+            }
+            if (car(sc->args) == sc->inport) {
+                s_goto(sc, OP_READ_INTERNAL);
+            }
+            x          = sc->inport;
+            sc->inport = car(sc->args);
+            x          = cons(sc, x, sc->NIL);
+            s_save(sc, OP_SET_INPORT, x, sc->NIL);
+            s_goto(sc, OP_READ_INTERNAL);
+
+        case OP_READ_CHAR: /* read-char */
+        case OP_PEEK_CHAR: /* peek-char */
+            {
+                int c;
+                if (is_pair(sc->args)) {
+                    if (car(sc->args) != sc->inport) {
+                        x = sc->inport;
+                        x = cons(sc, x, sc->NIL);
+                        s_save(sc, OP_SET_INPORT, x, sc->NIL);
+                        sc->inport = car(sc->args);
+                    }
+                }
+                c = inchar(sc);
+                if (c == EOF) {
+                    s_return(sc, sc->EOF_OBJ);
+                }
+                if (sc->op == OP_PEEK_CHAR) {
+                    backchar(sc, c);
+                }
+                s_return(sc, mk_character(sc, c));
+            }
+
+        case OP_CHAR_READY: /* char-ready? */
+            {
+                pointer p = sc->inport;
+                int     res;
+                if (is_pair(sc->args)) {
+                    p = car(sc->args);
+                }
+                res = p->_object._port->kind & port_string;
+                s_retbool(res);
+            }
+
+        case OP_SET_INPORT: /* set-input-port */ sc->inport = car(sc->args); s_return(sc, sc->value);
+
+        case OP_SET_OUTPORT: /* set-output-port */ sc->outport = car(sc->args); s_return(sc, sc->value);
+
+        case OP_RDSEXPR:
+            switch (sc->tok) {
+                case TOK_EOF:
+                    if (sc->inport == sc->loadport) {
+                        sc->args = sc->NIL;
+                        s_goto(sc, OP_QUIT);
+                    } else {
+                        s_return(sc, sc->EOF_OBJ);
+                    }
+                case TOK_COMMENT:
+                    {
+                        int c;
+                        while ((c = inchar(sc)) != '\n' && c != EOF)
+                            ;
+                        sc->tok = token(sc);
+                        s_goto(sc, OP_RDSEXPR);
+                    }
+                case TOK_VEC:
+                    s_save(sc, OP_RDVEC, sc->NIL, sc->NIL);
+                    /* fall through */
+                case TOK_LPAREN:
+                    sc->tok = token(sc);
+                    if (sc->tok == TOK_RPAREN) {
+                        s_return(sc, sc->NIL);
+                    } else if (sc->tok == TOK_DOT) {
+                        Error_0(sc, "syntax error: illegal dot expression");
+                    } else {
+                        sc->nesting_stack[sc->file_i]++;
+                        s_save(sc, OP_RDLIST, sc->NIL, sc->NIL);
+                        s_goto(sc, OP_RDSEXPR);
+                    }
+                case TOK_QUOTE:
+                    s_save(sc, OP_RDQUOTE, sc->NIL, sc->NIL);
+                    sc->tok = token(sc);
+                    s_goto(sc, OP_RDSEXPR);
+                case TOK_BQUOTE:
+                    sc->tok = token(sc);
+                    if (sc->tok == TOK_VEC) {
+                        s_save(sc, OP_RDQQUOTEVEC, sc->NIL, sc->NIL);
+                        sc->tok = TOK_LPAREN;
+                        s_goto(sc, OP_RDSEXPR);
+                    } else {
+                        s_save(sc, OP_RDQQUOTE, sc->NIL, sc->NIL);
+                    }
+                    s_goto(sc, OP_RDSEXPR);
+                case TOK_COMMA:
+                    s_save(sc, OP_RDUNQUOTE, sc->NIL, sc->NIL);
+                    sc->tok = token(sc);
+                    s_goto(sc, OP_RDSEXPR);
+                case TOK_ATMARK:
+                    s_save(sc, OP_RDUQTSP, sc->NIL, sc->NIL);
+                    sc->tok = token(sc);
+                    s_goto(sc, OP_RDSEXPR);
+                case TOK_ATOM: s_return(sc, mk_atom(sc, readstr_upto(sc, "();\t\n\r ")));
+                case TOK_DQUOTE:
+                    x = readstrexp(sc);
+                    if (x == sc->F) {
+                        Error_0(sc, "Error reading string");
+                    }
+                    setimmutable(x);
+                    s_return(sc, x);
+                case TOK_SHARP:
+                    {
+                        pointer f = find_slot_in_env(sc, sc->envir, sc->SHARP_HOOK, 1);
+                        if (f == sc->NIL) {
+                            Error_0(sc, "undefined sharp expression");
+                        } else {
+                            sc->code = cons(sc, slot_value_in_env(f), sc->NIL);
+                            s_goto(sc, OP_EVAL);
+                        }
+                    }
+                case TOK_SHARP_CONST:
+                    if ((x = mk_sharp_const(sc, readstr_upto(sc, "();\t\n\r "))) == sc->NIL) {
+                        Error_0(sc, "undefined sharp expression");
+                    } else {
+                        s_return(sc, x);
+                    }
+                default: Error_0(sc, "syntax error: illegal token");
+            }
+            break;
+
+        case OP_RDLIST:
+            {
+                sc->args = cons(sc, sc->value, sc->args);
+                sc->tok  = token(sc);
+                if (sc->tok == TOK_COMMENT) {
+                    int c;
+                    while ((c = inchar(sc)) != '\n' && c != EOF)
+                        ;
+                    sc->tok = token(sc);
+                }
+                if (sc->tok == TOK_RPAREN) {
+                    int c = inchar(sc);
+                    if (c != '\n')
+                        backchar(sc, c);
+                    sc->nesting_stack[sc->file_i]--;
+                    s_return(sc, reverse_in_place(sc, sc->NIL, sc->args));
+                } else if (sc->tok == TOK_DOT) {
+                    s_save(sc, OP_RDDOT, sc->args, sc->NIL);
+                    sc->tok = token(sc);
+                    s_goto(sc, OP_RDSEXPR);
+                } else {
+                    s_save(sc, OP_RDLIST, sc->args, sc->NIL);
                     ;
-               sc->tok = token(sc);
-          }
-          if (sc->tok == TOK_RPAREN) {
-               int c = inchar(sc);
-               if (c != '\n') backchar(sc,c);
-               sc->nesting_stack[sc->file_i]--;
-               s_return(sc,reverse_in_place(sc, sc->NIL, sc->args));
-          } else if (sc->tok == TOK_DOT) {
-               s_save(sc,OP_RDDOT, sc->args, sc->NIL);
-               sc->tok = token(sc);
-               s_goto(sc,OP_RDSEXPR);
-          } else {
-               s_save(sc,OP_RDLIST, sc->args, sc->NIL);;
-               s_goto(sc,OP_RDSEXPR);
-          }
-     }
-
-     case OP_RDDOT:
-          if (token(sc) != TOK_RPAREN) {
-               Error_0(sc,"syntax error: illegal dot expression");
-          } else {
-               sc->nesting_stack[sc->file_i]--;
-               s_return(sc,reverse_in_place(sc, sc->value, sc->args));
-          }
-
-     case OP_RDQUOTE:
-          s_return(sc,cons(sc, sc->QUOTE, cons(sc, sc->value, sc->NIL)));
-
-     case OP_RDQQUOTE:
-          s_return(sc,cons(sc, sc->QQUOTE, cons(sc, sc->value, sc->NIL)));
-
-     case OP_RDQQUOTEVEC:
-       s_return(sc,cons(sc, mk_symbol(sc,"apply"),
-			cons(sc, mk_symbol(sc,"vector"), 
-			     cons(sc,cons(sc, sc->QQUOTE, 
-				  cons(sc,sc->value,sc->NIL)),
-				  sc->NIL))));
-
-     case OP_RDUNQUOTE:
-          s_return(sc,cons(sc, sc->UNQUOTE, cons(sc, sc->value, sc->NIL)));
-
-     case OP_RDUQTSP:
-          s_return(sc,cons(sc, sc->UNQUOTESP, cons(sc, sc->value, sc->NIL)));
-
-     case OP_RDVEC:
-          /*sc->code=cons(sc,mk_proc(sc,OP_VECTOR),sc->value);
-          s_goto(sc,OP_EVAL); Cannot be quoted*/
-       /*x=cons(sc,mk_proc(sc,OP_VECTOR),sc->value);
-	 s_return(sc,x); Cannot be part of pairs*/
-       /*sc->code=mk_proc(sc,OP_VECTOR);
-       sc->args=sc->value;
-       s_goto(sc,OP_APPLY);*/
-       sc->args=sc->value;
-       s_goto(sc,OP_VECTOR);
-
-     /* ========== printing part ========== */
-     case OP_P0LIST:
-          if(is_vector(sc->args)) {
-               putstr(sc,"#(");
-               sc->args=cons(sc,sc->args,mk_integer(sc,0));
-               s_goto(sc,OP_PVECFROM);
-          } else if(is_environment(sc->args)) {
-               putstr(sc,"#<ENVIRONMENT>");
-               s_return(sc,sc->T);
-          } else if (!is_pair(sc->args)) {
-               printatom(sc, sc->args, sc->print_flag);
-               s_return(sc,sc->T);
-          } else if (car(sc->args) == sc->QUOTE && ok_abbrev(cdr(sc->args))) {
-               putstr(sc, "'");
-               sc->args = cadr(sc->args);
-               s_goto(sc,OP_P0LIST);
-          } else if (car(sc->args) == sc->QQUOTE && ok_abbrev(cdr(sc->args))) {
-               putstr(sc, "`");
-               sc->args = cadr(sc->args);
-               s_goto(sc,OP_P0LIST);
-          } else if (car(sc->args) == sc->UNQUOTE && ok_abbrev(cdr(sc->args))) {
-               putstr(sc, ",");
-               sc->args = cadr(sc->args);
-               s_goto(sc,OP_P0LIST);
-          } else if (car(sc->args) == sc->UNQUOTESP && ok_abbrev(cdr(sc->args))) {
-               putstr(sc, ",@");
-               sc->args = cadr(sc->args);
-               s_goto(sc,OP_P0LIST);
-          } else {
-               putstr(sc, "(");
-               s_save(sc,OP_P1LIST, cdr(sc->args), sc->NIL);
-               sc->args = car(sc->args);
-               s_goto(sc,OP_P0LIST);
-          }
-
-     case OP_P1LIST:
-          if (is_pair(sc->args)) {
-	    s_save(sc,OP_P1LIST, cdr(sc->args), sc->NIL);
-	    putstr(sc, " ");
-	    sc->args = car(sc->args);
-	    s_goto(sc,OP_P0LIST);
-	  } else if(is_vector(sc->args)) {
-	    s_save(sc,OP_P1LIST,sc->NIL,sc->NIL);
-	    putstr(sc, " . ");
-	    s_goto(sc,OP_P0LIST);
-          } else {
-	    if (sc->args != sc->NIL) {
-	      putstr(sc, " . ");
-	      printatom(sc, sc->args, sc->print_flag);
-	    }
-	    putstr(sc, ")");
-	    s_return(sc,sc->T);
-          }
-     case OP_PVECFROM: {
-          int i=ivalue_unchecked(cdr(sc->args));
-          pointer vec=car(sc->args);
-          int len=ivalue_unchecked(vec);
-          if(i==len) {
-               putstr(sc,")");
-               s_return(sc,sc->T);
-          } else {
-               pointer elem=vector_elem(vec,i);
-               ivalue_unchecked(cdr(sc->args))=i+1;
-               s_save(sc,OP_PVECFROM, sc->args, sc->NIL);
-               sc->args=elem;
-               putstr(sc," ");
-               s_goto(sc,OP_P0LIST);
-          }
-     }
-
-     default:
-          sprintf(sc->strbuff, "%d: illegal operator", sc->op);
-          Error_0(sc,sc->strbuff);
-
-     }
-     return sc->T;
-}
-
-static pointer opexe_6(scheme *sc, enum scheme_opcodes op) {
-     pointer x, y;
-     long v;
-
-     switch (op) {
-     case OP_LIST_LENGTH:     /* length */   /* a.k */
-          v=list_length(sc,car(sc->args));
-          if(v<0) {
-               Error_1(sc,"length: not a list:",car(sc->args));
-          }
-          s_return(sc,mk_integer(sc, v));
-
-     case OP_ASSQ:       /* assq */     /* a.k */
-          x = car(sc->args);
-          for (y = cadr(sc->args); is_pair(y); y = cdr(y)) {
-               if (!is_pair(car(y))) {
-                    Error_0(sc,"unable to handle non pair element");
-               }
-               if (x == caar(y))
+                    s_goto(sc, OP_RDSEXPR);
+                }
+            }
+
+        case OP_RDDOT:
+            if (token(sc) != TOK_RPAREN) {
+                Error_0(sc, "syntax error: illegal dot expression");
+            } else {
+                sc->nesting_stack[sc->file_i]--;
+                s_return(sc, reverse_in_place(sc, sc->value, sc->args));
+            }
+
+        case OP_RDQUOTE: s_return(sc, cons(sc, sc->QUOTE, cons(sc, sc->value, sc->NIL)));
+
+        case OP_RDQQUOTE: s_return(sc, cons(sc, sc->QQUOTE, cons(sc, sc->value, sc->NIL)));
+
+        case OP_RDQQUOTEVEC:
+            s_return(
+                sc, cons(
+                        sc, mk_symbol(sc, "apply"),
+                        cons(
+                            sc, mk_symbol(sc, "vector"),
+                            cons(sc, cons(sc, sc->QQUOTE, cons(sc, sc->value, sc->NIL)), sc->NIL)
+                        )
+                    )
+            );
+
+        case OP_RDUNQUOTE: s_return(sc, cons(sc, sc->UNQUOTE, cons(sc, sc->value, sc->NIL)));
+
+        case OP_RDUQTSP: s_return(sc, cons(sc, sc->UNQUOTESP, cons(sc, sc->value, sc->NIL)));
+
+        case OP_RDVEC:
+            /*sc->code=cons(sc,mk_proc(sc,OP_VECTOR),sc->value);
+            s_goto(sc,OP_EVAL); Cannot be quoted*/
+            /*x=cons(sc,mk_proc(sc,OP_VECTOR),sc->value);
+          s_return(sc,x); Cannot be part of pairs*/
+            /*sc->code=mk_proc(sc,OP_VECTOR);
+            sc->args=sc->value;
+            s_goto(sc,OP_APPLY);*/
+            sc->args = sc->value;
+            s_goto(sc, OP_VECTOR);
+
+        /* ========== printing part ========== */
+        case OP_P0LIST:
+            if (is_vector(sc->args)) {
+                putstr(sc, "#(");
+                sc->args = cons(sc, sc->args, mk_integer(sc, 0));
+                s_goto(sc, OP_PVECFROM);
+            } else if (is_environment(sc->args)) {
+                putstr(sc, "#<ENVIRONMENT>");
+                s_return(sc, sc->T);
+            } else if (!is_pair(sc->args)) {
+                printatom(sc, sc->args, sc->print_flag);
+                s_return(sc, sc->T);
+            } else if (car(sc->args) == sc->QUOTE && ok_abbrev(cdr(sc->args))) {
+                putstr(sc, "'");
+                sc->args = cadr(sc->args);
+                s_goto(sc, OP_P0LIST);
+            } else if (car(sc->args) == sc->QQUOTE && ok_abbrev(cdr(sc->args))) {
+                putstr(sc, "`");
+                sc->args = cadr(sc->args);
+                s_goto(sc, OP_P0LIST);
+            } else if (car(sc->args) == sc->UNQUOTE && ok_abbrev(cdr(sc->args))) {
+                putstr(sc, ",");
+                sc->args = cadr(sc->args);
+                s_goto(sc, OP_P0LIST);
+            } else if (car(sc->args) == sc->UNQUOTESP && ok_abbrev(cdr(sc->args))) {
+                putstr(sc, ",@");
+                sc->args = cadr(sc->args);
+                s_goto(sc, OP_P0LIST);
+            } else {
+                putstr(sc, "(");
+                s_save(sc, OP_P1LIST, cdr(sc->args), sc->NIL);
+                sc->args = car(sc->args);
+                s_goto(sc, OP_P0LIST);
+            }
+
+        case OP_P1LIST:
+            if (is_pair(sc->args)) {
+                s_save(sc, OP_P1LIST, cdr(sc->args), sc->NIL);
+                putstr(sc, " ");
+                sc->args = car(sc->args);
+                s_goto(sc, OP_P0LIST);
+            } else if (is_vector(sc->args)) {
+                s_save(sc, OP_P1LIST, sc->NIL, sc->NIL);
+                putstr(sc, " . ");
+                s_goto(sc, OP_P0LIST);
+            } else {
+                if (sc->args != sc->NIL) {
+                    putstr(sc, " . ");
+                    printatom(sc, sc->args, sc->print_flag);
+                }
+                putstr(sc, ")");
+                s_return(sc, sc->T);
+            }
+        case OP_PVECFROM:
+            {
+                int     i   = ivalue_unchecked(cdr(sc->args));
+                pointer vec = car(sc->args);
+                int     len = ivalue_unchecked(vec);
+                if (i == len) {
+                    putstr(sc, ")");
+                    s_return(sc, sc->T);
+                } else {
+                    pointer elem                    = vector_elem(vec, i);
+                    ivalue_unchecked(cdr(sc->args)) = i + 1;
+                    s_save(sc, OP_PVECFROM, sc->args, sc->NIL);
+                    sc->args = elem;
+                    putstr(sc, " ");
+                    s_goto(sc, OP_P0LIST);
+                }
+            }
+
+        default: sprintf(sc->strbuff, "%d: illegal operator", sc->op); Error_0(sc, sc->strbuff);
+    }
+    return sc->T;
+}
+
+static pointer
+opexe_6(scheme* sc, enum scheme_opcodes op) {
+    pointer x, y;
+    long    v;
+
+    switch (op) {
+        case OP_LIST_LENGTH: /* length */ /* a.k */
+            v = list_length(sc, car(sc->args));
+            if (v < 0) {
+                Error_1(sc, "length: not a list:", car(sc->args));
+            }
+            s_return(sc, mk_integer(sc, v));
+
+        case OP_ASSQ: /* assq */ /* a.k */
+            x = car(sc->args);
+            for (y = cadr(sc->args); is_pair(y); y = cdr(y)) {
+                if (!is_pair(car(y))) {
+                    Error_0(sc, "unable to handle non pair element");
+                }
+                if (x == caar(y))
                     break;
-          }
-          if (is_pair(y)) {
-               s_return(sc,car(y));
-          } else {
-               s_return(sc,sc->F);
-          }
-          
-          
-     case OP_GET_CLOSURE:     /* get-closure-code */   /* a.k */
-          sc->args = car(sc->args);
-          if (sc->args == sc->NIL) {
-               s_return(sc,sc->F);
-          } else if (is_closure(sc->args)) {
-               s_return(sc,cons(sc, sc->LAMBDA, closure_code(sc->value)));
-          } else if (is_macro(sc->args)) {
-               s_return(sc,cons(sc, sc->LAMBDA, closure_code(sc->value)));
-          } else {
-               s_return(sc,sc->F);
-          }
-     case OP_CLOSUREP:        /* closure? */
-          /*
-           * Note, macro object is also a closure.
-           * Therefore, (closure? <#MACRO>) ==> #t
-           */
-          s_retbool(is_closure(car(sc->args)));
-     case OP_MACROP:          /* macro? */
-          s_retbool(is_macro(car(sc->args)));
-     default:
-          sprintf(sc->strbuff, "%d: illegal operator", sc->op);
-          Error_0(sc,sc->strbuff);
-     }
-     return sc->T; /* NOTREACHED */
-}
-
-typedef pointer (*dispatch_func)(scheme *, enum scheme_opcodes);
+            }
+            if (is_pair(y)) {
+                s_return(sc, car(y));
+            } else {
+                s_return(sc, sc->F);
+            }
+
+        case OP_GET_CLOSURE: /* get-closure-code */ /* a.k */
+            sc->args = car(sc->args);
+            if (sc->args == sc->NIL) {
+                s_return(sc, sc->F);
+            } else if (is_closure(sc->args)) {
+                s_return(sc, cons(sc, sc->LAMBDA, closure_code(sc->value)));
+            } else if (is_macro(sc->args)) {
+                s_return(sc, cons(sc, sc->LAMBDA, closure_code(sc->value)));
+            } else {
+                s_return(sc, sc->F);
+            }
+        case OP_CLOSUREP: /* closure? */
+            /*
+             * Note, macro object is also a closure.
+             * Therefore, (closure? <#MACRO>) ==> #t
+             */
+            s_retbool(is_closure(car(sc->args)));
+        case OP_MACROP: /* macro? */ s_retbool(is_macro(car(sc->args)));
+        default: sprintf(sc->strbuff, "%d: illegal operator", sc->op); Error_0(sc, sc->strbuff);
+    }
+    return sc->T; /* NOTREACHED */
+}
+
+typedef pointer (*dispatch_func)(scheme*, enum scheme_opcodes);
 
 typedef int (*test_predicate)(pointer);
-static int is_any(pointer p) { return 1;}
-static int is_num_integer(pointer p) { 
-  return is_number(p) && ((p)->_object._number.is_fixnum); 
+
+static int
+is_any(pointer p) {
+    return 1;
+}
+
+static int
+is_num_integer(pointer p) {
+    return is_number(p) && ((p)->_object._number.is_fixnum);
 }
-static int is_nonneg(pointer p) {
-  return is_num_integer(p) && ivalue(p)>=0;
+
+static int
+is_nonneg(pointer p) {
+    return is_num_integer(p) && ivalue(p) >= 0;
 }
 
 /* Correspond carefully with following defines! */
 static struct {
-  test_predicate fct;
-  const char *kind;
-} tests[]={
-  {0,0}, /* unused */
-  {is_any, 0},
-  {is_string, "string"},
-  {is_symbol, "symbol"},
-  {is_port, "port"},
-  {0,"input port"},
-  {0,"output_port"},
-  {is_environment, "environment"},
-  {is_pair, "pair"},
-  {0, "pair or '()"},
-  {is_character, "character"},
-  {is_vector, "vector"},
-  {is_number, "number"},
-  {is_num_integer, "integer"},
-  {is_nonneg, "non-negative integer"}
+    test_predicate fct;
+    const char*    kind;
+} tests[] = {
+    {             0,                      0}, /* unused */
+    {        is_any,                      0},
+    {     is_string,               "string"},
+    {     is_symbol,               "symbol"},
+    {       is_port,                 "port"},
+    {             0,           "input port"},
+    {             0,          "output_port"},
+    {is_environment,          "environment"},
+    {       is_pair,                 "pair"},
+    {             0,          "pair or '()"},
+    {  is_character,            "character"},
+    {     is_vector,               "vector"},
+    {     is_number,               "number"},
+    {is_num_integer,              "integer"},
+    {     is_nonneg, "non-negative integer"}
 };
 
-#define TST_NONE 0
-#define TST_ANY "\001"
-#define TST_STRING "\002"
-#define TST_SYMBOL "\003"
-#define TST_PORT "\004"
-#define TST_INPORT "\005"
-#define TST_OUTPORT "\006"
+#define TST_NONE        0
+#define TST_ANY         "\001"
+#define TST_STRING      "\002"
+#define TST_SYMBOL      "\003"
+#define TST_PORT        "\004"
+#define TST_INPORT      "\005"
+#define TST_OUTPORT     "\006"
 #define TST_ENVIRONMENT "\007"
-#define TST_PAIR "\010"
-#define TST_LIST "\011"
-#define TST_CHAR "\012"
-#define TST_VECTOR "\013"
-#define TST_NUMBER "\014"
-#define TST_INTEGER "\015"
-#define TST_NATURAL "\016"
+#define TST_PAIR        "\010"
+#define TST_LIST        "\011"
+#define TST_CHAR        "\012"
+#define TST_VECTOR      "\013"
+#define TST_NUMBER      "\014"
+#define TST_INTEGER     "\015"
+#define TST_NATURAL     "\016"
 
 typedef struct {
-  dispatch_func func;
-  char *name;
-  int min_arity;
-  int max_arity;
-  char *arg_tests_encoding;
+    dispatch_func func;
+    char*         name;
+    int           min_arity;
+    int           max_arity;
+    char*         arg_tests_encoding;
 } op_code_info;
 
 #define INF_ARG 0xffff
 
-static op_code_info dispatch_table[]= { 
-#define _OP_DEF(A,B,C,D,E,OP) {A,B,C,D,E}, 
-#include "opdefines.h" 
-  { 0 } 
-}; 
+static op_code_info dispatch_table[] = {
+#define _OP_DEF(A, B, C, D, E, OP) { A, B, C, D, E },
+#include "opdefines.h"
+    { 0 }
+};
 
-static const char *procname(pointer x) {
- int n=procnum(x);
- const char *name=dispatch_table[n].name;
- if(name==0) {
-     name="ILLEGAL!";
- }
- return name;
+static const char*
+procname(pointer x) {
+    int         n    = procnum(x);
+    const char* name = dispatch_table[n].name;
+    if (name == 0) {
+        name = "ILLEGAL!";
+    }
+    return name;
 }
 
 /* kernel of this interpreter */
-static void Eval_Cycle(scheme *sc, enum scheme_opcodes op) {
-  int count=0;
-  /*int old_op;*/
-  
-  sc->op = op;
-  for (;;) {
-    op_code_info *pcd=dispatch_table+sc->op;
-    if (pcd->name!=0) { /* if built-in function, check arguments */
-      char msg[512];
-      int ok=1;
-      int n=list_length(sc,sc->args);
-      
-      /* Check number of arguments */
-      if(n<pcd->min_arity) {
-	ok=0;
-	sprintf(msg,"%s: needs%s %d argument(s)",
-		pcd->name,
-		pcd->min_arity==pcd->max_arity?"":" at least",
-		pcd->min_arity);
-      }
-      if(ok && n>pcd->max_arity) {
-	ok=0;
-	sprintf(msg,"%s: needs%s %d argument(s)",
-		pcd->name,
-		pcd->min_arity==pcd->max_arity?"":" at most",
-		pcd->max_arity);
-      }
-      if(ok) {
-	if(pcd->arg_tests_encoding!=0) {
-	  int i=0;
-	  int j;
-	  const char *t=pcd->arg_tests_encoding;
-	  pointer arglist=sc->args;
-	  do {
-	    pointer arg=car(arglist);
-	    j=(int)t[0];
-	    if(j==TST_INPORT[0]) {
-	      if(!is_inport(arg)) break;
-	    } else if(j==TST_OUTPORT[0]) {
-	      if(!is_outport(arg)) break;
-            } else if(j==TST_LIST[0]) {
-              if(arg!=sc->NIL && !is_pair(arg)) break; 	      
-	    } else {
-	      if(!tests[j].fct(arg)) break;
-	    }
-
-	    if(t[1]!=0) {/* last test is replicated as necessary */
-	      t++;
-	    }
-	    arglist=cdr(arglist);
-	    i++;
-	  } while(i<n);
-	  if(i<n) {
-	    ok=0;
-	    sprintf(msg,"%s: argument %d must be: %s",
-		    pcd->name,
-		    i+1,
-		    tests[j].kind);
-	  }
-	}
-      }
-      if(!ok) {
-	if(_Error_1(sc,msg,0)==sc->NIL) {
-	  return;
-	}
-	pcd=dispatch_table+sc->op;
-      }
-    }
-    /*old_op=sc->op;*/
-    if (pcd->func(sc, (enum scheme_opcodes)sc->op) == sc->NIL) {
-      return;
-    }
-    if(sc->no_memory) {
-      fprintf(stderr,"No memory!\n");
-      return;
+static void
+Eval_Cycle(scheme* sc, enum scheme_opcodes op) {
+    int count = 0;
+    /*int old_op;*/
+
+    sc->op = op;
+    for (;;) {
+        op_code_info* pcd = dispatch_table + sc->op;
+        if (pcd->name != 0) { /* if built-in function, check arguments */
+            char msg[512];
+            int  ok = 1;
+            int  n  = list_length(sc, sc->args);
+
+            /* Check number of arguments */
+            if (n < pcd->min_arity) {
+                ok = 0;
+                sprintf(
+                    msg, "%s: needs%s %d argument(s)", pcd->name, pcd->min_arity == pcd->max_arity ? "" : " at least",
+                    pcd->min_arity
+                );
+            }
+            if (ok && n > pcd->max_arity) {
+                ok = 0;
+                sprintf(
+                    msg, "%s: needs%s %d argument(s)", pcd->name, pcd->min_arity == pcd->max_arity ? "" : " at most",
+                    pcd->max_arity
+                );
+            }
+            if (ok) {
+                if (pcd->arg_tests_encoding != 0) {
+                    int         i = 0;
+                    int         j;
+                    const char* t       = pcd->arg_tests_encoding;
+                    pointer     arglist = sc->args;
+                    do {
+                        pointer arg = car(arglist);
+                        j           = (int)t[0];
+                        if (j == TST_INPORT[0]) {
+                            if (!is_inport(arg))
+                                break;
+                        } else if (j == TST_OUTPORT[0]) {
+                            if (!is_outport(arg))
+                                break;
+                        } else if (j == TST_LIST[0]) {
+                            if (arg != sc->NIL && !is_pair(arg))
+                                break;
+                        } else {
+                            if (!tests[j].fct(arg))
+                                break;
+                        }
+
+                        if (t[1] != 0) { /* last test is replicated as necessary */
+                            t++;
+                        }
+                        arglist = cdr(arglist);
+                        i++;
+                    } while (i < n);
+                    if (i < n) {
+                        ok = 0;
+                        sprintf(msg, "%s: argument %d must be: %s", pcd->name, i + 1, tests[j].kind);
+                    }
+                }
+            }
+            if (!ok) {
+                if (_Error_1(sc, msg, 0) == sc->NIL) {
+                    return;
+                }
+                pcd = dispatch_table + sc->op;
+            }
+        }
+        /*old_op=sc->op;*/
+        if (pcd->func(sc, (enum scheme_opcodes)sc->op) == sc->NIL) {
+            return;
+        }
+        if (sc->no_memory) {
+            fprintf(stderr, "No memory!\n");
+            return;
+        }
+        count++;
     }
-    count++;
-  }
 }
 
 /* ========== Initialization of internal keywords ========== */
 
-static void assign_syntax(scheme *sc, char *name) {
-     pointer x;
+static void
+assign_syntax(scheme* sc, char* name) {
+    pointer x;
 
-     x = oblist_add_by_name(sc, name); 
-     typeflag(x) |= T_SYNTAX; 
+    x = oblist_add_by_name(sc, name);
+    typeflag(x) |= T_SYNTAX;
 }
 
-static void assign_proc(scheme *sc, enum scheme_opcodes op, char *name) {
-     pointer x, y;
+static void
+assign_proc(scheme* sc, enum scheme_opcodes op, char* name) {
+    pointer x, y;
 
-     x = mk_symbol(sc, name);
-     y = mk_proc(sc,op);
-     new_slot_in_env(sc, x, y); 
+    x = mk_symbol(sc, name);
+    y = mk_proc(sc, op);
+    new_slot_in_env(sc, x, y);
 }
 
-static pointer mk_proc(scheme *sc, enum scheme_opcodes op) {
-     pointer y;
+static pointer
+mk_proc(scheme* sc, enum scheme_opcodes op) {
+    pointer y;
 
-     y = get_cell(sc, sc->NIL, sc->NIL);
-     typeflag(y) = (T_PROC | T_ATOM);
-     ivalue_unchecked(y) = (long) op;
-     set_integer(y);
-     return y;
+    y                   = get_cell(sc, sc->NIL, sc->NIL);
+    typeflag(y)         = (T_PROC | T_ATOM);
+    ivalue_unchecked(y) = (long)op;
+    set_integer(y);
+    return y;
 }
 
 /* Hard-coded for the given keywords. Remember to rewrite if more are added! */
-static int syntaxnum(pointer p) {
-     const char *s=strvalue(car(p));
-     switch(strlength(car(p))) {
-     case 2:
-          if(s[0]=='i') return OP_IF0;        /* if */
-          else return OP_OR0;                 /* or */ 
-     case 3:
-          if(s[0]=='a') return OP_AND0;      /* and */
-          else return OP_LET0;               /* let */
-     case 4:
-          switch(s[3]) {
-          case 'e': return OP_CASE0;         /* case */
-          case 'd': return OP_COND0;         /* cond */
-          case '*': return OP_LET0AST;       /* let* */
-          default: return OP_SET0;           /* set! */          
-          }
-     case 5:
-          switch(s[2]) {
-          case 'g': return OP_BEGIN;         /* begin */
-          case 'l': return OP_DELAY;         /* delay */
-          case 'c': return OP_MACRO0;        /* macro */
-          default: return OP_QUOTE;          /* quote */
-          }
-     case 6:
-          switch(s[2]) {
-          case 'm': return OP_LAMBDA;        /* lambda */
-          case 'f': return OP_DEF0;          /* define */
-          default: return OP_LET0REC;        /* letrec */
-          }
-     default:
-          return OP_C0STREAM;                /* cons-stream */
-     }
+static int
+syntaxnum(pointer p) {
+    const char* s = strvalue(car(p));
+    switch (strlength(car(p))) {
+        case 2:
+            if (s[0] == 'i')
+                return OP_IF0; /* if */
+            else
+                return OP_OR0; /* or */
+        case 3:
+            if (s[0] == 'a')
+                return OP_AND0; /* and */
+            else
+                return OP_LET0; /* let */
+        case 4:
+            switch (s[3]) {
+                case 'e': return OP_CASE0;   /* case */
+                case 'd': return OP_COND0;   /* cond */
+                case '*': return OP_LET0AST; /* let* */
+                default: return OP_SET0;     /* set! */
+            }
+        case 5:
+            switch (s[2]) {
+                case 'g': return OP_BEGIN;  /* begin */
+                case 'l': return OP_DELAY;  /* delay */
+                case 'c': return OP_MACRO0; /* macro */
+                default: return OP_QUOTE;   /* quote */
+            }
+        case 6:
+            switch (s[2]) {
+                case 'm': return OP_LAMBDA; /* lambda */
+                case 'f': return OP_DEF0;   /* define */
+                default: return OP_LET0REC; /* letrec */
+            }
+        default: return OP_C0STREAM; /* cons-stream */
+    }
 }
 
 /* initialization of TinyScheme */
 #if USE_INTERFACE
-INTERFACE static pointer s_cons(scheme *sc, pointer a, pointer b) {
- return cons(sc,a,b);
-}
-INTERFACE static pointer s_immutable_cons(scheme *sc, pointer a, pointer b) {
- return immutable_cons(sc,a,b);
-}
-
-static struct scheme_interface vtbl ={
-  scheme_define,
-  s_cons,
-  s_immutable_cons,
-  mk_integer,
-  mk_real,
-  mk_symbol,
-  gensym,
-  mk_string,
-  mk_counted_string,
-  mk_character,
-  mk_vector,
-  mk_foreign_func,
-  putstr,
-  putcharacter,
-
-  is_string,
-  string_value,
-  is_number,
-  nvalue,
-  ivalue,
-  rvalue,
-  is_integer,
-  is_real,
-  is_character,
-  charvalue,
-  is_vector,
-  ivalue,
-  fill_vector,
-  vector_elem,
-  set_vector_elem,
-  is_port,
-  is_pair,
-  pair_car,
-  pair_cdr,
-  set_car,
-  set_cdr,
-
-  is_symbol,
-  symname,
-
-  is_syntax,
-  is_proc,
-  is_foreign,
-  syntaxname,
-  is_closure,
-  is_macro,
-  closure_code,
-  closure_env,
-
-  is_continuation,
-  is_promise,
-  is_environment,
-  is_immutable,
-  setimmutable,
-
-  scheme_load_file,
-  scheme_load_string
-};
-#endif
+INTERFACE static pointer
+s_cons(scheme* sc, pointer a, pointer b) {
+    return cons(sc, a, b);
+}
 
-scheme *scheme_init_new() {
-  scheme *sc=(scheme*)malloc(sizeof(scheme));
-  if(!scheme_init(sc)) {
-    free(sc);
-    return 0;
-  } else {
-    return sc;
-  }
+INTERFACE static pointer
+s_immutable_cons(scheme* sc, pointer a, pointer b) {
+    return immutable_cons(sc, a, b);
 }
 
-scheme *scheme_init_new_custom_alloc(func_alloc malloc, func_dealloc free) {
-  scheme *sc=(scheme*)malloc(sizeof(scheme));
-  if(!scheme_init_custom_alloc(sc,malloc,free)) {
-    free(sc);
-    return 0;
-  } else {
-    return sc;
-  }
+static struct scheme_interface vtbl = { scheme_define,
+                                        s_cons,
+                                        s_immutable_cons,
+                                        mk_integer,
+                                        mk_real,
+                                        mk_symbol,
+                                        gensym,
+                                        mk_string,
+                                        mk_counted_string,
+                                        mk_character,
+                                        mk_vector,
+                                        mk_foreign_func,
+                                        putstr,
+                                        putcharacter,
+
+                                        is_string,
+                                        string_value,
+                                        is_number,
+                                        nvalue,
+                                        ivalue,
+                                        rvalue,
+                                        is_integer,
+                                        is_real,
+                                        is_character,
+                                        charvalue,
+                                        is_vector,
+                                        ivalue,
+                                        fill_vector,
+                                        vector_elem,
+                                        set_vector_elem,
+                                        is_port,
+                                        is_pair,
+                                        pair_car,
+                                        pair_cdr,
+                                        set_car,
+                                        set_cdr,
+
+                                        is_symbol,
+                                        symname,
+
+                                        is_syntax,
+                                        is_proc,
+                                        is_foreign,
+                                        syntaxname,
+                                        is_closure,
+                                        is_macro,
+                                        closure_code,
+                                        closure_env,
+
+                                        is_continuation,
+                                        is_promise,
+                                        is_environment,
+                                        is_immutable,
+                                        setimmutable,
+
+                                        scheme_load_file,
+                                        scheme_load_string };
+#endif
+
+scheme*
+scheme_init_new() {
+    scheme* sc = (scheme*)malloc(sizeof(scheme));
+    if (!scheme_init(sc)) {
+        free(sc);
+        return 0;
+    } else {
+        return sc;
+    }
 }
 
+scheme*
+scheme_init_new_custom_alloc(func_alloc malloc, func_dealloc free) {
+    scheme* sc = (scheme*)malloc(sizeof(scheme));
+    if (!scheme_init_custom_alloc(sc, malloc, free)) {
+        free(sc);
+        return 0;
+    } else {
+        return sc;
+    }
+}
 
-int scheme_init(scheme *sc) {
- return scheme_init_custom_alloc(sc,malloc,free);
+int
+scheme_init(scheme* sc) {
+    return scheme_init_custom_alloc(sc, malloc, free);
 }
 
-int scheme_init_custom_alloc(scheme *sc, func_alloc malloc, func_dealloc free) {
-  int i, n=sizeof(dispatch_table)/sizeof(dispatch_table[0]);
-  pointer x;
+int
+scheme_init_custom_alloc(scheme* sc, func_alloc malloc, func_dealloc free) {
+    int     i, n = sizeof(dispatch_table) / sizeof(dispatch_table[0]);
+    pointer x;
 
-  num_zero.is_fixnum=1;
-  num_zero.value.ivalue=0;
-  num_one.is_fixnum=1;
-  num_one.value.ivalue=1;
+    num_zero.is_fixnum    = 1;
+    num_zero.value.ivalue = 0;
+    num_one.is_fixnum     = 1;
+    num_one.value.ivalue  = 1;
 
 #if USE_INTERFACE
-  sc->vptr=&vtbl;
+    sc->vptr = &vtbl;
 #endif
-  sc->gensym_cnt=0;
-  sc->malloc=malloc;
-  sc->free=free;
-  sc->last_cell_seg = -1;
-  sc->sink = &sc->_sink;
-  sc->NIL = &sc->_NIL;
-  sc->T = &sc->_HASHT;
-  sc->F = &sc->_HASHF;
-  sc->EOF_OBJ=&sc->_EOF_OBJ;
-  sc->free_cell = &sc->_NIL;
-  sc->fcells = 0;
-  sc->no_memory=0;
-  sc->inport=sc->NIL;
-  sc->outport=sc->NIL;
-  sc->save_inport=sc->NIL;
-  sc->loadport=sc->NIL;
-  sc->nesting=0;
-  sc->interactive_repl=0;
-  
-  if (alloc_cellseg(sc,FIRST_CELLSEGS) != FIRST_CELLSEGS) {
-    sc->no_memory=1;
-    return 0;
-  }
-  sc->gc_verbose = 0;
-  dump_stack_initialize(sc); 
-  sc->code = sc->NIL;
-  sc->tracing=0;
-  
-  /* init sc->NIL */
-  typeflag(sc->NIL) = (T_ATOM | MARK);
-  car(sc->NIL) = cdr(sc->NIL) = sc->NIL;
-  /* init T */
-  typeflag(sc->T) = (T_ATOM | MARK);
-  car(sc->T) = cdr(sc->T) = sc->T;
-  /* init F */
-  typeflag(sc->F) = (T_ATOM | MARK);
-  car(sc->F) = cdr(sc->F) = sc->F;
-  sc->oblist = oblist_initial_value(sc); 
-  /* init global_env */
-  new_frame_in_env(sc, sc->NIL); 
-  sc->global_env = sc->envir; 
-  /* init else */
-  x = mk_symbol(sc,"else");
-  new_slot_in_env(sc, x, sc->T); 
-
-  assign_syntax(sc, "lambda");
-  assign_syntax(sc, "quote");
-  assign_syntax(sc, "define");
-  assign_syntax(sc, "if");
-  assign_syntax(sc, "begin");
-  assign_syntax(sc, "set!");
-  assign_syntax(sc, "let");
-  assign_syntax(sc, "let*");
-  assign_syntax(sc, "letrec");
-  assign_syntax(sc, "cond");
-  assign_syntax(sc, "delay");
-  assign_syntax(sc, "and");
-  assign_syntax(sc, "or");
-  assign_syntax(sc, "cons-stream");
-  assign_syntax(sc, "macro");
-  assign_syntax(sc, "case");
-  
-  for(i=0; i<n; i++) {
-    if(dispatch_table[i].name!=0) {
-      assign_proc(sc, (enum scheme_opcodes)i, dispatch_table[i].name);
+    sc->gensym_cnt       = 0;
+    sc->malloc           = malloc;
+    sc->free             = free;
+    sc->last_cell_seg    = -1;
+    sc->sink             = &sc->_sink;
+    sc->NIL              = &sc->_NIL;
+    sc->T                = &sc->_HASHT;
+    sc->F                = &sc->_HASHF;
+    sc->EOF_OBJ          = &sc->_EOF_OBJ;
+    sc->free_cell        = &sc->_NIL;
+    sc->fcells           = 0;
+    sc->no_memory        = 0;
+    sc->inport           = sc->NIL;
+    sc->outport          = sc->NIL;
+    sc->save_inport      = sc->NIL;
+    sc->loadport         = sc->NIL;
+    sc->nesting          = 0;
+    sc->interactive_repl = 0;
+
+    if (alloc_cellseg(sc, FIRST_CELLSEGS) != FIRST_CELLSEGS) {
+        sc->no_memory = 1;
+        return 0;
+    }
+    sc->gc_verbose = 0;
+    dump_stack_initialize(sc);
+    sc->code    = sc->NIL;
+    sc->tracing = 0;
+
+    /* init sc->NIL */
+    typeflag(sc->NIL) = (T_ATOM | MARK);
+    car(sc->NIL) = cdr(sc->NIL) = sc->NIL;
+    /* init T */
+    typeflag(sc->T) = (T_ATOM | MARK);
+    car(sc->T) = cdr(sc->T) = sc->T;
+    /* init F */
+    typeflag(sc->F) = (T_ATOM | MARK);
+    car(sc->F) = cdr(sc->F) = sc->F;
+    sc->oblist              = oblist_initial_value(sc);
+    /* init global_env */
+    new_frame_in_env(sc, sc->NIL);
+    sc->global_env = sc->envir;
+    /* init else */
+    x = mk_symbol(sc, "else");
+    new_slot_in_env(sc, x, sc->T);
+
+    assign_syntax(sc, "lambda");
+    assign_syntax(sc, "quote");
+    assign_syntax(sc, "define");
+    assign_syntax(sc, "if");
+    assign_syntax(sc, "begin");
+    assign_syntax(sc, "set!");
+    assign_syntax(sc, "let");
+    assign_syntax(sc, "let*");
+    assign_syntax(sc, "letrec");
+    assign_syntax(sc, "cond");
+    assign_syntax(sc, "delay");
+    assign_syntax(sc, "and");
+    assign_syntax(sc, "or");
+    assign_syntax(sc, "cons-stream");
+    assign_syntax(sc, "macro");
+    assign_syntax(sc, "case");
+
+    for (i = 0; i < n; i++) {
+        if (dispatch_table[i].name != 0) {
+            assign_proc(sc, (enum scheme_opcodes)i, dispatch_table[i].name);
+        }
     }
-  }
 
-  /* initialization of global pointers to special symbols */
-  sc->LAMBDA = mk_symbol(sc, "lambda");
-  sc->QUOTE = mk_symbol(sc, "quote");
-  sc->QQUOTE = mk_symbol(sc, "quasiquote");
-  sc->UNQUOTE = mk_symbol(sc, "unquote");
-  sc->UNQUOTESP = mk_symbol(sc, "unquote-splicing");
-  sc->FEED_TO = mk_symbol(sc, "=>");
-  sc->COLON_HOOK = mk_symbol(sc,"*colon-hook*");
-  sc->ERROR_HOOK = mk_symbol(sc, "*error-hook*");
-  sc->SHARP_HOOK = mk_symbol(sc, "*sharp-hook*");
+    /* initialization of global pointers to special symbols */
+    sc->LAMBDA     = mk_symbol(sc, "lambda");
+    sc->QUOTE      = mk_symbol(sc, "quote");
+    sc->QQUOTE     = mk_symbol(sc, "quasiquote");
+    sc->UNQUOTE    = mk_symbol(sc, "unquote");
+    sc->UNQUOTESP  = mk_symbol(sc, "unquote-splicing");
+    sc->FEED_TO    = mk_symbol(sc, "=>");
+    sc->COLON_HOOK = mk_symbol(sc, "*colon-hook*");
+    sc->ERROR_HOOK = mk_symbol(sc, "*error-hook*");
+    sc->SHARP_HOOK = mk_symbol(sc, "*sharp-hook*");
+
+    return !sc->no_memory;
+}
 
-  return !sc->no_memory;
+void
+scheme_set_input_port_file(scheme* sc, FILE* fin) {
+    sc->inport = port_from_file(sc, fin, port_input);
 }
 
-void scheme_set_input_port_file(scheme *sc, FILE *fin) {
-  sc->inport=port_from_file(sc,fin,port_input);
+void
+scheme_set_input_port_string(scheme* sc, char* start, char* past_the_end) {
+    sc->inport = port_from_string(sc, start, past_the_end, port_input);
 }
 
-void scheme_set_input_port_string(scheme *sc, char *start, char *past_the_end) {
-  sc->inport=port_from_string(sc,start,past_the_end,port_input);
+void
+scheme_set_output_port_file(scheme* sc, FILE* fout) {
+    sc->outport = port_from_file(sc, fout, port_output);
 }
 
-void scheme_set_output_port_file(scheme *sc, FILE *fout) {
-  sc->outport=port_from_file(sc,fout,port_output);
+void
+scheme_set_output_port_string(scheme* sc, char* start, char* past_the_end) {
+    sc->outport = port_from_string(sc, start, past_the_end, port_output);
 }
 
-void scheme_set_output_port_string(scheme *sc, char *start, char *past_the_end) {
-  sc->outport=port_from_string(sc,start,past_the_end,port_output);
+void
+scheme_set_external_data(scheme* sc, void* p) {
+    sc->ext_data = p;
 }
 
-void scheme_set_external_data(scheme *sc, void *p) {
- sc->ext_data=p;
+void
+scheme_deinit(scheme* sc) {
+    int i;
+
+    sc->oblist     = sc->NIL;
+    sc->global_env = sc->NIL;
+    dump_stack_free(sc);
+    sc->envir = sc->NIL;
+    sc->code  = sc->NIL;
+    sc->args  = sc->NIL;
+    sc->value = sc->NIL;
+    if (is_port(sc->inport)) {
+        typeflag(sc->inport) = T_ATOM;
+    }
+    sc->inport  = sc->NIL;
+    sc->outport = sc->NIL;
+    if (is_port(sc->save_inport)) {
+        typeflag(sc->save_inport) = T_ATOM;
+    }
+    sc->save_inport = sc->NIL;
+    if (is_port(sc->loadport)) {
+        typeflag(sc->loadport) = T_ATOM;
+    }
+    sc->loadport   = sc->NIL;
+    sc->gc_verbose = 0;
+    gc(sc, sc->NIL, sc->NIL);
+
+    for (i = 0; i <= sc->last_cell_seg; i++) {
+        sc->free(sc->alloc_seg[i]);
+    }
 }
 
-void scheme_deinit(scheme *sc) {
-  int i;
+void
+scheme_load_file(scheme* sc, FILE* fin) {
+    dump_stack_reset(sc);
+    sc->envir                        = sc->global_env;
+    sc->file_i                       = 0;
+    sc->load_stack[0].kind           = port_input | port_file;
+    sc->load_stack[0].rep.stdio.file = fin;
+    sc->loadport                     = mk_port(sc, sc->load_stack);
+    sc->retcode                      = 0;
+    if (fin == stdin) {
+        sc->interactive_repl = 1;
+    }
+    sc->inport = sc->loadport;
+    Eval_Cycle(sc, OP_T0LVL);
+    typeflag(sc->loadport) = T_ATOM;
+    if (sc->retcode == 0) {
+        sc->retcode = sc->nesting != 0;
+    }
+}
 
-  sc->oblist=sc->NIL;
-  sc->global_env=sc->NIL;
-  dump_stack_free(sc); 
-  sc->envir=sc->NIL;
-  sc->code=sc->NIL;
-  sc->args=sc->NIL;
-  sc->value=sc->NIL;
-  if(is_port(sc->inport)) {
-    typeflag(sc->inport) = T_ATOM;
-  }
-  sc->inport=sc->NIL;
-  sc->outport=sc->NIL;
-  if(is_port(sc->save_inport)) {
-    typeflag(sc->save_inport) = T_ATOM;
-  }
-  sc->save_inport=sc->NIL;
-  if(is_port(sc->loadport)) {
+void
+scheme_load_string(scheme* sc, const char* cmd) {
+    dump_stack_reset(sc);
+    sc->envir                                 = sc->global_env;
+    sc->file_i                                = 0;
+    sc->load_stack[0].kind                    = port_input | port_string;
+    sc->load_stack[0].rep.string.start        = (char*)cmd; /* This func respects const */
+    sc->load_stack[0].rep.string.past_the_end = (char*)cmd + strlen(cmd);
+    sc->load_stack[0].rep.string.curr         = (char*)cmd;
+    sc->loadport                              = mk_port(sc, sc->load_stack);
+    sc->retcode                               = 0;
+    sc->interactive_repl                      = 0;
+    sc->inport                                = sc->loadport;
+    Eval_Cycle(sc, OP_T0LVL);
     typeflag(sc->loadport) = T_ATOM;
-  }
-  sc->loadport=sc->NIL;
-  sc->gc_verbose=0;
-  gc(sc,sc->NIL,sc->NIL);
-
-  for(i=0; i<=sc->last_cell_seg; i++) {
-    sc->free(sc->alloc_seg[i]);
-  }
-}
-
-void scheme_load_file(scheme *sc, FILE *fin) {
-  dump_stack_reset(sc); 
-  sc->envir = sc->global_env;
-  sc->file_i=0;
-  sc->load_stack[0].kind=port_input|port_file;
-  sc->load_stack[0].rep.stdio.file=fin;
-  sc->loadport=mk_port(sc,sc->load_stack);
-  sc->retcode=0;
-  if(fin==stdin) {
-    sc->interactive_repl=1;
-  }
-  sc->inport=sc->loadport;
-  Eval_Cycle(sc, OP_T0LVL);
-  typeflag(sc->loadport)=T_ATOM;
-  if(sc->retcode==0) {
-    sc->retcode=sc->nesting!=0;
-  }
-}
-
-void scheme_load_string(scheme *sc, const char *cmd) {
-  dump_stack_reset(sc); 
-  sc->envir = sc->global_env;
-  sc->file_i=0;
-  sc->load_stack[0].kind=port_input|port_string;
-  sc->load_stack[0].rep.string.start=(char*)cmd; /* This func respects const */
-  sc->load_stack[0].rep.string.past_the_end=(char*)cmd+strlen(cmd);
-  sc->load_stack[0].rep.string.curr=(char*)cmd;
-  sc->loadport=mk_port(sc,sc->load_stack);
-  sc->retcode=0;
-  sc->interactive_repl=0;
-  sc->inport=sc->loadport;
-  Eval_Cycle(sc, OP_T0LVL);
-  typeflag(sc->loadport)=T_ATOM;
-  if(sc->retcode==0) {
-    sc->retcode=sc->nesting!=0;
-  }
-}
-
-void scheme_define(scheme *sc, pointer envir, pointer symbol, pointer value) {
-     pointer x;
-
-     x=find_slot_in_env(sc,envir,symbol,0);
-     if (x != sc->NIL) { 
-          set_slot_in_env(sc, x, value); 
-     } else { 
-          new_slot_spec_in_env(sc, envir, symbol, value); 
-     } 
+    if (sc->retcode == 0) {
+        sc->retcode = sc->nesting != 0;
+    }
+}
+
+void
+scheme_define(scheme* sc, pointer envir, pointer symbol, pointer value) {
+    pointer x;
+
+    x = find_slot_in_env(sc, envir, symbol, 0);
+    if (x != sc->NIL) {
+        set_slot_in_env(sc, x, value);
+    } else {
+        new_slot_spec_in_env(sc, envir, symbol, value);
+    }
 }
 
 #if !STANDALONE
-void scheme_apply0(scheme *sc, const char *procname) {
-     pointer carx=mk_symbol(sc,procname);
-     pointer cdrx=sc->NIL;
-
-     dump_stack_reset(sc); 
-     sc->envir = sc->global_env;
-     sc->code = cons(sc,carx,cdrx);
-     sc->interactive_repl=0;
-     sc->retcode=0;
-     Eval_Cycle(sc,OP_EVAL);
-     }
-
-void scheme_call(scheme *sc, pointer func, pointer args) { 
-   dump_stack_reset(sc); 
-   sc->envir = sc->global_env; 
-   sc->args = args; 
-   sc->code = func; 
-   sc->interactive_repl =0; 
-   sc->retcode = 0; 
-   Eval_Cycle(sc, OP_APPLY); 
-} 
+void
+scheme_apply0(scheme* sc, const char* procname) {
+    pointer carx = mk_symbol(sc, procname);
+    pointer cdrx = sc->NIL;
+
+    dump_stack_reset(sc);
+    sc->envir            = sc->global_env;
+    sc->code             = cons(sc, carx, cdrx);
+    sc->interactive_repl = 0;
+    sc->retcode          = 0;
+    Eval_Cycle(sc, OP_EVAL);
+}
+
+void
+scheme_call(scheme* sc, pointer func, pointer args) {
+    dump_stack_reset(sc);
+    sc->envir            = sc->global_env;
+    sc->args             = args;
+    sc->code             = func;
+    sc->interactive_repl = 0;
+    sc->retcode          = 0;
+    Eval_Cycle(sc, OP_APPLY);
+}
 #endif
 
 /* ========== Main ========== */
@@ -4389,95 +4530,100 @@ void scheme_call(scheme *sc, pointer func, pointer args) {
 #if STANDALONE
 
 #ifdef macintosh
-int main()
-{
-     extern MacTS_main(int argc, char **argv);
-     char**    argv;
-     int argc = ccommand(&argv);
-     MacTS_main(argc,argv);
-     return 0;
-}
-int MacTS_main(int argc, char **argv) {
+int
+main() {
+    extern MacTS_main(int argc, char** argv);
+    char** argv;
+    int    argc = ccommand(&argv);
+    MacTS_main(argc, argv);
+    return 0;
+}
+int
+MacTS_main(int argc, char** argv) {
 #else
-int main(int argc, char **argv) {
+int
+main(int argc, char** argv) {
 #endif
-  scheme sc;
-  FILE *fin = 0;
-  char *file_name=InitFile;
-  int retcode;
-  int isfile=1;
-  
-  if(argc==1) {
-    printf(banner);
-  }
-  if(argc==2 && strcmp(argv[1],"-?")==0) {
-    printf("Usage: %s [-? | <file1> <file2> ... | -1 <file> <arg1> <arg2> ...]\n\tUse - as filename for stdin.\n",argv[0]);
-    return 1;
-  }
-  if(!scheme_init(&sc)) {
-    fprintf(stderr,"Could not initialize!\n");
-    return 2;
-  }
-  scheme_set_input_port_file(&sc, stdin);
-  scheme_set_output_port_file(&sc, stdout);
+    scheme sc;
+    FILE*  fin       = 0;
+    char*  file_name = InitFile;
+    int    retcode;
+    int    isfile = 1;
+
+    if (argc == 1) {
+        printf(banner);
+    }
+    if (argc == 2 && strcmp(argv[1], "-?") == 0) {
+        printf(
+            "Usage: %s [-? | <file1> <file2> ... | -1 <file> <arg1> <arg2> ...]\n\tUse - as filename for stdin.\n",
+            argv[0]
+        );
+        return 1;
+    }
+    if (!scheme_init(&sc)) {
+        fprintf(stderr, "Could not initialize!\n");
+        return 2;
+    }
+    scheme_set_input_port_file(&sc, stdin);
+    scheme_set_output_port_file(&sc, stdout);
 #if USE_DL
-  scheme_define(&sc,sc.global_env,mk_symbol(&sc,"load-extension"),mk_foreign_func(&sc, scm_load_ext));
+    scheme_define(&sc, sc.global_env, mk_symbol(&sc, "load-extension"), mk_foreign_func(&sc, scm_load_ext));
 #endif
-  argv++;
-  if(access(file_name,0)!=0) {
-    char *p=getenv("TINYSCHEMEINIT");
-    if(p!=0) {
-      file_name=p;
+    argv++;
+    if (access(file_name, 0) != 0) {
+        char* p = getenv("TINYSCHEMEINIT");
+        if (p != 0) {
+            file_name = p;
+        }
     }
-  }
-  do {
-    if(strcmp(file_name,"-")==0) {
-      fin=stdin;
-    } else if(strcmp(file_name,"-1")==0 || strcmp(file_name,"-c")==0) {
-      pointer args=sc.NIL;
-      isfile=file_name[1]=='1';
-      file_name=*argv++;
-      if(strcmp(file_name,"-")==0) {
-	fin=stdin;
-      } else if(isfile) {
-	fin=fopen(file_name,"r");
-      }
-      for(;*argv;argv++) {
-	pointer value=mk_string(&sc,*argv);
-	args=cons(&sc,value,args);
-      }
-      args=reverse_in_place(&sc,sc.NIL,args);
-      scheme_define(&sc,sc.global_env,mk_symbol(&sc,"*args*"),args);
+    do {
+        if (strcmp(file_name, "-") == 0) {
+            fin = stdin;
+        } else if (strcmp(file_name, "-1") == 0 || strcmp(file_name, "-c") == 0) {
+            pointer args = sc.NIL;
+            isfile       = file_name[1] == '1';
+            file_name    = *argv++;
+            if (strcmp(file_name, "-") == 0) {
+                fin = stdin;
+            } else if (isfile) {
+                fin = fopen(file_name, "r");
+            }
+            for (; *argv; argv++) {
+                pointer value = mk_string(&sc, *argv);
+                args          = cons(&sc, value, args);
+            }
+            args = reverse_in_place(&sc, sc.NIL, args);
+            scheme_define(&sc, sc.global_env, mk_symbol(&sc, "*args*"), args);
 
-    } else {
-      fin=fopen(file_name,"r");
-    }
-    if(isfile && fin==0) {
-      fprintf(stderr,"Could not open file %s\n",file_name);
-    } else {
-      if(isfile) {
-        scheme_load_file(&sc,fin);
-      } else {
-        scheme_load_string(&sc,file_name);
-      }
-      if(!isfile || fin!=stdin) {
-	if(sc.retcode!=0) {
-	  fprintf(stderr,"Errors encountered reading %s\n",file_name);
-	}
-	if(isfile) {
-	  fclose(fin);
-	}
-      }
+        } else {
+            fin = fopen(file_name, "r");
+        }
+        if (isfile && fin == 0) {
+            fprintf(stderr, "Could not open file %s\n", file_name);
+        } else {
+            if (isfile) {
+                scheme_load_file(&sc, fin);
+            } else {
+                scheme_load_string(&sc, file_name);
+            }
+            if (!isfile || fin != stdin) {
+                if (sc.retcode != 0) {
+                    fprintf(stderr, "Errors encountered reading %s\n", file_name);
+                }
+                if (isfile) {
+                    fclose(fin);
+                }
+            }
+        }
+        file_name = *argv++;
+    } while (file_name != 0);
+    if (argc == 1) {
+        scheme_load_file(&sc, stdin);
     }
-    file_name=*argv++;
-  } while(file_name!=0);
-  if(argc==1) {
-    scheme_load_file(&sc,stdin);
-  }
-  retcode=sc.retcode;
-  scheme_deinit(&sc);
-  
-  return retcode;
+    retcode = sc.retcode;
+    scheme_deinit(&sc);
+
+    return retcode;
 }
 
 #endif
diff --git a/src/scheme.h b/src/scheme.h
index 869d950..821dbfc 100644
--- a/src/scheme.h
+++ b/src/scheme.h
@@ -17,41 +17,38 @@
 /*
  * Default values for #define'd symbols
  */
-#ifndef STANDALONE       /* If used as standalone interpreter */
-# define STANDALONE 1
+#ifndef STANDALONE /* If used as standalone interpreter */
+#define STANDALONE 1
 #endif
 
-
 #if !defined(_MSC_VER) && !defined(__MINGW32__)
-# define USE_STRCASECMP 1 
-# define USE_STRLWR 1 
-# define SCHEME_EXPORT
-#else 
-# define USE_STRCASECMP 0 
-# define USE_STRLWR 0 
-# if defined(__MINGW32__)
-#  define SCHEME_EXPORT
-# else
-#  ifdef _SCHEME_SOURCE
-#   define SCHEME_EXPORT __declspec(dllexport)
-#  else
-#   define SCHEME_EXPORT __declspec(dllimport)
-#  endif
-# endif
+#define USE_STRCASECMP 1
+#define USE_STRLWR     1
+#define SCHEME_EXPORT
+#else
+#define USE_STRCASECMP 0
+#define USE_STRLWR     0
+#if defined(__MINGW32__)
+#define SCHEME_EXPORT
+#else
+#ifdef _SCHEME_SOURCE
+#define SCHEME_EXPORT __declspec(dllexport)
+#else
+#define SCHEME_EXPORT __declspec(dllimport)
+#endif
+#endif
 #endif
-
-
 
 #if USE_NO_FEATURES
-# define USE_MATH 0
-# define USE_CHAR_CLASSIFIERS 0
-# define USE_ASCII_NAMES 0
-# define USE_STRING_PORTS 0
-# define USE_ERROR_HOOK 0
-# define USE_TRACING 0
-# define USE_COLON_HOOK 0
-# define USE_DL 0
-# define USE_PLIST 0
+#define USE_MATH             0
+#define USE_CHAR_CLASSIFIERS 0
+#define USE_ASCII_NAMES      0
+#define USE_STRING_PORTS     0
+#define USE_ERROR_HOOK       0
+#define USE_TRACING          0
+#define USE_COLON_HOOK       0
+#define USE_DL               0
+#define USE_PLIST            0
 #endif
 
 /*
@@ -61,169 +58,167 @@
 #define USE_SCHEME_STACK
 
 #if USE_DL
-# define USE_INTERFACE 1
+#define USE_INTERFACE 1
 #endif
 
-
-#ifndef USE_MATH         /* If math support is needed */
-# define USE_MATH 1
+#ifndef USE_MATH /* If math support is needed */
+#define USE_MATH 1
 #endif
 
-#ifndef USE_CHAR_CLASSIFIERS  /* If char classifiers are needed */
-# define USE_CHAR_CLASSIFIERS 1
+#ifndef USE_CHAR_CLASSIFIERS /* If char classifiers are needed */
+#define USE_CHAR_CLASSIFIERS 1
 #endif
 
-#ifndef USE_ASCII_NAMES  /* If extended escaped characters are needed */
-# define USE_ASCII_NAMES 1
+#ifndef USE_ASCII_NAMES /* If extended escaped characters are needed */
+#define USE_ASCII_NAMES 1
 #endif
 
-#ifndef USE_STRING_PORTS      /* Enable string ports */
-# define USE_STRING_PORTS 1
+#ifndef USE_STRING_PORTS /* Enable string ports */
+#define USE_STRING_PORTS 1
 #endif
 
 #ifndef USE_TRACING
-# define USE_TRACING 1
+#define USE_TRACING 1
 #endif
 
 #ifndef USE_PLIST
-# define USE_PLIST 0
+#define USE_PLIST 0
 #endif
 
 /* To force system errors through user-defined error handling (see *error-hook*) */
 #ifndef USE_ERROR_HOOK
-# define USE_ERROR_HOOK 1
+#define USE_ERROR_HOOK 1
 #endif
 
-#ifndef USE_COLON_HOOK   /* Enable qualified qualifier */
-# define USE_COLON_HOOK 1
+#ifndef USE_COLON_HOOK /* Enable qualified qualifier */
+#define USE_COLON_HOOK 1
 #endif
 
-#ifndef USE_STRCASECMP   /* stricmp for Unix */
-# define USE_STRCASECMP 0
+#ifndef USE_STRCASECMP /* stricmp for Unix */
+#define USE_STRCASECMP 0
 #endif
 
 #ifndef USE_STRLWR
-# define USE_STRLWR 1
+#define USE_STRLWR 1
 #endif
 
-#ifndef STDIO_ADDS_CR    /* Define if DOS/Windows */
-# define STDIO_ADDS_CR 0
+#ifndef STDIO_ADDS_CR /* Define if DOS/Windows */
+#define STDIO_ADDS_CR 0
 #endif
 
 #ifndef INLINE
-# define INLINE
+#define INLINE
 #endif
 
 #ifndef USE_INTERFACE
-# define USE_INTERFACE 0
+#define USE_INTERFACE 0
 #endif
 
 typedef struct scheme scheme;
-typedef struct cell *pointer;
+typedef struct cell*  pointer;
 
-typedef void * (*func_alloc)(size_t);
-typedef void (*func_dealloc)(void *);
+typedef void* (*func_alloc)(size_t);
+typedef void (*func_dealloc)(void*);
 
 /* num, for generic arithmetic */
 typedef struct num {
-     char is_fixnum;
-     union {
-          long ivalue;
-          double rvalue;
-     } value;
-} num;
+    char is_fixnum;
 
-SCHEME_EXPORT scheme *scheme_init_new();
-SCHEME_EXPORT scheme *scheme_init_new_custom_alloc(func_alloc malloc, func_dealloc free);
-SCHEME_EXPORT int scheme_init(scheme *sc);
-SCHEME_EXPORT int scheme_init_custom_alloc(scheme *sc, func_alloc, func_dealloc);
-SCHEME_EXPORT void scheme_deinit(scheme *sc);
-void scheme_set_input_port_file(scheme *sc, FILE *fin);
-void scheme_set_input_port_string(scheme *sc, char *start, char *past_the_end);
-SCHEME_EXPORT void scheme_set_output_port_file(scheme *sc, FILE *fin);
-void scheme_set_output_port_string(scheme *sc, char *start, char *past_the_end);
-SCHEME_EXPORT void scheme_load_file(scheme *sc, FILE *fin);
-SCHEME_EXPORT void scheme_load_string(scheme *sc, const char *cmd);
-void scheme_apply0(scheme *sc, const char *procname);
-SCHEME_EXPORT pointer scheme_apply1(scheme *sc, const char *procname, pointer);
-void scheme_set_external_data(scheme *sc, void *p);
-SCHEME_EXPORT void scheme_define(scheme *sc, pointer env, pointer symbol, pointer value);
-
-typedef pointer (*foreign_func)(scheme *, pointer);
-
-pointer _cons(scheme *sc, pointer a, pointer b, int immutable);
-pointer mk_integer(scheme *sc, long num);
-pointer mk_real(scheme *sc, double num);
-pointer mk_symbol(scheme *sc, const char *name);
-pointer gensym(scheme *sc);
-pointer mk_string(scheme *sc, const char *str);
-pointer mk_counted_string(scheme *sc, const char *str, int len);
-pointer mk_character(scheme *sc, int c);
-pointer mk_foreign_func(scheme *sc, foreign_func f);
-void putstr(scheme *sc, const char *s);
+    union {
+        long   ivalue;
+        double rvalue;
+    } value;
+} num;
 
+SCHEME_EXPORT scheme* scheme_init_new();
+SCHEME_EXPORT scheme* scheme_init_new_custom_alloc(func_alloc malloc, func_dealloc free);
+SCHEME_EXPORT int     scheme_init(scheme* sc);
+SCHEME_EXPORT int     scheme_init_custom_alloc(scheme* sc, func_alloc, func_dealloc);
+SCHEME_EXPORT void    scheme_deinit(scheme* sc);
+void                  scheme_set_input_port_file(scheme* sc, FILE* fin);
+void                  scheme_set_input_port_string(scheme* sc, char* start, char* past_the_end);
+SCHEME_EXPORT void    scheme_set_output_port_file(scheme* sc, FILE* fin);
+void                  scheme_set_output_port_string(scheme* sc, char* start, char* past_the_end);
+SCHEME_EXPORT void    scheme_load_file(scheme* sc, FILE* fin);
+SCHEME_EXPORT void    scheme_load_string(scheme* sc, const char* cmd);
+void                  scheme_apply0(scheme* sc, const char* procname);
+SCHEME_EXPORT pointer scheme_apply1(scheme* sc, const char* procname, pointer);
+void                  scheme_set_external_data(scheme* sc, void* p);
+SCHEME_EXPORT void    scheme_define(scheme* sc, pointer env, pointer symbol, pointer value);
+
+typedef pointer (*foreign_func)(scheme*, pointer);
+
+pointer _cons(scheme* sc, pointer a, pointer b, int immutable);
+pointer mk_integer(scheme* sc, long num);
+pointer mk_real(scheme* sc, double num);
+pointer mk_symbol(scheme* sc, const char* name);
+pointer gensym(scheme* sc);
+pointer mk_string(scheme* sc, const char* str);
+pointer mk_counted_string(scheme* sc, const char* str, int len);
+pointer mk_character(scheme* sc, int c);
+pointer mk_foreign_func(scheme* sc, foreign_func f);
+void    putstr(scheme* sc, const char* s);
 
 #if USE_INTERFACE
 struct scheme_interface {
-  void (*scheme_define)(scheme *sc, pointer env, pointer symbol, pointer value);
-  pointer (*cons)(scheme *sc, pointer a, pointer b);
-  pointer (*immutable_cons)(scheme *sc, pointer a, pointer b);
-  pointer (*mk_integer)(scheme *sc, long num);
-  pointer (*mk_real)(scheme *sc, double num);
-  pointer (*mk_symbol)(scheme *sc, const char *name);
-  pointer (*gensym)(scheme *sc);
-  pointer (*mk_string)(scheme *sc, const char *str);
-  pointer (*mk_counted_string)(scheme *sc, const char *str, int len);
-  pointer (*mk_character)(scheme *sc, int c);
-  pointer (*mk_vector)(scheme *sc, int len);
-  pointer (*mk_foreign_func)(scheme *sc, foreign_func f);
-  void (*putstr)(scheme *sc, const char *s);
-  void (*putcharacter)(scheme *sc, int c);
-  
-  int (*is_string)(pointer p);
-  char *(*string_value)(pointer p);
-  int (*is_number)(pointer p);
-  num (*nvalue)(pointer p);
-  long (*ivalue)(pointer p);
-  double (*rvalue)(pointer p);
-  int (*is_integer)(pointer p);
-  int (*is_real)(pointer p);
-  int (*is_character)(pointer p);
-  long (*charvalue)(pointer p);
-  int (*is_vector)(pointer p);
-  long (*vector_length)(pointer vec);
-  void (*fill_vector)(pointer vec, pointer elem);
-  pointer (*vector_elem)(pointer vec, int ielem);
-  pointer (*set_vector_elem)(pointer vec, int ielem, pointer newel);
-  int (*is_port)(pointer p);
-  
-  int (*is_pair)(pointer p);
-  pointer (*pair_car)(pointer p);
-  pointer (*pair_cdr)(pointer p);
-  pointer (*set_car)(pointer p, pointer q);
-  pointer (*set_cdr)(pointer p, pointer q);
-
-  int (*is_symbol)(pointer p);
-  char *(*symname)(pointer p);
-  
-  int (*is_syntax)(pointer p);
-  int (*is_proc)(pointer p);
-  int (*is_foreign)(pointer p);
-  char *(*syntaxname)(pointer p);
-  int (*is_closure)(pointer p);
-  int (*is_macro)(pointer p);
-  pointer (*closure_code)(pointer p);
-  pointer (*closure_env)(pointer p);
-
-  int (*is_continuation)(pointer p);
-  int (*is_promise)(pointer p);
-  int (*is_environment)(pointer p);
-  int (*is_immutable)(pointer p);
-  void (*setimmutable)(pointer p);
-  void (*load_file)(scheme *sc, FILE *fin);
-  void (*load_string)(scheme *sc, const char *input);
+    void (*scheme_define)(scheme* sc, pointer env, pointer symbol, pointer value);
+    pointer (*cons)(scheme* sc, pointer a, pointer b);
+    pointer (*immutable_cons)(scheme* sc, pointer a, pointer b);
+    pointer (*mk_integer)(scheme* sc, long num);
+    pointer (*mk_real)(scheme* sc, double num);
+    pointer (*mk_symbol)(scheme* sc, const char* name);
+    pointer (*gensym)(scheme* sc);
+    pointer (*mk_string)(scheme* sc, const char* str);
+    pointer (*mk_counted_string)(scheme* sc, const char* str, int len);
+    pointer (*mk_character)(scheme* sc, int c);
+    pointer (*mk_vector)(scheme* sc, int len);
+    pointer (*mk_foreign_func)(scheme* sc, foreign_func f);
+    void (*putstr)(scheme* sc, const char* s);
+    void (*putcharacter)(scheme* sc, int c);
+
+    int (*is_string)(pointer p);
+    char* (*string_value)(pointer p);
+    int (*is_number)(pointer p);
+    num (*nvalue)(pointer p);
+    long (*ivalue)(pointer p);
+    double (*rvalue)(pointer p);
+    int (*is_integer)(pointer p);
+    int (*is_real)(pointer p);
+    int (*is_character)(pointer p);
+    long (*charvalue)(pointer p);
+    int (*is_vector)(pointer p);
+    long (*vector_length)(pointer vec);
+    void (*fill_vector)(pointer vec, pointer elem);
+    pointer (*vector_elem)(pointer vec, int ielem);
+    pointer (*set_vector_elem)(pointer vec, int ielem, pointer newel);
+    int (*is_port)(pointer p);
+
+    int (*is_pair)(pointer p);
+    pointer (*pair_car)(pointer p);
+    pointer (*pair_cdr)(pointer p);
+    pointer (*set_car)(pointer p, pointer q);
+    pointer (*set_cdr)(pointer p, pointer q);
+
+    int (*is_symbol)(pointer p);
+    char* (*symname)(pointer p);
+
+    int (*is_syntax)(pointer p);
+    int (*is_proc)(pointer p);
+    int (*is_foreign)(pointer p);
+    char* (*syntaxname)(pointer p);
+    int (*is_closure)(pointer p);
+    int (*is_macro)(pointer p);
+    pointer (*closure_code)(pointer p);
+    pointer (*closure_env)(pointer p);
+
+    int (*is_continuation)(pointer p);
+    int (*is_promise)(pointer p);
+    int (*is_environment)(pointer p);
+    int (*is_immutable)(pointer p);
+    void (*setimmutable)(pointer p);
+    void (*load_file)(scheme* sc, FILE* fin);
+    void (*load_string)(scheme* sc, const char* input);
 };
 #endif
 
 #endif
-
diff --git a/src/selection.c b/src/selection.c
index ad1c92b..0a85c43 100644
--- a/src/selection.c
+++ b/src/selection.c
@@ -27,43 +27,38 @@
 
 #include "gerbv.h"
 
-GArray *selection_new_array (void)
-{
-	return g_array_new (FALSE, FALSE, sizeof (gerbv_selection_item_t));
+GArray*
+selection_new_array(void) {
+    return g_array_new(FALSE, FALSE, sizeof(gerbv_selection_item_t));
 }
 
-gchar *selection_free_array (gerbv_selection_info_t *sel_info)
-{
-	return g_array_free (sel_info->selectedNodeArray, FALSE);
+gchar*
+selection_free_array(gerbv_selection_info_t* sel_info) {
+    return g_array_free(sel_info->selectedNodeArray, FALSE);
 }
 
-guint selection_length (gerbv_selection_info_t *sel_info)
-{
-	return sel_info->selectedNodeArray->len;
+guint
+selection_length(gerbv_selection_info_t* sel_info) {
+    return sel_info->selectedNodeArray->len;
 }
 
-gerbv_selection_item_t selection_get_item_by_index (
-			gerbv_selection_info_t *sel_info, guint idx)
-{
-	return g_array_index (sel_info->selectedNodeArray,
-				gerbv_selection_item_t, idx);
+gerbv_selection_item_t
+selection_get_item_by_index(gerbv_selection_info_t* sel_info, guint idx) {
+    return g_array_index(sel_info->selectedNodeArray, gerbv_selection_item_t, idx);
 }
 
-void selection_clear_item_by_index (
-			gerbv_selection_info_t *sel_info, guint idx)
-{
-	g_array_remove_index (sel_info->selectedNodeArray, idx);
+void
+selection_clear_item_by_index(gerbv_selection_info_t* sel_info, guint idx) {
+    g_array_remove_index(sel_info->selectedNodeArray, idx);
 }
 
-void selection_clear (gerbv_selection_info_t *sel_info)
-{
-	if (selection_length(sel_info))
-		g_array_remove_range (sel_info->selectedNodeArray, 0,
-				sel_info->selectedNodeArray->len);
+void
+selection_clear(gerbv_selection_info_t* sel_info) {
+    if (selection_length(sel_info))
+        g_array_remove_range(sel_info->selectedNodeArray, 0, sel_info->selectedNodeArray->len);
 }
 
-void selection_add_item (gerbv_selection_info_t *sel_info,
-				gerbv_selection_item_t *item)
-{
-	g_array_append_val (sel_info->selectedNodeArray, *item);
+void
+selection_add_item(gerbv_selection_info_t* sel_info, gerbv_selection_item_t* item) {
+    g_array_append_val(sel_info->selectedNodeArray, *item);
 }
diff --git a/src/selection.h b/src/selection.h
index 68148a0..ce8ce10 100644
--- a/src/selection.h
+++ b/src/selection.h
@@ -25,13 +25,9 @@
     \ingroup libgerbv
 */
 
-GArray *selection_new_array (void);
-guint selection_length (gerbv_selection_info_t *sel_info);
-void selection_add_item (gerbv_selection_info_t *sel_info,
-					gerbv_selection_item_t *item);
-gerbv_selection_item_t selection_get_item_by_index (
-				gerbv_selection_info_t *sel_info, guint idx);
-void selection_clear_item_by_index (
-				gerbv_selection_info_t *sel_info, guint idx);
-void selection_clear (gerbv_selection_info_t *sel_info);
-
+GArray*                selection_new_array(void);
+guint                  selection_length(gerbv_selection_info_t* sel_info);
+void                   selection_add_item(gerbv_selection_info_t* sel_info, gerbv_selection_item_t* item);
+gerbv_selection_item_t selection_get_item_by_index(gerbv_selection_info_t* sel_info, guint idx);
+void                   selection_clear_item_by_index(gerbv_selection_info_t* sel_info, guint idx);
+void                   selection_clear(gerbv_selection_info_t* sel_info);
diff --git a/src/table.c b/src/table.c
index a6b3394..cc47d1a 100644
--- a/src/table.c
+++ b/src/table.c
@@ -1,7 +1,7 @@
 /*! \file table.c
     \brief GTK widgets functions for table.
     \ingroup gerbv
- */ 
+ */
 
 #include <glib-object.h>
 #include <gtk/gtk.h>
@@ -9,229 +9,196 @@
 
 #include "table.h"
 
-static gint compare_uint(GtkTreeModel *model,
-		GtkTreeIter *a, GtkTreeIter *b,
-		gpointer p)
-{
-	gint sort_col = GPOINTER_TO_INT(p);
-	guint no1, no2;
+static gint
+compare_uint(GtkTreeModel* model, GtkTreeIter* a, GtkTreeIter* b, gpointer p) {
+    gint  sort_col = GPOINTER_TO_INT(p);
+    guint no1, no2;
 
-	gtk_tree_model_get(model, a, sort_col, &no1, -1);
-	gtk_tree_model_get(model, b, sort_col, &no2, -1);
+    gtk_tree_model_get(model, a, sort_col, &no1, -1);
+    gtk_tree_model_get(model, b, sort_col, &no2, -1);
 
-	return no1 - no2;
+    return no1 - no2;
 }
 
-static gint compare_int(GtkTreeModel *model,
-		GtkTreeIter *a, GtkTreeIter *b,
-		gpointer p)
-{
-	gint sort_col = GPOINTER_TO_INT(p);
-	gint no1, no2;
+static gint
+compare_int(GtkTreeModel* model, GtkTreeIter* a, GtkTreeIter* b, gpointer p) {
+    gint sort_col = GPOINTER_TO_INT(p);
+    gint no1, no2;
 
-	gtk_tree_model_get(model, a, sort_col, &no1, -1);
-	gtk_tree_model_get(model, b, sort_col, &no2, -1);
+    gtk_tree_model_get(model, a, sort_col, &no1, -1);
+    gtk_tree_model_get(model, b, sort_col, &no2, -1);
 
-	return no1 - no2;
+    return no1 - no2;
 }
 
-static gint compare_double(GtkTreeModel *model,
-		GtkTreeIter *a, GtkTreeIter *b,
-		gpointer p)
-{
-	gint sort_col = GPOINTER_TO_INT(p);
-	double no1, no2;
+static gint
+compare_double(GtkTreeModel* model, GtkTreeIter* a, GtkTreeIter* b, gpointer p) {
+    gint   sort_col = GPOINTER_TO_INT(p);
+    double no1, no2;
 
-	gtk_tree_model_get(model, a, sort_col, &no1, -1);
-	gtk_tree_model_get(model, b, sort_col, &no2, -1);
+    gtk_tree_model_get(model, a, sort_col, &no1, -1);
+    gtk_tree_model_get(model, b, sort_col, &no2, -1);
 
-	if (no1 > no2)
-		return 1;
+    if (no1 > no2)
+        return 1;
 
-	if (no1 < no2)
-		return -1;
-	
-	return 0;
+    if (no1 < no2)
+        return -1;
+
+    return 0;
 }
 
-static gint compare_str(GtkTreeModel *model,
-		GtkTreeIter *a, GtkTreeIter *b,
-		gpointer p)
-{
-	gint sort_col = GPOINTER_TO_INT(p);
-	gchar *str1, *str2;
-	gint ret;
+static gint
+compare_str(GtkTreeModel* model, GtkTreeIter* a, GtkTreeIter* b, gpointer p) {
+    gint   sort_col = GPOINTER_TO_INT(p);
+    gchar *str1, *str2;
+    gint   ret;
 
-	/* TODO: rewrite and sort D1 -- D10 */
+    /* TODO: rewrite and sort D1 -- D10 */
 
-	gtk_tree_model_get(model, a, sort_col, &str1, -1);
-	gtk_tree_model_get(model, b, sort_col, &str2, -1);
+    gtk_tree_model_get(model, a, sort_col, &str1, -1);
+    gtk_tree_model_get(model, b, sort_col, &str2, -1);
 
-	if (str1 == NULL || str2 == NULL) {
-		if (str1 == NULL && str2 == NULL)
-			return 0;
+    if (str1 == NULL || str2 == NULL) {
+        if (str1 == NULL && str2 == NULL)
+            return 0;
 
-		ret = (str1 == NULL) ? -1 : 1;
-	} else {
-		ret = g_utf8_collate(str1, str2);
-	}
+        ret = (str1 == NULL) ? -1 : 1;
+    } else {
+        ret = g_utf8_collate(str1, str2);
+    }
 
-	g_free(str1);
-	g_free(str2);
+    g_free(str1);
+    g_free(str2);
 
-	return ret;
+    return ret;
 }
 
 /* ... is (char *)title / (GType)type pairs */
-struct table *table_new_with_columns(gint col_nums, ...)
-{
-	struct table *table;
-	GtkTreeViewColumn *column;
-	const char *titles[col_nums];
-	va_list args;
-	gint i;
-
-	if (col_nums == 0)
-		return NULL;
-
-	va_start(args, col_nums);
-	table = g_new(struct table, 1);
-	table->types = g_new(GType, col_nums);
-	for (i = 0; i < col_nums; i++) {
-		titles[i] = va_arg(args, const char *);
-		table->types[i] = va_arg(args, GType);
-	}
-	va_end(args);
-
-	table->column_nums = col_nums;
-	table->list_store = gtk_list_store_newv(col_nums, table->types);
-	table->widget = gtk_tree_view_new_with_model(
-			GTK_TREE_MODEL(table->list_store));
-	/* Auto free tree_model at tree_view destruction */
-	g_object_unref(GTK_TREE_MODEL(table->list_store));
-
-	table->renderers = g_new(GtkCellRenderer *, col_nums);
-	for (i = 0; i < col_nums; i++) {
-		table->renderers[i] = gtk_cell_renderer_text_new();
-		column = gtk_tree_view_column_new();
-		gtk_tree_view_column_set_title(column, titles[i]);
-		gtk_tree_view_column_pack_start(column,
-				table->renderers[i], FALSE);
-		/* TODO: get "text" attribute by types[i] function? */
-		gtk_tree_view_column_add_attribute(column,
-				table->renderers[i], "text", i);
-		gtk_tree_view_append_column(GTK_TREE_VIEW(table->widget), column);
-	}
-
-	return table;
+struct table*
+table_new_with_columns(gint col_nums, ...) {
+    struct table*      table;
+    GtkTreeViewColumn* column;
+    const char*        titles[col_nums];
+    va_list            args;
+    gint               i;
+
+    if (col_nums == 0)
+        return NULL;
+
+    va_start(args, col_nums);
+    table        = g_new(struct table, 1);
+    table->types = g_new(GType, col_nums);
+    for (i = 0; i < col_nums; i++) {
+        titles[i]       = va_arg(args, const char*);
+        table->types[i] = va_arg(args, GType);
+    }
+    va_end(args);
+
+    table->column_nums = col_nums;
+    table->list_store  = gtk_list_store_newv(col_nums, table->types);
+    table->widget      = gtk_tree_view_new_with_model(GTK_TREE_MODEL(table->list_store));
+    /* Auto free tree_model at tree_view destruction */
+    g_object_unref(GTK_TREE_MODEL(table->list_store));
+
+    table->renderers = g_new(GtkCellRenderer*, col_nums);
+    for (i = 0; i < col_nums; i++) {
+        table->renderers[i] = gtk_cell_renderer_text_new();
+        column              = gtk_tree_view_column_new();
+        gtk_tree_view_column_set_title(column, titles[i]);
+        gtk_tree_view_column_pack_start(column, table->renderers[i], FALSE);
+        /* TODO: get "text" attribute by types[i] function? */
+        gtk_tree_view_column_add_attribute(column, table->renderers[i], "text", i);
+        gtk_tree_view_append_column(GTK_TREE_VIEW(table->widget), column);
+    }
+
+    return table;
 }
 
-void table_destroy(struct table *table)
-{
-	gtk_widget_destroy(table->widget);
-	g_free(table->types);
-	g_free(table);
+void
+table_destroy(struct table* table) {
+    gtk_widget_destroy(table->widget);
+    g_free(table->types);
+    g_free(table);
 }
 
-void table_set_sortable(struct table *table)
-{
-	GtkTreeSortable *sortable = GTK_TREE_SORTABLE(table->list_store);
-	GtkTreeViewColumn *column;
-	gint i, first_sort_col = -1;
-
-	for (i = 0; i < table->column_nums; i++) {
-		column = gtk_tree_view_get_column(
-				GTK_TREE_VIEW(table->widget), i);
-		switch (table->types[i]) {
-		case G_TYPE_UINT:
-			gtk_tree_sortable_set_sort_func(sortable, i,
-					&compare_uint, GINT_TO_POINTER(i),
-					NULL);
-			if (first_sort_col == -1)
-				first_sort_col = i;
-			break;
-		case G_TYPE_INT:
-			gtk_tree_sortable_set_sort_func(sortable, i,
-					&compare_int, GINT_TO_POINTER(i),
-					NULL);
-			if (first_sort_col == -1)
-				first_sort_col = i;
-			break;
-		case G_TYPE_DOUBLE:
-			gtk_tree_sortable_set_sort_func(sortable, i,
-					&compare_double, GINT_TO_POINTER(i),
-					NULL);
-			if (first_sort_col == -1)
-				first_sort_col = i;
-			break;
-		case G_TYPE_STRING:
-			gtk_tree_sortable_set_sort_func(sortable, i,
-					&compare_str, GINT_TO_POINTER(i),
-					NULL);
-			if (first_sort_col == -1)
-				first_sort_col = i;
-			break;
-		}
-
-		switch (table->types[i]) {
-		case G_TYPE_UINT:
-		case G_TYPE_INT:
-		case G_TYPE_DOUBLE:
-		case G_TYPE_STRING:
-			gtk_tree_view_column_set_sort_column_id(column, i);
-		}
-	}
-
-	if (first_sort_col != -1)
-		gtk_tree_sortable_set_sort_column_id(sortable,
-				first_sort_col, GTK_SORT_ASCENDING);
+void
+table_set_sortable(struct table* table) {
+    GtkTreeSortable*   sortable = GTK_TREE_SORTABLE(table->list_store);
+    GtkTreeViewColumn* column;
+    gint               i, first_sort_col = -1;
+
+    for (i = 0; i < table->column_nums; i++) {
+        column = gtk_tree_view_get_column(GTK_TREE_VIEW(table->widget), i);
+        switch (table->types[i]) {
+            case G_TYPE_UINT:
+                gtk_tree_sortable_set_sort_func(sortable, i, &compare_uint, GINT_TO_POINTER(i), NULL);
+                if (first_sort_col == -1)
+                    first_sort_col = i;
+                break;
+            case G_TYPE_INT:
+                gtk_tree_sortable_set_sort_func(sortable, i, &compare_int, GINT_TO_POINTER(i), NULL);
+                if (first_sort_col == -1)
+                    first_sort_col = i;
+                break;
+            case G_TYPE_DOUBLE:
+                gtk_tree_sortable_set_sort_func(sortable, i, &compare_double, GINT_TO_POINTER(i), NULL);
+                if (first_sort_col == -1)
+                    first_sort_col = i;
+                break;
+            case G_TYPE_STRING:
+                gtk_tree_sortable_set_sort_func(sortable, i, &compare_str, GINT_TO_POINTER(i), NULL);
+                if (first_sort_col == -1)
+                    first_sort_col = i;
+                break;
+        }
+
+        switch (table->types[i]) {
+            case G_TYPE_UINT:
+            case G_TYPE_INT:
+            case G_TYPE_DOUBLE:
+            case G_TYPE_STRING: gtk_tree_view_column_set_sort_column_id(column, i);
+        }
+    }
+
+    if (first_sort_col != -1)
+        gtk_tree_sortable_set_sort_column_id(sortable, first_sort_col, GTK_SORT_ASCENDING);
 }
 
 /* Set column alignment:
    0.0 -- left, 0.5 -- center, 1.0 -- right */
-void table_set_column_align(struct table *table, gint column_num, gfloat align)
-{
-	g_object_set(G_OBJECT(table->renderers[column_num]),
-			"xalign", align, NULL);
+void
+table_set_column_align(struct table* table, gint column_num, gfloat align) {
+    g_object_set(G_OBJECT(table->renderers[column_num]), "xalign", align, NULL);
 }
 
 /* ... is values with types as in table_new_with_columns() */
-int table_add_row(struct table *table, ...)
-{
-	GtkTreeIter iter;
-	GValue val;
-	va_list args;
-	gint i;
+int
+table_add_row(struct table* table, ...) {
+    GtkTreeIter iter;
+    GValue      val;
+    va_list     args;
+    gint        i;
 
 #if !GLIB_CHECK_VERSION(2, 36, 0)
-	g_type_init();
+    g_type_init();
 #endif
 
-	va_start(args, table);
-	gtk_list_store_append(table->list_store, &iter);
-	for (i = 0; i < table->column_nums; i++) {
-		memset(&val, 0, sizeof(GValue));
-		g_value_init(&val, table->types[i]);
-		switch (table->types[i]) {
-		case G_TYPE_STRING:
-			g_value_set_static_string(&val,
-					va_arg(args, const char *));
-			break;
-		case G_TYPE_INT:
-			g_value_set_int(&val, va_arg(args, int));
-			break;
-		case G_TYPE_UINT:
-			g_value_set_uint(&val, va_arg(args, unsigned int));
-			break;
-		case G_TYPE_DOUBLE:
-			g_value_set_double(&val, va_arg(args, double));
-			break;
-		default:
-			g_assert_not_reached();
-		}
-		gtk_list_store_set_value(table->list_store, &iter, i, &val);
-	}
-	va_end(args);
-
-	return 0;
+    va_start(args, table);
+    gtk_list_store_append(table->list_store, &iter);
+    for (i = 0; i < table->column_nums; i++) {
+        memset(&val, 0, sizeof(GValue));
+        g_value_init(&val, table->types[i]);
+        switch (table->types[i]) {
+            case G_TYPE_STRING: g_value_set_static_string(&val, va_arg(args, const char*)); break;
+            case G_TYPE_INT: g_value_set_int(&val, va_arg(args, int)); break;
+            case G_TYPE_UINT: g_value_set_uint(&val, va_arg(args, unsigned int)); break;
+            case G_TYPE_DOUBLE: g_value_set_double(&val, va_arg(args, double)); break;
+            default: g_assert_not_reached();
+        }
+        gtk_list_store_set_value(table->list_store, &iter, i, &val);
+    }
+    va_end(args);
+
+    return 0;
 }
diff --git a/src/table.h b/src/table.h
index 9c6373a..0e47209 100644
--- a/src/table.h
+++ b/src/table.h
@@ -1,23 +1,23 @@
 /** \file table.h
     \brief Header info for GTK widgets table functions.
     \ingroup gerbv
- */ 
+ */
 
 #ifndef TABLE_H
 #define TABLE_H
 
 struct table {
-	GtkWidget	*widget;	/* All table */
-	GtkListStore	*list_store;
-	GType		*types;		/* Column types array */
-	GtkCellRenderer **renderers;	/* Column renderers pointers array */
-	gint		column_nums;	/* Column number */
+    GtkWidget*        widget; /* All table */
+    GtkListStore*     list_store;
+    GType*            types;       /* Column types array */
+    GtkCellRenderer** renderers;   /* Column renderers pointers array */
+    gint              column_nums; /* Column number */
 };
 
-struct table *table_new_with_columns(gint col_nums, ...);
-void table_destroy(struct table *table);
-void table_set_sortable(struct table *table);
-void table_set_column_align(struct table *table, gint column_num, gfloat align);
-int table_add_row(struct table *table, ...);
+struct table* table_new_with_columns(gint col_nums, ...);
+void          table_destroy(struct table* table);
+void          table_set_sortable(struct table* table);
+void          table_set_column_align(struct table* table, gint column_num, gfloat align);
+int           table_add_row(struct table* table, ...);
 
-#endif	/* TABLE_H */
+#endif /* TABLE_H */
diff --git a/src/tooltable.c b/src/tooltable.c
index 59ef437..38bf4b0 100644
--- a/src/tooltable.c
+++ b/src/tooltable.c
@@ -32,58 +32,63 @@
 #include "common.h"
 #include "gerbv.h"
 
-#define MIN_TOOL_NUMBER         1       /* T01 */
-#define MAX_TOOL_NUMBER         99      /* T99 */
-
-static int have_tools_file = 0;
-static double tools[1+MAX_TOOL_NUMBER];
-
-static void 
-ProcessToolLine(const char *cp, const char *file_name, long int file_line)
-{
-    const char *cp0 = cp;
-    int toolNumber;
-    double toolDia;
-    
+#define MIN_TOOL_NUMBER 1  /* T01 */
+#define MAX_TOOL_NUMBER 99 /* T99 */
+
+static int    have_tools_file = 0;
+static double tools[1 + MAX_TOOL_NUMBER];
+
+static void
+ProcessToolLine(const char* cp, const char* file_name, long int file_line) {
+    const char* cp0 = cp;
+    int         toolNumber;
+    double      toolDia;
+
     if (cp == NULL)
         return;
-    
+
     /* Skip leading spaces if there are some */
-    while (isspace((int) *cp)) {
+    while (isspace((int)*cp)) {
         if (*(++cp) == '\0')
             return;
     }
-    
+
     if (*cp != 'T') {
-        GERB_COMPILE_WARNING(_("Ignored strange tool \"%s\" "
-				"at line %ld in file \"%s\""),
-			cp0, file_line, file_name);
+        GERB_COMPILE_WARNING(
+            _("Ignored strange tool \"%s\" "
+              "at line %ld in file \"%s\""),
+            cp0, file_line, file_name
+        );
         return;
     }
-    if ((!isdigit((int) cp[1])) || (!isdigit((int) cp[2]))) {
-        GERB_COMPILE_WARNING(_("No tool number in \"%s\" "
-				"at line %ld in file \"%s\""),
-			cp0, file_line, file_name);
+    if ((!isdigit((int)cp[1])) || (!isdigit((int)cp[2]))) {
+        GERB_COMPILE_WARNING(
+            _("No tool number in \"%s\" "
+              "at line %ld in file \"%s\""),
+            cp0, file_line, file_name
+        );
         return;
     }
     do {
         char tnb[3];
-        tnb[0] = cp[1];
-        tnb[1] = cp[2];
-        tnb[2] = '\0';
+        tnb[0]     = cp[1];
+        tnb[1]     = cp[2];
+        tnb[2]     = '\0';
         toolNumber = atoi(tnb);
         if ((toolNumber < MIN_TOOL_NUMBER) || (toolNumber > MAX_TOOL_NUMBER)) {
-            GERB_COMPILE_WARNING(_("Can't parse tool number in \"%s\" "
-				    "at line %ld in file \"%s\""),
-			    cp0, file_line, file_name);
+            GERB_COMPILE_WARNING(
+                _("Can't parse tool number in \"%s\" "
+                  "at line %ld in file \"%s\""),
+                cp0, file_line, file_name
+            );
             return;
         }
     } while (0);
-    
+
     cp += 3; /* Skip Tnn */
 
     /* Skip following spaces if there are some */
-    while (isspace((int) *cp)) {
+    while (isspace((int)*cp)) {
         if (*(++cp) == '\0')
             return;
     }
@@ -92,44 +97,50 @@ ProcessToolLine(const char *cp, const char *file_name, long int file_line)
     toolDia = atof(cp);
 
     if (toolDia <= 0) {
-        GERB_COMPILE_ERROR(_("Tool T%02d diameter is impossible "
-				"at line %ld in file \"%s\""),
-			toolNumber, file_line, file_name);
+        GERB_COMPILE_ERROR(
+            _("Tool T%02d diameter is impossible "
+              "at line %ld in file \"%s\""),
+            toolNumber, file_line, file_name
+        );
         return;
     }
     if (toolDia < 0.001) {
-        GERB_COMPILE_WARNING(_("Tool T%02d diameter is very small "
-				"at line %ld in file \"%s\""),
-			toolNumber, file_line, file_name);
+        GERB_COMPILE_WARNING(
+            _("Tool T%02d diameter is very small "
+              "at line %ld in file \"%s\""),
+            toolNumber, file_line, file_name
+        );
     }
-    
+
     if (tools[toolNumber] != 0) {
-        GERB_COMPILE_ERROR(_("Tool T%02d is already defined, occurred "
-				"at line %ld in file \"%s\""),
-			toolNumber, file_line, file_name);
-        GERB_FATAL_ERROR(_("Exiting because this is a HOLD error "
-				"at any board house."));
+        GERB_COMPILE_ERROR(
+            _("Tool T%02d is already defined, occurred "
+              "at line %ld in file \"%s\""),
+            toolNumber, file_line, file_name
+        );
+        GERB_FATAL_ERROR(
+            _("Exiting because this is a HOLD error "
+              "at any board house.")
+        );
         exit(1);
         return;
     }
-    
+
     tools[toolNumber] = toolDia;
 } /* ProcessToolLine */
 
-
-int 
-gerbv_process_tools_file(const char *tf)
-{
-    FILE *f;
-    char buf[80];
+int
+gerbv_process_tools_file(const char* tf) {
+    FILE*    f;
+    char     buf[80];
     long int file_line = 0;
-    
+
     have_tools_file = 0;
     memset(tools, 0, sizeof(tools));
-    
+
     if (tf == NULL)
         return 0;
-    
+
     f = fopen(tf, "r");
     if (f == NULL) {
         GERB_COMPILE_ERROR(_("Failed to open \"%s\" for reading"), tf);
@@ -137,10 +148,10 @@ gerbv_process_tools_file(const char *tf)
     }
     while (!feof(f)) {
         memset(buf, 0, sizeof(buf));
-        if (NULL == fgets(buf, sizeof(buf)-1, f))
+        if (NULL == fgets(buf, sizeof(buf) - 1, f))
             break;
 
-	file_line++;
+        file_line++;
         ProcessToolLine(buf, tf, file_line);
     }
     fclose(f);
@@ -148,10 +159,8 @@ gerbv_process_tools_file(const char *tf)
     return 1;
 } /* gerbv_process_tools_file */
 
-
-double 
-gerbv_get_tool_diameter(int toolNumber)
-{
+double
+gerbv_get_tool_diameter(int toolNumber) {
     if (!have_tools_file)
         return 0;
     if ((toolNumber < MIN_TOOL_NUMBER) || (toolNumber > MAX_TOOL_NUMBER))
