about summary refs log tree commit diff
path: root/converter/ppm/ppmtompeg
diff options
context:
space:
mode:
Diffstat (limited to 'converter/ppm/ppmtompeg')
-rw-r--r--converter/ppm/ppmtompeg/Makefile33
-rw-r--r--converter/ppm/ppmtompeg/bframe.c1
-rw-r--r--converter/ppm/ppmtompeg/bsearch.c1
-rw-r--r--converter/ppm/ppmtompeg/combine.c6
-rw-r--r--converter/ppm/ppmtompeg/file.c351
-rw-r--r--converter/ppm/ppmtompeg/frames.c58
-rw-r--r--converter/ppm/ppmtompeg/gethostname_win32.c404
-rw-r--r--converter/ppm/ppmtompeg/headers/bitio.h4
-rw-r--r--converter/ppm/ppmtompeg/headers/block.h44
-rw-r--r--converter/ppm/ppmtompeg/headers/byteorder.h2
-rw-r--r--converter/ppm/ppmtompeg/headers/frame.h16
-rw-r--r--converter/ppm/ppmtompeg/headers/frames.h170
-rw-r--r--converter/ppm/ppmtompeg/headers/iframe.h118
-rw-r--r--converter/ppm/ppmtompeg/headers/motion_search.h3
-rw-r--r--converter/ppm/ppmtompeg/headers/mpeg.h5
-rw-r--r--converter/ppm/ppmtompeg/headers/mproto.h8
-rw-r--r--converter/ppm/ppmtompeg/headers/param.h97
-rw-r--r--converter/ppm/ppmtompeg/headers/prototypes.h9
-rw-r--r--converter/ppm/ppmtompeg/headers/subsample.h39
-rw-r--r--converter/ppm/ppmtompeg/huff.h34
-rw-r--r--converter/ppm/ppmtompeg/iframe.c225
-rw-r--r--converter/ppm/ppmtompeg/jpeg.c28
-rw-r--r--converter/ppm/ppmtompeg/mheaders.c712
-rw-r--r--converter/ppm/ppmtompeg/mpeg.c120
-rw-r--r--converter/ppm/ppmtompeg/noparallel.c2
-rw-r--r--converter/ppm/ppmtompeg/parallel.c10
-rw-r--r--converter/ppm/ppmtompeg/param.c143
-rw-r--r--converter/ppm/ppmtompeg/pframe.c2
-rw-r--r--converter/ppm/ppmtompeg/ppmtompeg.c160
-rw-r--r--converter/ppm/ppmtompeg/psearch.c2
-rw-r--r--converter/ppm/ppmtompeg/rate.c1
-rw-r--r--converter/ppm/ppmtompeg/specifics.c45
-rw-r--r--converter/ppm/ppmtompeg/subsample.c1
33 files changed, 1601 insertions, 1253 deletions
diff --git a/converter/ppm/ppmtompeg/Makefile b/converter/ppm/ppmtompeg/Makefile
index 4e0ad8d6..a1004fdd 100644
--- a/converter/ppm/ppmtompeg/Makefile
+++ b/converter/ppm/ppmtompeg/Makefile
@@ -5,7 +5,7 @@ endif
 SUBDIR = converter/ppm/ppmtompeg
 VPATH=.:$(SRCDIR)/$(SUBDIR)
 
-include $(BUILDDIR)/Makefile.config
+include $(BUILDDIR)/config.mk
 
 ifeq ($(JPEGLIB),NONE)
   # 'nojpeg' is a module that implements all the jpeg access routines as
@@ -18,11 +18,12 @@ else
   JPEGLIBX = $(JPEGLIB)
 endif
 
-INCLUDES = -I$(SRCDIR)/$(SUBDIR)/headers 
+COMP_INCLUDES = -I$(SRCDIR)/$(SUBDIR)/headers 
 
+EXTERN_INCLUDES =
 ifneq ($(JPEGHDR_DIR),NONE)
   ifneq ($(JPEGHDR_DIR)x,x)
-    INCLUDES += -I$(JPEGHDR_DIR)
+    EXTERN_INCLUDES += -I$(JPEGHDR_DIR)
   endif
 endif
 
@@ -38,17 +39,31 @@ endif
 #
 
 MP_BASE_OBJS = mfwddct.o postdct.o huff.o bitio.o mheaders.o
-MP_ENCODE_OBJS = iframe.o pframe.o bframe.o psearch.o bsearch.o block.o 
+MP_ENCODE_OBJS = \
+  frames.o \
+  iframe.o \
+  pframe.o \
+  bframe.o \
+  psearch.o \
+  bsearch.o \
+  block.o 
+
 MP_OTHER_OBJS = mpeg.o subsample.o param.o rgbtoycc.o \
 	readframe.o combine.o jrevdct.o frame.o fsize.o frametype.o \
-	specifics.o rate.o opts.o input.o gethostname.o
+	specifics.o rate.o opts.o input.o
 ifeq ($(OMIT_NETWORK),y)
-  MP_PARALLEL_OBJS = noparallel.o
+  MP_OTHER_OBJS += noparallel.o
+else
+  MP_OTHER_OBJS += parallel.o psocket.o
+endif
+ifeq ($(MSVCRT),Y)
+  MP_OTHER_OBJS += gethostname_win32.o
 else
-  MP_PARALLEL_OBJS = parallel.o psocket.o
+  MP_OTHER_OBJS += gethostname.o
 endif
+
 NONMAIN_OBJS = $(MP_BASE_OBJS) $(MP_OTHER_OBJS) $(MP_ENCODE_OBJS) \
-	      $(MP_PARALLEL_OBJS) $(JPEG_MODULE).o
+	      	$(JPEG_MODULE).o
 OBJECTS = ppmtompeg.o $(NONMAIN_OBJS)
 MERGE_OBJECTS = ppmtompeg.o2 $(NONMAIN_OBJS)
 MP_INCLUDE = mproto.h mtypes.h huff.h bitio.h
@@ -61,7 +76,7 @@ SCRIPTS =
 .PHONY: all
 all: ppmtompeg
 
-include $(SRCDIR)/Makefile.common
+include $(SRCDIR)/common.mk
 
 ifeq ($(NEED_RUNTIME_PATH),Y)
   LIBOPTR = -runtime
diff --git a/converter/ppm/ppmtompeg/bframe.c b/converter/ppm/ppmtompeg/bframe.c
index 5dfb76d3..1dbc1846 100644
--- a/converter/ppm/ppmtompeg/bframe.c
+++ b/converter/ppm/ppmtompeg/bframe.c
@@ -84,7 +84,6 @@ static struct bframeStats {
  *====================*/
 
 extern Block **dct, **dctr, **dctb;
-extern dct_data_type **dct_data;
 #define NO_MOTION 0
 #define MOTION 1
 #define SKIP 2  /* used in useMotion in dct_data */
diff --git a/converter/ppm/ppmtompeg/bsearch.c b/converter/ppm/ppmtompeg/bsearch.c
index 142987f5..70edfef6 100644
--- a/converter/ppm/ppmtompeg/bsearch.c
+++ b/converter/ppm/ppmtompeg/bsearch.c
@@ -77,6 +77,7 @@
 #include "frames.h"
 #include "motion_search.h"
 #include "fsize.h"
+#include "block.h"
 
 
 /*==================*
diff --git a/converter/ppm/ppmtompeg/combine.c b/converter/ppm/ppmtompeg/combine.c
index 52cc646d..8e0d3281 100644
--- a/converter/ppm/ppmtompeg/combine.c
+++ b/converter/ppm/ppmtompeg/combine.c
@@ -35,8 +35,8 @@
 #include <errno.h>
 #include <unistd.h>
 
-#include "ppm.h"
 #include "nstring.h"
+#include "nsleep.h"
 
 #include "mtypes.h"
 #include "frames.h"
@@ -111,11 +111,9 @@ appendSpecifiedGopFiles(struct inputSource * const inputSourceP,
              ++nAttempts) {
 
             ifP = fopen(fileName, "rb");
-            if (ifP == NULL) {
+            if (ifP == NULL)
                 pm_message("ERROR:  Couldn't read file '%s'.  retry %u", 
                            fileName, nAttempts);
-                sleep(1);
-            }
         }
         if (ifP) {
             if (!realQuiet)
diff --git a/converter/ppm/ppmtompeg/file.c b/converter/ppm/ppmtompeg/file.c
index ae741962..223170a4 100644
--- a/converter/ppm/ppmtompeg/file.c
+++ b/converter/ppm/ppmtompeg/file.c
@@ -19,17 +19,6 @@
  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  */
 
-/*  
- *  $Header: /n/picasso/project/mm/mpeg/mpeg_dist/mpeg_encode/RCS/file.c,v 1.2 1993/06/30 20:06:09 keving Exp $
- *  $Log: file.c,v $
- * Revision 1.2  1993/06/30  20:06:09  keving
- * nothing
- *
- * Revision 1.1  1993/06/03  21:08:08  keving
- * nothing
- *
- */
-
 #include "tk.h"
 
 #include "all.h"
@@ -40,11 +29,10 @@
 #include <time.h>
 #include <string.h>
 #include <dirent.h>
-#include <strings.h>
 
 #define MAX_FILES   1000
-#define MAX_NAME_LEN	256
-#define MAX_STRING_LEN	MAX_NAME_LEN
+#define MAX_NAME_LEN    256
+#define MAX_STRING_LEN  MAX_NAME_LEN
 
 typedef int boolean;
 #define TRUE 1
@@ -52,77 +40,76 @@ typedef int boolean;
 
 extern char currentPath[MAXPATHLEN];
 
-char	globString[1024];
+char globString[1024];
 
-static DIR *dfd;
+static DIR * dfd;
 
-void	ResetPath(void);
+void ResetPath(void);
 int ListDirectory(ClientData nulldata, Tcl_Interp *interp, int argc,
-		  char **argv);
+                  char **argv);
 int ChangeDirectory(ClientData nulldata, Tcl_Interp *interp, int argc,
-		  char **argv);
-void	SortFiles(int numStrings, char strings[MAX_FILES][MAX_NAME_LEN],
-		  boolean *dirList, int permute[]);
+                    char **argv);
+void SortFiles(int numStrings, char strings[MAX_FILES][MAX_NAME_LEN],
+               boolean *dirList, int permute[]);
+
+static void UpdatePath(Tcl_Interp *interp, char *directory);
+static boolean MatchesGlob(char *string, char *glob);
 
-static void	UpdatePath(Tcl_Interp *interp, char *directory);
-static boolean	MatchesGlob(char *string, char *glob);
 
 
+void
+ResetPath() {
 
-void	ResetPath()
-{
-    if ( getwd(currentPath) == 0 )
-    {
-	fprintf(stderr, "Error getting pathname!!!\n");
-	exit(1);
+    if (getwd(currentPath) == 0) {
+        fprintf(stderr, "Error getting pathname!!!\n");
+        exit(1);
     }
 
     strcpy(&currentPath[strlen(currentPath)], "/");
 
     dfd = opendir(currentPath);
-    if ( dfd == NULL )
-    {
-	fprintf(stderr, "can't open '%s'\n", currentPath);
-	exit(1);
+    if (dfd == NULL) {
+        fprintf(stderr, "can't open '%s'\n", currentPath);
+        exit(1);
     }
 }
 
 
-static void	UpdatePath(Tcl_Interp *interp, char *directory)
-{
+
+static void
+UpdatePath(Tcl_Interp *interp, char *directory) {
+
     int length;
     char *charPtr;
 
     length = strlen(currentPath);
 
-    if ( strcmp(directory, "./") == 0 )
-	return /* nothing */ ;
-    else if ( strcmp(directory, "../") == 0 )
-    {
-	/* delete backwards up to '/' */
-
-	if ( length < 2 )
-	{
-	    fprintf(stderr, "Error:  backing up from root directory!!!\n");
-	    exit(1);
-	}
-
-	charPtr = &currentPath[length-2];
-	while ( (charPtr != currentPath) && (*charPtr != '/') )
-	    charPtr--;
-	charPtr++;	/* leave the '/' */
-	*charPtr = '\0';
-    }
-    else
-    {
-	strcpy(&currentPath[length], directory);
+    if (streq(directory, "./"))
+        return /* nothing */ ;
+    else if (streq(directory, "../")) {
+        /* delete backwards up to '/' */
+
+        if (length < 2) {
+            fprintf(stderr, "Error:  backing up from root directory!!!\n");
+            exit(1);
+        }
+
+        charPtr = &currentPath[length-2];
+        while ((charPtr != currentPath) && (*charPtr != '/'))
+            --charPtr;
+        ++charPtr;  /* leave the '/' */
+        *charPtr = '\0';
+    } else {
+        strcpy(&currentPath[length], directory);
     }
 }
 
 
-int ChangeDirectory(ClientData nulldata, Tcl_Interp *interp, int argc,
-		  char **argv)
-{
+
+int
+ChangeDirectory(ClientData nulldata, Tcl_Interp *interp, int argc,
+                char **argv) {
+
     char *directory = argv[1];
 
     UpdatePath(interp, directory);
@@ -130,82 +117,74 @@ int ChangeDirectory(ClientData nulldata, Tcl_Interp *interp, int argc,
     fprintf(stdout, "Opening directory: '%s'\n", currentPath);
 
     dfd = opendir(currentPath);
-    if ( dfd == NULL )
-    {
-	fprintf(stderr, "can't open '%s'\n", currentPath);
-	return TCL_OK;	/* shouldn't, really */
+    if (dfd == NULL) {
+        fprintf(stderr, "can't open '%s'\n", currentPath);
+        return TCL_OK;  /* shouldn't, really */
     }
-
+    
     return TCL_OK;
 }
 
 
-int ListDirectory(ClientData nulldata, Tcl_Interp *interp, int argc,
-		  char **argv)
-{
-    struct dirent *dp;
+
+int
+ListDirectory(ClientData nulldata, Tcl_Interp *interp, int argc,
+              char **argv) {
+
+    struct dirent * dp;
     struct stat stbuf;
     char command[256];
     char fileName[MAX_FILES][MAX_NAME_LEN];
     boolean dirList[MAX_FILES];
     int permute[MAX_FILES];
-    int	fileCount = 0;
-    register int index;
+    int fileCount = 0;
+    int index;
     char fullName[MAXPATHLEN];
-    char    *restPtr;
+    char * restPtr;
 
     sprintf(command, "ShowCurrentDirectory %s", currentPath);
     Tcl_Eval(interp, command, 0, (char **) NULL);
 
-    if ( dfd == NULL )
-    {
-	fprintf(stderr, "TRIED TO LIST NULL DIRECTORY\n");
+    if (dfd == NULL) {
+        fprintf(stderr, "TRIED TO LIST NULL DIRECTORY\n");
 
-	return TCL_OK;
+        return TCL_OK;
     }
 
-/* check if root directory */
-    if ( strlen(currentPath) != 1 )
-    {
-	sprintf(fileName[fileCount], "../");
-	dirList[fileCount] = TRUE;
-	fileCount++;
+    /* check if root directory */
+    if (strlen(currentPath) != 1) {
+        sprintf(fileName[fileCount], "../");
+        dirList[fileCount] = TRUE;
+        ++fileCount;
     }
 
     strcpy(fullName, currentPath);
     restPtr = &fullName[strlen(fullName)];
 
-    while ( (dp = readdir(dfd)) != NULL )
-    {
-	strcpy(restPtr, dp->d_name);
-	stat(fullName, &stbuf);
-
-	if ( dp->d_name[0] != '.' )
-	{
-	    if ( S_ISDIR(stbuf.st_mode) )
-	    {
-		sprintf(fileName[fileCount], "%s/", dp->d_name);
-		dirList[fileCount] = TRUE;
-		fileCount++;
-	    }
-	    else
-	    {
-		if ( MatchesGlob(dp->d_name, globString) )
-		{
-		    strcpy(fileName[fileCount], dp->d_name);
-		    dirList[fileCount] = FALSE;
-		    fileCount++;
-		}
-	    }
-	}
+    while ((dp = readdir(dfd)) != NULL) {
+        strcpy(restPtr, dp->d_name);
+        stat(fullName, &stbuf);
+        
+        if (dp->d_name[0] != '.') {
+            if (S_ISDIR(stbuf.st_mode)) {
+                sprintf(fileName[fileCount], "%s/", dp->d_name);
+                dirList[fileCount] = TRUE;
+                ++fileCount;
+            } else {
+                if (MatchesGlob(dp->d_name, globString)) {
+                    strcpy(fileName[fileCount], dp->d_name);
+                    dirList[fileCount] = FALSE;
+                    ++fileCount;
+                }
+            }
+        }
     }
 
     SortFiles(fileCount, fileName, dirList, permute);
 
-    for ( index = 0; index < fileCount; index++ )
-    {
-	sprintf(command, "AddBrowseFile %s", fileName[permute[index]]);
-	Tcl_Eval(interp, command, 0, (char **) NULL);
+    for (index = 0; index < fileCount; ++index) {
+        sprintf(command, "AddBrowseFile %s", fileName[permute[index]]);
+        Tcl_Eval(interp, command, 0, (char **) NULL);
     }
 
     closedir(dfd);
@@ -214,108 +193,110 @@ int ListDirectory(ClientData nulldata, Tcl_Interp *interp, int argc,
 }
 
 
-void	SortFiles(int numStrings, char strings[MAX_FILES][MAX_NAME_LEN],
-		  boolean *dirList, int permute[])
-{
-    register int i, j;
-    int temp;
-    int	numDirs;
-    int	ptr;
 
-    for ( i = 0; i < numStrings; i++ )
-	permute[i] = i;
+void
+SortFiles(int numStrings, char strings[MAX_FILES][MAX_NAME_LEN],
+          boolean *dirList, int permute[]) {
+
+    int i;
+    int numDirs;
+    int ptr;
+
+    for (i = 0; i < numStrings; ++i)
+        permute[i] = i;
 
     /* put all directories at front */
     numDirs = 0;
     ptr = numStrings-1;
-    while ( numDirs != ptr )
-    {
-	/* go past dirs */
-	while ( (numDirs < ptr) && (dirList[permute[numDirs]]) )
-	    numDirs++;
-
-	/* go past non-dirs */
-	while ( (numDirs < ptr) && (! dirList[permute[ptr]]) )
-	    ptr--;
-
-	if ( numDirs != ptr )
-	{
-	    temp = permute[numDirs];
-	    permute[numDirs] = ptr;
-	    permute[ptr] = temp;
-	}
+    while (numDirs != ptr) {
+        /* go past dirs */
+        while ((numDirs < ptr) && (dirList[permute[numDirs]]))
+            ++numDirs;
+
+        /* go past non-dirs */
+        while ((numDirs < ptr) && (! dirList[permute[ptr]]))
+            --ptr;
+
+        if (numDirs != ptr) {
+            int const temp = permute[numDirs];
+            permute[numDirs] = ptr;
+            permute[ptr] = temp;
+        }
     }
 
-    if ( dirList[permute[numDirs]] )
-	numDirs++;
-
-    for ( i = 0; i < numDirs; i++ )
-	for ( j = i+1; j < numDirs; j++ )
-	{
-	    if ( strcmp(&strings[permute[j]][0], &strings[permute[i]][0]) < 0 )
-	    {
-		temp = permute[j];
-		permute[j] = permute[i];
-		permute[i] = temp;
-	    }
-	}
-
-    for ( i = numDirs; i < numStrings; i++ )
-	for ( j = i+1; j < numStrings; j++ )
-	{
-	    if ( strcmp(&strings[permute[j]][0], &strings[permute[i]][0]) < 0 )
-	    {
-		temp = permute[j];
-		permute[j] = permute[i];
-		permute[i] = temp;
-	    }
-	}
+    if (dirList[permute[numDirs]])
+        ++numDirs;
+
+    for (i = 0; i < numDirs; ++i) {
+        int j;
+        for (j = i + 1; j < numDirs; ++j) {
+            if (strcmp(&strings[permute[j]][0], &strings[permute[i]][0]) < 0) {
+                int const temp = permute[j];
+                permute[j] = permute[i];
+                permute[i] = temp;
+            }
+        }
+    }
+    for (i = numDirs; i < numStrings; ++i) {
+        int j;
+        for (j = i + 1; j < numStrings; ++j) {
+            if (strcmp(&strings[permute[j]][0], &strings[permute[i]][0]) < 0) {
+                int const temp = permute[j];
+                permute[j] = permute[i];
+                permute[i] = temp;
+            }
+        }
+    }
 }
 
 
-int SetBrowseGlob (ClientData nulldata, Tcl_Interp *interp,
-		   int argc, char **argv)
-{
-    if (argc == 2 )
-    {
-	strcpy(globString, argv[1]);
 
-	fprintf(stdout, "GLOB:  %s\n", globString);
+int
+SetBrowseGlob(ClientData nulldata, Tcl_Interp *interp,
+              int argc, char **argv) {
+
+    if (argc == 2) {
+        strcpy(globString, argv[1]);
+
+        fprintf(stdout, "GLOB:  %s\n", globString);
 
-	return TCL_OK;
+        return TCL_OK;
     }
 
-	Tcl_AppendResult (interp, 
-            "wrong args: should be \"", argv[0]," string\"", (char *) NULL);
-	return TCL_ERROR;
+    Tcl_AppendResult(interp, 
+                     "wrong args: should be \"", argv[0]," string\"",
+                     NULL);
+    return TCL_ERROR;
 }
 
 
-static boolean	MatchesGlob(char *string, char *glob)
-{
-    char    *stringRight, *globRight;
 
-    while ( (*glob != '\0') && (*glob != '*') )	    /* match left side */
-    {
-	if ( (*string == '\0') || (*string != *glob) )
-	    return FALSE;
-	string++;
-	glob++;
+static boolean
+MatchesGlob(char *string, char *glob) {
+
+    char * stringRight;
+    char * globRight;
+
+    while ((*glob != '\0') && (*glob != '*')) {
+        /* match left side */
+        if ((*string == '\0') || (*string != *glob))
+            return FALSE;
+        ++string;
+        ++glob;
     }
 
-    if ( *glob == '\0' )	/* no star */
-	return TRUE;
+    if (*glob == '\0')    /* no star */
+        return TRUE;
 
     /* now match right side */
     stringRight = &string[strlen(string)-1];
     globRight = &glob[strlen(glob)-1];
 
-    while ( *globRight != '*' )
-    {
-	if ( (stringRight < string) || (*stringRight != *globRight) )
-	    return FALSE;
-	globRight--;
-	stringRight--;
+    while (*globRight != '*') {
+        if ((stringRight < string) || (*stringRight != *globRight))
+            return FALSE;
+        --globRight;
+        --stringRight;
     }
 
     return TRUE;
diff --git a/converter/ppm/ppmtompeg/frames.c b/converter/ppm/ppmtompeg/frames.c
new file mode 100644
index 00000000..a0764890
--- /dev/null
+++ b/converter/ppm/ppmtompeg/frames.c
@@ -0,0 +1,58 @@
+#include "mallocvar.h"
+#include "fsize.h"
+
+#include "frames.h"
+
+
+Block **dct=NULL, **dctr=NULL, **dctb=NULL;
+dct_data_type   **dct_data; /* used in p/bframe.c */
+
+
+/*===========================================================================*
+ *
+ * AllocDctBlocks
+ *
+ *  allocate memory for dct blocks
+ *
+ * RETURNS: nothing
+ *
+ * SIDE EFFECTS:    creates dct, dctr, dctb
+ *
+ *===========================================================================*/
+void
+AllocDctBlocks(void) {
+
+    int dctx, dcty;
+    int i;
+
+    dctx = Fsize_x / DCTSIZE;
+    dcty = Fsize_y / DCTSIZE;
+
+    MALLOCARRAY(dct, dcty);
+    ERRCHK(dct, "malloc");
+    for (i = 0; i < dcty; ++i) {
+        dct[i] = (Block *) malloc(sizeof(Block) * dctx);
+        ERRCHK(dct[i], "malloc");
+    }
+
+    MALLOCARRAY(dct_data, dcty);
+    ERRCHK(dct_data, "malloc");
+    for (i = 0; i < dcty; ++i) {
+        MALLOCARRAY(dct_data[i], dctx);
+        ERRCHK(dct[i], "malloc");
+    }
+
+    MALLOCARRAY(dctr, dcty/2);
+    ERRCHK(dctr, "malloc");
+    MALLOCARRAY(dctb, dcty/2);
+    ERRCHK(dctb, "malloc");
+    for (i = 0; i < dcty/2; ++i) {
+        MALLOCARRAY(dctr[i], dctx/2);
+        ERRCHK(dctr[i], "malloc");
+        MALLOCARRAY(dctb[i], dctx/2);
+        ERRCHK(dctb[i], "malloc");
+    }
+}
+
+
+
diff --git a/converter/ppm/ppmtompeg/gethostname_win32.c b/converter/ppm/ppmtompeg/gethostname_win32.c
new file mode 100644
index 00000000..383f4e55
--- /dev/null
+++ b/converter/ppm/ppmtompeg/gethostname_win32.c
@@ -0,0 +1,404 @@
+/* define this macro for activating debugging version */
+/* #define GETHOSTNAME_LOCAL_DEBUG     1*/
+
+#include <windows.h>
+#include <tchar.h>
+#include <stdarg.h>
+
+#ifndef GETHOSTNAME_LOCAL_DEBUG
+#include "pm.h"
+#include "gethostname.h"
+#endif
+
+#define BUFSIZE 80
+
+typedef void (WINAPI *PGNSI)(LPSYSTEM_INFO);
+typedef BOOL (WINAPI *PGPI)(DWORD, DWORD, DWORD, DWORD, PDWORD);
+
+typedef struct {
+    char  str[256];
+    int   level;
+} push_string_t;
+
+static void
+pushString(push_string_t *p, const char *fmt, ...)
+{
+    va_list args;
+
+    va_start(args, fmt);
+    p->level += _vsnprintf(p->str + p->level, sizeof(p->str)-p->level, fmt, args);
+    va_end(args);
+}
+
+#if _WIN32_WINNT < 0x0600
+/*
+ * Reference available here:
+ *
+ * GetProductInfo() Function
+ * http://msdn2.microsoft.com/en-us/library/ms724358.aspx
+ */
+#define PRODUCT_BUSINESS                        0x00000006  /* Business Edition */
+#define PRODUCT_BUSINESS_N                      0x00000010  /* Business Edition */
+#define PRODUCT_CLUSTER_SERVER                  0x00000012  /* Cluster Server Edition */
+#define PRODUCT_DATACENTER_SERVER               0x00000008  /* Server Datacenter Edition (full installation) */
+#define PRODUCT_DATACENTER_SERVER_CORE          0x0000000C  /* Server Datacenter Edition (core installation) */
+#define PRODUCT_ENTERPRISE                      0x00000004  /* Enterprise Edition */
+#define PRODUCT_ENTERPRISE_N                    0x0000001B  /* Enterprise Edition */
+#define PRODUCT_ENTERPRISE_SERVER               0x0000000A  /* Server Enterprise Edition (full installation) */
+#define PRODUCT_ENTERPRISE_SERVER_CORE          0x0000000E  /* Server Enterprise Edition (core installation) */
+#define PRODUCT_ENTERPRISE_SERVER_IA64          0x0000000F  /* Server Enterprise Edition for Itanium-based Systems */
+#define PRODUCT_HOME_BASIC                      0x00000002  /* Home Basic Edition */
+#define PRODUCT_HOME_BASIC_N                    0x00000005  /* Home Basic Edition */
+#define PRODUCT_HOME_PREMIUM                    0x00000003  /* Home Premium Edition */
+#define PRODUCT_HOME_PREMIUM_N                  0x0000001A  /* Home Premium Edition */
+#define PRODUCT_HOME_SERVER                     0x00000013  /* Home Server Edition */
+#define PRODUCT_SERVER_FOR_SMALLBUSINESS        0x00000018  /* Server for Small Business Edition */
+#define PRODUCT_SMALLBUSINESS_SERVER            0x00000009  /* Small Business Server */
+#define PRODUCT_SMALLBUSINESS_SERVER_PREMIUM    0x00000019  /* Small Business Server Premium Edition */
+#define PRODUCT_STANDARD_SERVER                 0x00000007  /* Server Standard Edition (full installation) */
+#define PRODUCT_STANDARD_SERVER_CORE            0x0000000D  /* Server Standard Edition (core installation) */
+#define PRODUCT_STARTER                         0x0000000B  /* Starter Edition */
+#define PRODUCT_STORAGE_ENTERPRISE_SERVER       0x00000017  /* Storage Server Enterprise Edition */
+#define PRODUCT_STORAGE_EXPRESS_SERVER          0x00000014  /* Storage Server Express Edition */
+#define PRODUCT_STORAGE_STANDARD_SERVER         0x00000015  /* Storage Server Standard Edition */
+#define PRODUCT_STORAGE_WORKGROUP_SERVER        0x00000016  /* Storage Server Workgroup Edition */
+#define PRODUCT_UNDEFINED                       0x00000000  /* An unknown product */
+#define PRODUCT_ULTIMATE                        0x00000001  /* Ultimate Edition */
+#define PRODUCT_ULTIMATE_N                      0x0000001C  /* Ultimate Edition */
+#define PRODUCT_WEB_SERVER                      0x00000011  /* Web Server Edition (full installation) */
+#define PRODUCT_WEB_SERVER_CORE                 0x0000001D  /* Web Server Edition (core installation) */
+#endif
+
+static BOOL
+get_string_version(push_string_t *str)
+{
+    OSVERSIONINFOEX osvi;
+    SYSTEM_INFO si;
+    PGPI pGPI;
+    PGNSI pGNSI;
+    BOOL bOsVersionInfoEx;
+    DWORD dwType;
+
+    ZeroMemory(&si, sizeof(SYSTEM_INFO));
+    ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
+
+    /*
+     * Try calling GetVersionEx using the OSVERSIONINFOEX structure.
+     * If that fails, try using the OSVERSIONINFO structure.
+     */
+    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
+    if( !(bOsVersionInfoEx = GetVersionEx ((OSVERSIONINFO *) &osvi)) )
+    {
+        osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
+        if (! GetVersionEx ( (OSVERSIONINFO *) &osvi) ) 
+            return FALSE;
+    }
+
+    /* Call GetNativeSystemInfo if supported or GetSystemInfo otherwise. */
+    pGNSI = (PGNSI)
+            GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), 
+            "GetNativeSystemInfo");
+    if (NULL != pGNSI)
+        pGNSI(&si);
+    else
+        GetSystemInfo(&si);
+
+    switch (osvi.dwPlatformId)
+    {
+    /* Test for the Windows NT product family. */
+    case VER_PLATFORM_WIN32_NT:
+        /* Test for the specific product. */
+        if (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
+        {
+            if (osvi.wProductType == VER_NT_WORKSTATION)
+                pushString(str, "Windows Vista ");
+            else
+                pushString(str, "Windows Server 2008 ");
+
+            pGPI = (PGPI) GetProcAddress(
+                GetModuleHandle(TEXT("kernel32.dll")),
+                "GetProductInfo");
+
+            pGPI( 6, 0, 0, 0, &dwType);
+            switch (dwType)
+            {
+            case PRODUCT_ULTIMATE:
+                pushString(str, "Ultimate Edition");
+                break;
+            case PRODUCT_HOME_PREMIUM:
+                pushString(str, "Home Premium Edition");
+                break;
+            case PRODUCT_HOME_BASIC:
+                pushString(str, "Home Basic Edition");
+                break;
+            case PRODUCT_ENTERPRISE:
+                pushString(str, "Enterprise Edition");
+                break;
+            case PRODUCT_BUSINESS:
+                pushString(str, "Business Edition");
+                break;
+            case PRODUCT_STARTER:
+                pushString(str, "Starter Edition");
+                break;
+            case PRODUCT_CLUSTER_SERVER:
+                pushString(str, "Cluster Server Edition");
+                break;
+            case PRODUCT_DATACENTER_SERVER:
+                pushString(str, "Datacenter Edition");
+                break;
+            case PRODUCT_DATACENTER_SERVER_CORE:
+                pushString(str, "Datacenter Edition (core installation)");
+                break;
+            case PRODUCT_ENTERPRISE_SERVER:
+                pushString(str, "Enterprise Edition");
+                break;
+            case PRODUCT_ENTERPRISE_SERVER_CORE:
+                pushString(str, "Enterprise Edition (core installation)");
+                break;
+            case PRODUCT_ENTERPRISE_SERVER_IA64:
+                pushString(str, "Enterprise Edition for Itanium-based Systems");
+                break;
+            case PRODUCT_SMALLBUSINESS_SERVER:
+                pushString(str, "Small Business Server");
+                break;
+            case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM:
+                pushString(str, "Small Business Server Premium Edition");
+                break;
+            case PRODUCT_STANDARD_SERVER:
+                pushString(str, "Standard Edition");
+                break;
+            case PRODUCT_STANDARD_SERVER_CORE:
+                pushString(str, "Standard Edition (core installation)");
+                break;
+            case PRODUCT_WEB_SERVER:
+                pushString(str, "Web Server Edition");
+                break;
+            }
+            if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64)
+                pushString(str,  ", 64-bit");
+            else
+            if (si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_INTEL)
+                pushString(str, ", 32-bit");
+            else
+                /* space for optional build number */
+                pushString(str, " ");
+        }
+        else
+        if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2 )
+        {
+            if( GetSystemMetrics(SM_SERVERR2) )
+                pushString(str, "Microsoft Windows Server 2003 \"R2\" ");
+            else
+            if ( osvi.wSuiteMask==VER_SUITE_STORAGE_SERVER )
+                pushString(str, "Windows Storage Server 2003 ");
+            else
+            if( osvi.wProductType == VER_NT_WORKSTATION &&
+                si.wProcessorArchitecture==PROCESSOR_ARCHITECTURE_AMD64)
+                pushString(str, "Microsoft Windows XP Professional x64 Edition ");
+            else
+                pushString(str, "Microsoft Windows Server 2003, ");
+
+            /* Test for the server type. */
+            if ( osvi.wProductType != VER_NT_WORKSTATION )
+            {
+                switch (si.wProcessorArchitecture)
+                {
+                case PROCESSOR_ARCHITECTURE_IA64:
+                    if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
+                       pushString(str, "Datacenter Edition for Itanium-based Systems ");
+                    else
+                    if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
+                       pushString(str, "Enterprise Edition for Itanium-based Systems ");
+                    break;
+
+                case PROCESSOR_ARCHITECTURE_AMD64:
+                    if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
+                        pushString(str, "Datacenter x64 Edition ");
+                    else
+                    if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
+                        pushString(str, "Enterprise x64 Edition ");
+                    else
+                        pushString(str, "Standard x64 Edition ");
+                    break;
+
+                default:
+                    if ( osvi.wSuiteMask & VER_SUITE_COMPUTE_SERVER)
+                        pushString(str, "Compute Cluster Edition ");
+                    else
+                    if ( osvi.wSuiteMask & VER_SUITE_DATACENTER)
+                        pushString(str, "Datacenter Edition ");
+                    else
+                    if ( osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
+                        pushString(str, "Enterprise Edition ");
+                    else
+                    if ( osvi.wSuiteMask & VER_SUITE_BLADE)
+                        pushString(str, "Web Edition ");
+                    else
+                        pushString(str, "Standard Edition ");
+                    break;
+                }
+            }
+        }
+        else
+        if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1 )
+        {
+            pushString(str, "Microsoft Windows XP ");
+            if( osvi.wSuiteMask & VER_SUITE_PERSONAL )
+                pushString(str, "Home Edition ");
+            else
+                pushString(str, "Professional ");
+        }
+        else
+        if ( osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0 )
+        {
+            pushString(str, "Microsoft Windows 2000 ");
+            if (osvi.wProductType == VER_NT_WORKSTATION)
+                pushString(str, "Professional ");
+            else 
+            if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
+                pushString(str, "Datacenter Server ");
+            else
+            if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
+                pushString(str, "Advanced Server ");
+            else
+                pushString(str, "Server ");
+        } else
+        if ( osvi.dwMajorVersion <= 4 )
+            pushString(str, "Microsoft Windows NT ");
+
+        /* Test for specific product on Windows NT 4.0 SP6 and later. */
+        if (bOsVersionInfoEx)
+        {
+            /* Test for the workstation type. */
+            switch (osvi.wProductType)
+            {
+            case VER_NT_WORKSTATION:
+                if (si.wProcessorArchitecture!=PROCESSOR_ARCHITECTURE_AMD64 &&
+                    osvi.dwMajorVersion == 4)
+                    pushString(str, "Workstation 4.0 ");
+                break;
+
+            case VER_NT_SERVER:
+            case VER_NT_DOMAIN_CONTROLLER:
+                if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
+                    pushString(str, "Server 4.0, Enterprise Edition ");
+                else
+                    pushString(str, "Server 4.0 ");
+                break;
+            }
+        }
+        /* Test for specific product on Windows NT 4.0 SP5 and earlier */
+        else  
+        {
+            HKEY hKey;
+            TCHAR szProductType[BUFSIZE];
+            DWORD dwBufLen=BUFSIZE*sizeof(TCHAR);
+            LONG lRet;
+
+            lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
+                TEXT("SYSTEM\\CurrentControlSet\\Control\\ProductOptions"),
+                0, KEY_QUERY_VALUE, &hKey);
+            if (lRet != ERROR_SUCCESS)
+                return FALSE;
+
+            lRet = RegQueryValueEx(hKey, TEXT("ProductType"), NULL, NULL,
+                (LPBYTE) szProductType, &dwBufLen);
+            RegCloseKey( hKey );
+
+            if ((lRet != ERROR_SUCCESS) || (dwBufLen > BUFSIZE*sizeof(TCHAR)))
+                return FALSE;
+
+            if (lstrcmpi(TEXT("WINNT"), szProductType) == 0)
+                pushString(str, "Workstation ");
+            else
+            if (lstrcmpi(TEXT("LANMANNT"), szProductType) == 0)
+                pushString(str, "Server ");
+            else
+            if (lstrcmpi( TEXT("SERVERNT"), szProductType) == 0)
+                pushString(str, "Advanced Server ");
+            else
+                pushString(str, "%d.%d ", osvi.dwMajorVersion, osvi.dwMinorVersion);
+        }
+
+        /* Display service pack (if any) and build number. */
+        if (osvi.dwMajorVersion == 4 && 
+            lstrcmpi(osvi.szCSDVersion, TEXT("Service Pack 6")) == 0)
+        { 
+            HKEY hKey;
+            LONG lRet;
+
+            /* Test for SP6 versus SP6a. */
+            lRet = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
+                TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Hotfix\\Q246009"),
+                0, KEY_QUERY_VALUE, &hKey );
+            if( lRet == ERROR_SUCCESS )
+                pushString(str, "Service Pack 6a (Build %d)\n", osvi.dwBuildNumber & 0xFFFF );         
+            else
+                /* Windows NT 4.0 prior to SP6a */
+                pushString(str, "%s (Build %d)\n", osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF);
+
+             RegCloseKey( hKey );
+        }
+        else /* not Windows NT 4.0 */
+            pushString(str, "%s (Build %d)\n", osvi.szCSDVersion, osvi.dwBuildNumber & 0xFFFF);
+
+        break;
+
+    /* Test for the Windows Me/98/95. */
+    case VER_PLATFORM_WIN32_WINDOWS:
+        if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
+        {
+            pushString(str, "Microsoft Windows 95");
+            if (osvi.szCSDVersion[1]=='C' || osvi.szCSDVersion[1]=='B')
+                pushString(str, " OSR2");
+        }
+        else
+        if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
+        {
+            pushString(str, "Microsoft Windows 98");
+            if (osvi.szCSDVersion[1]=='A' || osvi.szCSDVersion[1]=='B')
+                pushString(str, " SE");
+        } 
+        else
+        if (osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
+            pushString(str, "Microsoft Windows Millennium Edition\n");
+        break;
+
+    case VER_PLATFORM_WIN32s:
+        pushString(str, "Microsoft Win32s\n");
+        break;
+    }
+    return TRUE; 
+}
+
+const char *
+GetHostName(void)
+{
+/*----------------------------------------------------------------------------
+   Return the host name of this system.
+-----------------------------------------------------------------------------*/
+    push_string_t str;
+
+    ZeroMemory(&str, sizeof(str));
+    if (!get_string_version(&str)) {
+#ifndef GETHOSTNAME_LOCAL_DEBUG
+        pm_error("Unable to find out host name.");
+#endif
+        pushString(&str, "unknown");
+    }
+    return (const char *)_strdup(str.str);
+}
+
+#ifdef GETHOSTNAME_LOCAL_DEBUG
+int WINAPI WinMain(HINSTANCE hCurInst, HINSTANCE hPrevInst,
+                   LPSTR lpsCmdLine, int nCmdShow)
+{
+    char *hostName = (char *)GetHostName();
+
+    /* compile as ascii only (not UNICODE) */
+    MessageBox(NULL, hostName, TEXT("GetHostName"), MB_OK);
+    free(hostName);
+
+    return 0;
+}
+#endif
diff --git a/converter/ppm/ppmtompeg/headers/bitio.h b/converter/ppm/ppmtompeg/headers/bitio.h
index 89e61fbb..a24c21cd 100644
--- a/converter/ppm/ppmtompeg/headers/bitio.h
+++ b/converter/ppm/ppmtompeg/headers/bitio.h
@@ -60,9 +60,7 @@
 #define BIT_IO_INCLUDED
 
 
-/*==============*
- * HEADER FILES *
- *==============*/
+#include <stdio.h>
 
 #include "general.h"
 #include "ansi.h"
diff --git a/converter/ppm/ppmtompeg/headers/block.h b/converter/ppm/ppmtompeg/headers/block.h
index 46050492..22d306a1 100644
--- a/converter/ppm/ppmtompeg/headers/block.h
+++ b/converter/ppm/ppmtompeg/headers/block.h
@@ -1,3 +1,46 @@
+#ifndef BLOCK_H_INCLUDED
+
+#include "frame.h"
+#include "mtypes.h"
+
+/* DIFFERENCE FUNCTIONS */
+
+int32
+LumBlockMAD(const LumBlock * const currentBlockP,
+            const LumBlock * const motionBlockP,
+            int32            const bestSoFar);
+
+int32
+LumBlockMSE(const LumBlock * const currentBlockP,
+            const LumBlock * const motionBlockP,
+            int32            const bestSoFar);
+
+int32
+LumMotionError(const LumBlock * const currentBlockP,
+               MpegFrame *      const prev,
+               int              const by,
+               int              const bx,
+               vector           const m,
+               int32            const bestSoFar);
+
+int32
+LumAddMotionError(const LumBlock * const currentBlockP,
+                  const LumBlock * const blockSoFarP,
+                  MpegFrame *      const prev,
+                  int              const by,
+                  int              const bx,
+                  vector           const m,
+                  int32            const bestSoFar);
+
+int32
+LumMotionErrorSubSampled(const LumBlock * const currentBlockP,
+                         MpegFrame *      const prevFrame,
+                         int              const by,
+                         int              const bx,
+                         vector           const m,
+                         int              const startY,
+                         int              const startX);
+
 void
 ComputeDiffDCTs(MpegFrame * const current,
                 MpegFrame * const prev,
@@ -51,3 +94,4 @@ AddBMotionBlock(Block          block,
 void
 BlockifyFrame(MpegFrame * const frameP);
 
+#endif
diff --git a/converter/ppm/ppmtompeg/headers/byteorder.h b/converter/ppm/ppmtompeg/headers/byteorder.h
index 0070252a..e2d8030c 100644
--- a/converter/ppm/ppmtompeg/headers/byteorder.h
+++ b/converter/ppm/ppmtompeg/headers/byteorder.h
@@ -72,6 +72,8 @@
 #else
     /* let in.h handle it, if possible */		   
 #include <sys/types.h>
+#if !defined(WIN32) || defined(__CYGWIN__)
 #include <netinet/in.h>
+#endif
 #endif /* FORCE_LITTLE_ENDIAN */
 #endif /* FORCE_BIG_ENDIAN */
diff --git a/converter/ppm/ppmtompeg/headers/frame.h b/converter/ppm/ppmtompeg/headers/frame.h
index 6df3d19f..acd74419 100644
--- a/converter/ppm/ppmtompeg/headers/frame.h
+++ b/converter/ppm/ppmtompeg/headers/frame.h
@@ -130,18 +130,4 @@ Frame_Resize(MpegFrame * const omf,
              int         const outsize_x,
              int         const outsize_y);
 
-
-extern void	  Frame_Free _ANSI_ARGS_((MpegFrame * const frame));
-extern void	  Frame_Exit _ANSI_ARGS_((void));
-extern void	  Frame_AllocPPM _ANSI_ARGS_((MpegFrame * frame));
-extern void	  Frame_AllocYCC _ANSI_ARGS_((MpegFrame * const mf));
-extern void	  Frame_AllocDecoded _ANSI_ARGS_((MpegFrame * const frame,
-						  boolean const makeReference));
-extern void	  Frame_AllocHalf _ANSI_ARGS_((MpegFrame * const frame));
-extern void	  Frame_AllocBlocks _ANSI_ARGS_((MpegFrame * const mf));
-extern void	  Frame_Resize _ANSI_ARGS_((MpegFrame * const omf, MpegFrame * const mf,
-					    int const insize_x, int const insize_y,
-					    int const outsize_x, int const outsize_y));
-
-
-#endif /* FRAME_INCLUDED */
+#endif
diff --git a/converter/ppm/ppmtompeg/headers/frames.h b/converter/ppm/ppmtompeg/headers/frames.h
index 14304c48..f2bcf6ae 100644
--- a/converter/ppm/ppmtompeg/headers/frames.h
+++ b/converter/ppm/ppmtompeg/headers/frames.h
@@ -16,6 +16,7 @@
 #include "ansi.h"
 #include "mtypes.h"
 #include "mheaders.h"
+#include "iframe.h"
 #include "frame.h"
 
 
@@ -86,11 +87,13 @@ typedef struct dct_data_tye_struct {
   int fmotionX, fmotionY, bmotionX, bmotionY;
 } dct_data_type;
 
-void    EncodeYDC _ANSI_ARGS_((int32 const dc_term, int32 * const pred_term, BitBucket * const bb));
-void
-EncodeCDC(int32       const dc_term,
-          int32     * const pred_term,
-          BitBucket * const bb);
+
+/*==================*
+ * GLOBAL VARIABLES *
+ *==================*/
+
+extern Block    **dct, **dctr, **dctb;
+extern dct_data_type **dct_data;
 
 
 /*========*
@@ -101,63 +104,6 @@ EncodeCDC(int32       const dc_term,
 #define int_ceil_div(a,b,c)     ((b*(c = a/b) < a) ? (c+1) : c)
 #define int_floor_div(a,b,c)    ((b*(c = a/b) > a) ? (c-1) : c)
 
-/* assumes many things:
- * block indices are (y,x)
- * variables y_dc_pred, cr_dc_pred, and cb_dc_pred
- * flat block fb exists
- */
-#define GEN_I_BLOCK(frameType, frame, bb, mbAI, qscale) {                   \
-    boolean overflow, overflowChange=FALSE;                             \
-        int overflowValue = 0;                                              \
-        do {                                                                \
-      overflow =  Mpost_QuantZigBlock(dct[y][x], fb[0],                 \
-             qscale, TRUE)==MPOST_OVERFLOW;                     \
-          overflow |= Mpost_QuantZigBlock(dct[y][x+1], fb[1],               \
-                 qscale, TRUE)==MPOST_OVERFLOW;                     \
-      overflow |= Mpost_QuantZigBlock(dct[y+1][x], fb[2],               \
-                         qscale, TRUE)==MPOST_OVERFLOW;                     \
-      overflow |= Mpost_QuantZigBlock(dct[y+1][x+1], fb[3],             \
-                         qscale, TRUE)==MPOST_OVERFLOW;                     \
-      overflow |= Mpost_QuantZigBlock(dctb[y >> 1][x >> 1],             \
-                         fb[4], qscale, TRUE)==MPOST_OVERFLOW;              \
-      overflow |= Mpost_QuantZigBlock(dctr[y >> 1][x >> 1],             \
-             fb[5], qscale, TRUE)==MPOST_OVERFLOW;              \
-          if ((overflow) && (qscale!=31)) {                                 \
-           overflowChange = TRUE; overflowValue++;                          \
-       qscale++;                                                        \
-       } else overflow = FALSE;                                         \
-    } while (overflow);                                                 \
-        Mhead_GenMBHeader(bb,                           \
-            frameType /* pict_code_type */, mbAI /* addr_incr */,   \
-            qscale /* q_scale */,                               \
-            0 /* forw_f_code */, 0 /* back_f_code */,           \
-            0 /* horiz_forw_r */, 0 /* vert_forw_r */,          \
-            0 /* horiz_back_r */, 0 /* vert_back_r */,          \
-            0 /* motion_forw */, 0 /* m_horiz_forw */,          \
-            0 /* m_vert_forw */, 0 /* motion_back */,           \
-            0 /* m_horiz_back */, 0 /* m_vert_back */,          \
-            0 /* mb_pattern */, TRUE /* mb_intra */);           \
-                                        \
-    /* Y blocks */                              \
-        EncodeYDC(fb[0][0], &y_dc_pred, bb);                            \
-    Mpost_RLEHuffIBlock(fb[0], bb);                         \
-    EncodeYDC(fb[1][0], &y_dc_pred, bb);                        \
-        Mpost_RLEHuffIBlock(fb[1], bb);                             \
-    EncodeYDC(fb[2][0], &y_dc_pred, bb);                        \
-    Mpost_RLEHuffIBlock(fb[2], bb);                         \
-    EncodeYDC(fb[3][0], &y_dc_pred, bb);                        \
-    Mpost_RLEHuffIBlock(fb[3], bb);                         \
-                                        \
-    /* CB block */                              \
-    EncodeCDC(fb[4][0], &cb_dc_pred, bb);                   \
-    Mpost_RLEHuffIBlock(fb[4], bb);                     \
-                                        \
-    /* CR block */                              \
-    EncodeCDC(fb[5][0], &cr_dc_pred, bb);                   \
-    Mpost_RLEHuffIBlock(fb[5], bb);                     \
-    if (overflowChange) qscale -= overflowValue;                        \
-    }
-
 #define BLOCK_TO_FRAME_COORD(bx1, bx2, x1, x2) {    \
     x1 = (bx1)*DCTSIZE;             \
     x2 = (bx2)*DCTSIZE;             \
@@ -254,6 +200,9 @@ encodeMotionVector(int      const x,
  *===============================*/
 
 void
+AllocDctBlocks(void);
+
+void
 ComputeBMotionLumBlock(MpegFrame * const prev,
                        MpegFrame * const next,
                        int         const by,
@@ -271,8 +220,6 @@ BMotionSearch(const LumBlock * const currentBlockP,
               motion *         const motionP,
               int              const oldMode);
 
-void GenIFrame (BitBucket * const bb,
-                MpegFrame * const mf);
 void GenPFrame (BitBucket * const bb,
                 MpegFrame * const current,
                 MpegFrame * const prev);
@@ -280,11 +227,6 @@ void GenBFrame (BitBucket * const bb,
                 MpegFrame * const curr,
                 MpegFrame * const prev,
                 MpegFrame * const next);
-void    AllocDctBlocks _ANSI_ARGS_((void ));
-
-
-float
-IFrameTotalTime(void);
 
 float
 PFrameTotalTime(void);
@@ -293,11 +235,6 @@ float
 BFrameTotalTime(void);
 
 void
-ShowIFrameSummary(unsigned int const inputFrameBits, 
-                  unsigned int const totalBits, 
-                  FILE *       const fpointer);
-
-void
 ShowPFrameSummary(unsigned int const inputFrameBits, 
                   unsigned int const totalBits, 
                   FILE *       const fpointer);
@@ -307,87 +244,6 @@ ShowBFrameSummary(unsigned int const inputFrameBits,
                   unsigned int const totalBits, 
                   FILE *       const fpointer);
 
-/* DIFFERENCE FUNCTIONS */
-
-int32
-LumBlockMAD(const LumBlock * const currentBlockP,
-            const LumBlock * const motionBlockP,
-            int32            const bestSoFar);
-
-int32
-LumBlockMSE(const LumBlock * const currentBlockP,
-            const LumBlock * const motionBlockP,
-            int32            const bestSoFar);
-
-int32
-LumMotionError(const LumBlock * const currentBlockP,
-               MpegFrame *      const prev,
-               int              const by,
-               int              const bx,
-               vector           const m,
-               int32            const bestSoFar);
-
-int32
-LumAddMotionError(const LumBlock * const currentBlockP,
-                  const LumBlock * const blockSoFarP,
-                  MpegFrame *      const prev,
-                  int              const by,
-                  int              const bx,
-                  vector           const m,
-                  int32            const bestSoFar);
-
-int32
-LumMotionErrorA(const LumBlock * const currentBlockP,
-                MpegFrame *      const prevFrame,
-                int              const by,
-                int              const bx,
-                vector           const m,
-                int32            const bestSoFar);
-
-int32
-LumMotionErrorB(const LumBlock * const currentP,
-                MpegFrame *      const prevFrame,
-                int              const by,
-                int              const bx,
-                vector           const m,
-                int32            const bestSoFar);
-
-int32
-LumMotionErrorC(const LumBlock * const currentP,
-                MpegFrame *      const prevFrame,
-                int              const by,
-                int              const bx,
-                vector           const m,
-                int32            const bestSoFar);
-
-int32
-LumMotionErrorD(const LumBlock * const currentP,
-                MpegFrame *      const prevFrame,
-                int              const by,
-                int              const bx,
-                vector           const m,
-                int32            const bestSoFar);
-
-int32
-LumMotionErrorSubSampled(const LumBlock * const currentBlockP,
-                         MpegFrame *      const prevFrame,
-                         int              const by,
-                         int              const bx,
-                         vector           const m,
-                         int              const startY,
-                         int              const startX);
-
-void
-BlockComputeSNR(MpegFrame * const current,
-                float *     const snr,
-                float *     const psnr);
-
-int32
-time_elapsed(void);
-
-void
-AllocDctBlocks(void);
-
 /*==================*
  * GLOBAL VARIABLES *
  *==================*/
@@ -399,7 +255,7 @@ extern int gopSize;
 extern int slicesPerFrame;
 extern int blocksPerSlice;
 extern int referenceFrame;
-extern int specificsOn;
+extern boolean specificsOn;
 extern int quietTime;       /* shut up for at least quietTime seconds;
                  * negative means shut up forever
                  */
@@ -413,7 +269,7 @@ extern int  fCodeI,fCodeP,fCodeB;
 extern boolean    forceEncodeLast;
 extern int TIME_RATE;
 
-#endif /* FRAMES_INCLUDED */
+#endif
 
 
 /*
diff --git a/converter/ppm/ppmtompeg/headers/iframe.h b/converter/ppm/ppmtompeg/headers/iframe.h
new file mode 100644
index 00000000..c4f77c74
--- /dev/null
+++ b/converter/ppm/ppmtompeg/headers/iframe.h
@@ -0,0 +1,118 @@
+#ifndef IFRAME_H_INCLUDED
+#define IFRAME_H_INCLUDED
+
+#include "frame.h"
+
+void
+SetFCode(void);
+
+void
+SetSlicesPerFrame(int const number);
+
+void
+SetBlocksPerSlice(void);
+
+void
+SetIQScale(int const qI);
+
+int
+GetIQScale(void);
+
+void
+GenIFrame(BitBucket * const bb, 
+          MpegFrame * const current);
+
+void
+ResetIFrameStats(void);
+
+float
+IFrameTotalTime(void);
+
+
+void
+ShowIFrameSummary(unsigned int const inputFrameBits, 
+                  unsigned int const totalBits, 
+                  FILE *       const fpointer);
+
+void
+EncodeYDC(int32       const dc_term,
+          int32 *     const pred_term,
+          BitBucket * const bb);
+
+void
+EncodeCDC(int32       const dc_term,
+          int32     * const pred_term,
+          BitBucket * const bb);
+
+void
+BlockComputeSNR(MpegFrame * const current,
+                float *     const snr,
+                float *     const psnr);
+
+void
+WriteDecodedFrame(MpegFrame * const frame);
+
+void
+PrintItoIBitRate(int const numBits,
+                 int const frameNum);
+
+int32 time_elapsed(void);
+
+/* assumes many things:
+ * block indices are (y,x)
+ * variables y_dc_pred, cr_dc_pred, and cb_dc_pred
+ * flat block fb exists
+ */
+#define GEN_I_BLOCK(frameType, frame, bb, mbAI, qscale) {                   \
+    boolean overflow, overflowChange=FALSE;                             \
+        int overflowValue = 0;                                              \
+        do {                                                                \
+      overflow =  Mpost_QuantZigBlock(dct[y][x], fb[0],                 \
+             qscale, TRUE)==MPOST_OVERFLOW;                     \
+          overflow |= Mpost_QuantZigBlock(dct[y][x+1], fb[1],               \
+                 qscale, TRUE)==MPOST_OVERFLOW;                     \
+      overflow |= Mpost_QuantZigBlock(dct[y+1][x], fb[2],               \
+                         qscale, TRUE)==MPOST_OVERFLOW;                     \
+      overflow |= Mpost_QuantZigBlock(dct[y+1][x+1], fb[3],             \
+                         qscale, TRUE)==MPOST_OVERFLOW;                     \
+      overflow |= Mpost_QuantZigBlock(dctb[y >> 1][x >> 1],             \
+                         fb[4], qscale, TRUE)==MPOST_OVERFLOW;              \
+      overflow |= Mpost_QuantZigBlock(dctr[y >> 1][x >> 1],             \
+             fb[5], qscale, TRUE)==MPOST_OVERFLOW;              \
+          if ((overflow) && (qscale!=31)) {                                 \
+           overflowChange = TRUE; overflowValue++;                          \
+       qscale++;                                                        \
+       } else overflow = FALSE;                                         \
+    } while (overflow);                                                 \
+        Mhead_GenMBHeader(bb,                           \
+            frameType /* pict_code_type */, mbAI /* addr_incr */,   \
+            qscale /* q_scale */,                               \
+            0 /* forw_f_code */, 0 /* back_f_code */,           \
+            0 /* horiz_forw_r */, 0 /* vert_forw_r */,          \
+            0 /* horiz_back_r */, 0 /* vert_back_r */,          \
+            0 /* motion_forw */, 0 /* m_horiz_forw */,          \
+            0 /* m_vert_forw */, 0 /* motion_back */,           \
+            0 /* m_horiz_back */, 0 /* m_vert_back */,          \
+            0 /* mb_pattern */, TRUE /* mb_intra */);           \
+                                        \
+    /* Y blocks */                              \
+        EncodeYDC(fb[0][0], &y_dc_pred, bb);                            \
+    Mpost_RLEHuffIBlock(fb[0], bb);                         \
+    EncodeYDC(fb[1][0], &y_dc_pred, bb);                        \
+        Mpost_RLEHuffIBlock(fb[1], bb);                             \
+    EncodeYDC(fb[2][0], &y_dc_pred, bb);                        \
+    Mpost_RLEHuffIBlock(fb[2], bb);                         \
+    EncodeYDC(fb[3][0], &y_dc_pred, bb);                        \
+    Mpost_RLEHuffIBlock(fb[3], bb);                         \
+                                        \
+    /* CB block */                              \
+    EncodeCDC(fb[4][0], &cb_dc_pred, bb);                   \
+    Mpost_RLEHuffIBlock(fb[4], bb);                     \
+                                        \
+    /* CR block */                              \
+    EncodeCDC(fb[5][0], &cr_dc_pred, bb);                   \
+    Mpost_RLEHuffIBlock(fb[5], bb);                     \
+    if (overflowChange) qscale -= overflowValue;                        \
+    }
+
+#endif
diff --git a/converter/ppm/ppmtompeg/headers/motion_search.h b/converter/ppm/ppmtompeg/headers/motion_search.h
index ab83cbca..62f3abab 100644
--- a/converter/ppm/ppmtompeg/headers/motion_search.h
+++ b/converter/ppm/ppmtompeg/headers/motion_search.h
@@ -100,6 +100,9 @@ PMotionSearch(const LumBlock * const currentBlockP,
               int              const bx, 
               vector *         const motionP);
 
+void
+MotionSearchPreComputation(MpegFrame * const frameP);
+
 /*==================*
  * GLOBAL VARIABLES *
  *==================*/
diff --git a/converter/ppm/ppmtompeg/headers/mpeg.h b/converter/ppm/ppmtompeg/headers/mpeg.h
index 23875c2c..56862c42 100644
--- a/converter/ppm/ppmtompeg/headers/mpeg.h
+++ b/converter/ppm/ppmtompeg/headers/mpeg.h
@@ -90,8 +90,9 @@ void
 ReadDecodedRefFrame(MpegFrame *  const frameP, 
                     unsigned int const frameNumber);
 
-extern void	WriteDecodedFrame _ANSI_ARGS_((MpegFrame * const frame));
-extern void	SetBitRateFileName _ANSI_ARGS_((char *fileName));
+void
+SetBitRateFileName(const char * const fileName);
+
 extern void	SetFrameRate _ANSI_ARGS_((void));
 
 
diff --git a/converter/ppm/ppmtompeg/headers/mproto.h b/converter/ppm/ppmtompeg/headers/mproto.h
index c3b0f4b3..d8fefd84 100644
--- a/converter/ppm/ppmtompeg/headers/mproto.h
+++ b/converter/ppm/ppmtompeg/headers/mproto.h
@@ -74,7 +74,6 @@
 #include "bitio.h"
 
 
-#define DCTSIZE2    DCTSIZE*DCTSIZE
 typedef short DCTELEM;
 typedef DCTELEM DCTBLOCK[DCTSIZE2];
 
@@ -111,9 +110,6 @@ void	ReadEYUV _ANSI_ARGS_((MpegFrame * mf, FILE *fpointer, int width,
 boolean	ReadPPM _ANSI_ARGS_((MpegFrame *mf, FILE *fpointer));
 void PPMtoYCC _ANSI_ARGS_((MpegFrame * mf));
 
-void	MotionSearchPreComputation _ANSI_ARGS_((MpegFrame *frame));
-boolean	PMotionSearch _ANSI_ARGS_((LumBlock currentBlock, MpegFrame *prev,
-				   int by, int bx, int *motionY, int *motionX));
 void	ComputeHalfPixelData _ANSI_ARGS_((MpegFrame *frame));
 void mp_validate_size _ANSI_ARGS_((int *x, int *y));
 void AllocYCC _ANSI_ARGS_((MpegFrame * mf));
@@ -126,7 +122,3 @@ void j_rev_dct _ANSI_ARGS_((DCTBLOCK data ));
 void j_rev_dct_sparse _ANSI_ARGS_((DCTBLOCK data , int pos ));
 void j_rev_dct _ANSI_ARGS_((DCTBLOCK data ));
 
-/* block.c */
-void	BlockToData _ANSI_ARGS_((uint8 **data, Block block, int by, int bx));
-void	AddMotionBlock _ANSI_ARGS_((Block block, uint8 **prev, int by, int bx,
-		       int my, int mx));
diff --git a/converter/ppm/ppmtompeg/headers/param.h b/converter/ppm/ppmtompeg/headers/param.h
index 31be61ee..c7f57b44 100644
--- a/converter/ppm/ppmtompeg/headers/param.h
+++ b/converter/ppm/ppmtompeg/headers/param.h
@@ -1,30 +1,4 @@
-/*===========================================================================*
- * param.h								     *
- *									     *
- *	reading the parameter file					     *
- *									     *
- *===========================================================================*/
-
-/*
- * Copyright (c) 1995 The Regents of the University of California.
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice and the following
- * two paragraphs appear in all copies of this software.
- *
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- */
+/* COPYRIGHT information is at end of file */
 
 #include "pm_c_util.h"
 #include "ansi.h"
@@ -35,14 +9,21 @@
  * CONSTANTS *
  *===========*/
 
-#define MAX_MACHINES	    256
+#define MAX_MACHINES        256
 #ifndef MAXPATHLEN
 #define MAXPATHLEN  1024
 #endif
 
-#define	ENCODE_FRAMES	0
-#define COMBINE_GOPS	1
-#define COMBINE_FRAMES	2
+typedef enum {
+    ENCODE_FRAMES,
+        /* The regular, default function: Input is individual single unencoded
+           frames.
+        */
+    COMBINE_GOPS,
+        /* Input is pre-encoded GOPs */
+    COMBINE_FRAMES
+        /* Input is pre-encoded individual frames */
+} majorProgramFunction;
 
 
 struct params {
@@ -53,9 +34,9 @@ struct params {
 
 
 void
-ReadParamFile(const char *    const fileName, 
-              int             const function,
-              struct params * const paramP);
+ReadParamFile(const char *         const fileName, 
+              majorProgramFunction const function,
+              struct params *      const paramP);
 
 /*==================*
  * GLOBAL VARIABLES *
@@ -63,25 +44,47 @@ ReadParamFile(const char *    const fileName,
 
 /* All this stuff ought to be in a struct param instead */
 
-extern char	outputFileName[256];
-extern int	whichGOP;
+extern char outputFileName[256];
+extern int whichGOP;
 extern int numMachines;
-extern char	machineName[MAX_MACHINES][256];
-extern char	userName[MAX_MACHINES][256];
-extern char	executable[MAX_MACHINES][1024];
-extern char	remoteParamFile[MAX_MACHINES][1024];
-extern boolean	remote[MAX_MACHINES];
-extern char	currentPath[MAXPATHLEN];
-extern char	currentFramePath[MAXPATHLEN];
-extern char	currentGOPPath[MAXPATHLEN];
+extern char machineName[MAX_MACHINES][256];
+extern char userName[MAX_MACHINES][256];
+extern char executable[MAX_MACHINES][1024];
+extern char remoteParamFile[MAX_MACHINES][1024];
+extern boolean remote[MAX_MACHINES];
+extern char currentPath[MAXPATHLEN];
+extern char currentFramePath[MAXPATHLEN];
+extern char currentGOPPath[MAXPATHLEN];
 extern char inputConversion[1024];
 extern char yuvConversion[256];
-extern int  yuvWidth, yuvHeight;
-extern int  realWidth, realHeight;
+extern int yuvWidth, yuvHeight;
+extern int realWidth, realHeight;
 extern char ioConversion[1024];
 extern char slaveConversion[1024];
-extern FILE *bitRateFile;
+extern FILE * bitRateFile;
 extern boolean showBitRatePerFrame;
 extern boolean computeMVHist;
 extern const double VidRateNum[9];
 extern boolean keepTempFiles;
+
+
+/*
+ * Copyright (c) 1995 The Regents of the University of California.
+ * All rights reserved.
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice and the following
+ * two paragraphs appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
+ */
diff --git a/converter/ppm/ppmtompeg/headers/prototypes.h b/converter/ppm/ppmtompeg/headers/prototypes.h
index a284888f..b421af35 100644
--- a/converter/ppm/ppmtompeg/headers/prototypes.h
+++ b/converter/ppm/ppmtompeg/headers/prototypes.h
@@ -44,33 +44,26 @@ void    ResetBFrameStats _ANSI_ARGS_((void));
 void    ResetPFrameStats _ANSI_ARGS_((void));
 void SetSearchRange (int const pixelsP,
                      int const pixelsB);
-void    ResetIFrameStats _ANSI_ARGS_((void));
 void
 SetPixelSearch(const char * const searchType);
-void    SetIQScale _ANSI_ARGS_((int const qI));
 void    SetPQScale _ANSI_ARGS_((int qP));
 void    SetBQScale _ANSI_ARGS_((int qB));
-float   EstimateSecondsPerIFrame _ANSI_ARGS_((void));
 float   EstimateSecondsPerPFrame _ANSI_ARGS_((void));
 float   EstimateSecondsPerBFrame _ANSI_ARGS_((void));
 void    SetGOPSize _ANSI_ARGS_((int size));
 void
 SetStatFileName(const char * const fileName);
-void    SetSlicesPerFrame _ANSI_ARGS_((int const number));
-void    SetBlocksPerSlice _ANSI_ARGS_((void));
 
 
 void DCTFrame _ANSI_ARGS_((MpegFrame * mf));
 
 void PPMtoYCC _ANSI_ARGS_((MpegFrame * mf));
 
-void    MotionSearchPreComputation _ANSI_ARGS_((MpegFrame * const frame));
+void    MotionSearchPreComputation _ANSI_ARGS_((MpegFrame *frame));
 
 void    ComputeHalfPixelData _ANSI_ARGS_((MpegFrame *frame));
 void mp_validate_size _ANSI_ARGS_((int *x, int *y));
 
-extern void SetFCode _ANSI_ARGS_((void));
-
 
 /* psearch.c */
 void    ShowPMVHistogram _ANSI_ARGS_((FILE *fpointer));
diff --git a/converter/ppm/ppmtompeg/headers/subsample.h b/converter/ppm/ppmtompeg/headers/subsample.h
new file mode 100644
index 00000000..deedf251
--- /dev/null
+++ b/converter/ppm/ppmtompeg/headers/subsample.h
@@ -0,0 +1,39 @@
+#ifndef SUBSAMPLE_H_INCLUDED
+#define SUBSAMPLE_H_INCLUDED
+
+#include "frame.h"
+#include "mtypes.h"
+
+int32
+LumMotionErrorA(const LumBlock * const currentBlockP,
+                MpegFrame *      const prevFrame,
+                int              const by,
+                int              const bx,
+                vector           const m,
+                int32            const bestSoFar);
+
+int32
+LumMotionErrorB(const LumBlock * const currentP,
+                MpegFrame *      const prevFrame,
+                int              const by,
+                int              const bx,
+                vector           const m,
+                int32            const bestSoFar);
+
+int32
+LumMotionErrorC(const LumBlock * const currentP,
+                MpegFrame *      const prevFrame,
+                int              const by,
+                int              const bx,
+                vector           const m,
+                int32            const bestSoFar);
+
+int32
+LumMotionErrorD(const LumBlock * const currentP,
+                MpegFrame *      const prevFrame,
+                int              const by,
+                int              const bx,
+                vector           const m,
+                int32            const bestSoFar);
+
+#endif
diff --git a/converter/ppm/ppmtompeg/huff.h b/converter/ppm/ppmtompeg/huff.h
deleted file mode 100644
index 4d0b8840..00000000
--- a/converter/ppm/ppmtompeg/huff.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (c) 1995 The Regents of the University of California.
- * All rights reserved.
- *
- * Permission to use, copy, modify, and distribute this software and its
- * documentation for any purpose, without fee, and without written agreement is
- * hereby granted, provided that the above copyright notice and the following
- * two paragraphs appear in all copies of this software.
- *
- * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
- * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
- * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
- * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
- * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
- * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
- * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
- */
-
-/*  
- *  $Header: /n/charlie-brown/project/mm/mpeg/mpeg_dist/mpeg_encode/RCS/huff.h,v 1.2 1995/01/19 23:08:28 eyhung Exp $
- */
-
-/*  
- *  THIS FILE IS MACHINE GENERATED!  DO NOT EDIT!
- */
-#define HUFF_MAXRUN	32
-#define HUFF_MAXLEVEL	41
-
-extern int huff_maxlevel[];
-extern uint32 *huff_table[];
-extern int *huff_bits[];
diff --git a/converter/ppm/ppmtompeg/iframe.c b/converter/ppm/ppmtompeg/iframe.c
index f4d7665a..7552f413 100644
--- a/converter/ppm/ppmtompeg/iframe.c
+++ b/converter/ppm/ppmtompeg/iframe.c
@@ -11,10 +11,9 @@
  *  GetIQScale                               *
  *  ResetIFrameStats                             *
  *  ShowIFrameSummary                            *
- *  EstimateSecondsPerIFrame                         *
  *  EncodeYDC                                *
  *  EncodeCDC                                *
- *      time_elapsed                                                         *
+ *  time_elapsed                                                         *
  *                                       *
  *===========================================================================*/
 
@@ -43,11 +42,11 @@
  * HEADER FILES *
  *==============*/
 
+#include <time.h>  /* Defines CLOCKS_PER_SEC, if this system has clock() */
 
-#ifdef CLOCKS_PER_SEC
-#include <times.h>
-#else
-#include <sys/times.h>
+#ifndef CLOCKS_PER_SEC
+  /* System doesn't have clock(); we assume it has times() instead */
+  #include <sys/times.h>
 #endif
 
 #include <sys/types.h>
@@ -67,12 +66,14 @@
 #include "specifics.h"
 #include "opts.h"
 
+#include "iframe.h"
+
 /*==================*
  * STATIC VARIABLES *
  *==================*/
 
-static  int lastNumBits = 0;
-static  int lastIFrame = 0;
+static int lastNumBits = 0;
+static int lastIFrame = 0;
 static int numBlocks = 0;
 static int numBits;
 static int numFrames = 0;
@@ -128,24 +129,11 @@ int fCodeI, fCodeP, fCodeB;
 boolean printSNR = FALSE;
 boolean printMSE = FALSE;
 boolean decodeRefFrames = FALSE;
-Block **dct=NULL, **dctr=NULL, **dctb=NULL;
-dct_data_type   **dct_data; /* used in p/bframe.c */
 int  TIME_RATE;
 
 
-/*=====================*
- * EXPORTED PROCEDURES *
- *=====================*/
-extern void PrintItoIBitRate _ANSI_ARGS_((int const numBits, int const frameNum));
 
-/*===============================*
- * INTERNAL PROCEDURE prototypes *
- *===============================*/
-void AllocDctBlocks(void );
-int SetFCodeHelper (int const sr);
-void CalcDistortion (MpegFrame * const current, int const y, int const x);
-
-int
+static int
 SetFCodeHelper(int const SR) {
 
     int     range,fCode;
@@ -296,6 +284,68 @@ GetIQScale(void) {
 
 
 
+static void
+CalcDistortion(MpegFrame * const current,
+               int         const y,
+               int         const x) {
+
+    int qscale, distort=0;
+    Block decblk;
+    FlatBlock fblk;
+    int datarate = 0;
+  
+    for (qscale = 1; qscale < 32; qscale ++) {
+        distort = 0;
+        datarate = 0;
+        Mpost_QuantZigBlock(dct[y][x], fblk, qscale, TRUE);
+        Mpost_UnQuantZigBlock(fblk, decblk, qscale, TRUE);
+        if (collect_distortion_detailed) datarate += CalcRLEHuffLength(fblk);
+        mpeg_jrevdct((int16 *)decblk);
+        distort += mse(current->y_blocks[y][x], decblk);
+
+        Mpost_QuantZigBlock(dct[y][x+1], fblk, qscale, TRUE);
+        Mpost_UnQuantZigBlock(fblk, decblk, qscale, TRUE);
+        if (collect_distortion_detailed) datarate += CalcRLEHuffLength(fblk);
+        mpeg_jrevdct((int16 *)decblk);
+        distort += mse(current->y_blocks[y][x+1], decblk);
+
+        Mpost_QuantZigBlock(dct[y+1][x], fblk, qscale, TRUE);
+        Mpost_UnQuantZigBlock(fblk, decblk, qscale, TRUE);
+        if (collect_distortion_detailed) datarate += CalcRLEHuffLength(fblk);
+        mpeg_jrevdct((int16 *)decblk);
+        distort += mse(current->y_blocks[y+1][x], decblk);
+
+        Mpost_QuantZigBlock(dct[y+1][x+1], fblk, qscale, TRUE);
+        Mpost_UnQuantZigBlock(fblk, decblk, qscale, TRUE);
+        if (collect_distortion_detailed) datarate += CalcRLEHuffLength(fblk);
+        mpeg_jrevdct((int16 *)decblk);
+        distort += mse(current->y_blocks[y+1][x+1], decblk);
+
+        Mpost_QuantZigBlock(dctb[y >> 1][x >> 1], fblk, qscale, TRUE);
+        Mpost_UnQuantZigBlock(fblk, decblk, qscale, TRUE);
+        if (collect_distortion_detailed) datarate += CalcRLEHuffLength(fblk);
+        mpeg_jrevdct((int16 *)decblk);
+        distort += mse(current->cb_blocks[y>>1][x>>1], decblk);
+
+        Mpost_QuantZigBlock(dctr[y >> 1][x >> 1], fblk, qscale, TRUE);
+        Mpost_UnQuantZigBlock(fblk, decblk, qscale, TRUE);
+        if (collect_distortion_detailed) datarate += CalcRLEHuffLength(fblk);
+        mpeg_jrevdct((int16 *)decblk);
+        distort += mse(current->cr_blocks[y >> 1][x >> 1], decblk);
+
+        if (!collect_distortion_detailed) {
+            fprintf(distortion_fp, "\t%d\n", distort);
+        } else if (collect_distortion_detailed == 1) {
+            fprintf(distortion_fp, "\t%d\t%d\n", distort, datarate);
+        } else {
+            fprintf(fp_table_rate[qscale-1], "%d\n", datarate);
+            fprintf(fp_table_dist[qscale-1], "%d\n", distort);
+        }
+    }
+}
+
+
+
 /*===========================================================================*
  *
  * GenIFrame
@@ -618,24 +668,6 @@ ShowIFrameSummary(unsigned int const inputFrameBits,
 
 /*===========================================================================*
  *
- * EstimateSecondsPerIFrame
- *
- *  estimates the number of seconds required per I-frame
- *
- * RETURNS: seconds (floating point value)
- *
- * SIDE EFFECTS:    none
- *
- *===========================================================================*/
-float
-EstimateSecondsPerIFrame()
-{
-    return (float)totalTime/((float)TIME_RATE*(float)numFrames);
-}
-
-
-/*===========================================================================*
- *
  * EncodeYDC
  *
  *  Encode the DC portion of a DCT of a luminance block
@@ -926,53 +958,6 @@ PrintItoIBitRate(int const numBits,
 
 
 
-/*===========================================================================*
- *
- * AllocDctBlocks
- *
- *  allocate memory for dct blocks
- *
- * RETURNS: nothing
- *
- * SIDE EFFECTS:    creates dct, dctr, dctb
- *
- *===========================================================================*/
-void
-AllocDctBlocks(void) {
-    int dctx, dcty;
-    int i;
-
-    dctx = Fsize_x / DCTSIZE;
-    dcty = Fsize_y / DCTSIZE;
-
-    dct = (Block **) malloc(sizeof(Block *) * dcty);
-    ERRCHK(dct, "malloc");
-    for (i = 0; i < dcty; i++) {
-        dct[i] = (Block *) malloc(sizeof(Block) * dctx);
-        ERRCHK(dct[i], "malloc");
-    }
-
-    dct_data = (dct_data_type **) malloc(sizeof(dct_data_type *) * dcty);
-    ERRCHK(dct_data, "malloc");
-    for (i = 0; i < dcty; i++) {
-        dct_data[i] = (dct_data_type *) malloc(sizeof(dct_data_type) * dctx);
-        ERRCHK(dct[i], "malloc");
-    }
-
-    dctr = (Block **) malloc(sizeof(Block *) * (dcty >> 1));
-    dctb = (Block **) malloc(sizeof(Block *) * (dcty >> 1));
-    ERRCHK(dctr, "malloc");
-    ERRCHK(dctb, "malloc");
-    for (i = 0; i < (dcty >> 1); i++) {
-        dctr[i] = (Block *) malloc(sizeof(Block) * (dctx >> 1));
-        dctb[i] = (Block *) malloc(sizeof(Block) * (dctx >> 1));
-        ERRCHK(dctr[i], "malloc");
-        ERRCHK(dctb[i], "malloc");
-    }
-}
-
-
-
 /*======================================================================*
  *
  * time_elapsed
@@ -994,69 +979,3 @@ int32 time_elapsed(void) {
     return timeBuffer.tms_utime + timeBuffer.tms_stime;
 #endif
 }
-
-
-
-void
-CalcDistortion(MpegFrame * const current,
-               int         const y,
-               int         const x) {
-
-    int qscale, distort=0;
-    Block decblk;
-    FlatBlock fblk;
-    int datarate = 0;
-  
-    for (qscale = 1; qscale < 32; qscale ++) {
-        distort = 0;
-        datarate = 0;
-        Mpost_QuantZigBlock(dct[y][x], fblk, qscale, TRUE);
-        Mpost_UnQuantZigBlock(fblk, decblk, qscale, TRUE);
-        if (collect_distortion_detailed) datarate += CalcRLEHuffLength(fblk);
-        mpeg_jrevdct((int16 *)decblk);
-        distort += mse(current->y_blocks[y][x], decblk);
-
-        Mpost_QuantZigBlock(dct[y][x+1], fblk, qscale, TRUE);
-        Mpost_UnQuantZigBlock(fblk, decblk, qscale, TRUE);
-        if (collect_distortion_detailed) datarate += CalcRLEHuffLength(fblk);
-        mpeg_jrevdct((int16 *)decblk);
-        distort += mse(current->y_blocks[y][x+1], decblk);
-
-        Mpost_QuantZigBlock(dct[y+1][x], fblk, qscale, TRUE);
-        Mpost_UnQuantZigBlock(fblk, decblk, qscale, TRUE);
-        if (collect_distortion_detailed) datarate += CalcRLEHuffLength(fblk);
-        mpeg_jrevdct((int16 *)decblk);
-        distort += mse(current->y_blocks[y+1][x], decblk);
-
-        Mpost_QuantZigBlock(dct[y+1][x+1], fblk, qscale, TRUE);
-        Mpost_UnQuantZigBlock(fblk, decblk, qscale, TRUE);
-        if (collect_distortion_detailed) datarate += CalcRLEHuffLength(fblk);
-        mpeg_jrevdct((int16 *)decblk);
-        distort += mse(current->y_blocks[y+1][x+1], decblk);
-
-        Mpost_QuantZigBlock(dctb[y >> 1][x >> 1], fblk, qscale, TRUE);
-        Mpost_UnQuantZigBlock(fblk, decblk, qscale, TRUE);
-        if (collect_distortion_detailed) datarate += CalcRLEHuffLength(fblk);
-        mpeg_jrevdct((int16 *)decblk);
-        distort += mse(current->cb_blocks[y>>1][x>>1], decblk);
-
-        Mpost_QuantZigBlock(dctr[y >> 1][x >> 1], fblk, qscale, TRUE);
-        Mpost_UnQuantZigBlock(fblk, decblk, qscale, TRUE);
-        if (collect_distortion_detailed) datarate += CalcRLEHuffLength(fblk);
-        mpeg_jrevdct((int16 *)decblk);
-        distort += mse(current->cr_blocks[y >> 1][x >> 1], decblk);
-
-        if (!collect_distortion_detailed) {
-            fprintf(distortion_fp, "\t%d\n", distort);
-        } else if (collect_distortion_detailed == 1) {
-            fprintf(distortion_fp, "\t%d\t%d\n", distort, datarate);
-        } else {
-            fprintf(fp_table_rate[qscale-1], "%d\n", datarate);
-            fprintf(fp_table_dist[qscale-1], "%d\n", distort);
-        }
-    }
-}
-
-
-
-
diff --git a/converter/ppm/ppmtompeg/jpeg.c b/converter/ppm/ppmtompeg/jpeg.c
index b51cf083..a703cf39 100644
--- a/converter/ppm/ppmtompeg/jpeg.c
+++ b/converter/ppm/ppmtompeg/jpeg.c
@@ -15,6 +15,7 @@
  * HEADER FILES *
  *==============*/
 #define _XOPEN_SOURCE    /* Make sure stdio.h contains fileno() */
+#include <unistd.h>
 #include <stdio.h>
 #include "all.h"
 /* With the lossless jpeg patch applied to the Jpeg library
@@ -52,6 +53,17 @@ extern void jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
 #define HEADER_SIZE 607   /*JFIF header size used on output images*/
 
 
+static int
+minDctVScaledSize(struct jpeg_decompress_struct const cinfo) {
+
+#if JPEG_LIB_VERSION >= 70
+    return cinfo.min_DCT_v_scaled_size;
+#else
+    return cinfo.min_DCT_scaled_size;
+#endif
+}
+
+
 
 /*=======================================================================*
  *                                                                       *
@@ -416,11 +428,7 @@ ReadJPEG(MpegFrame * const mf,
      */
   
     /* set parameters for decompression */
-#ifdef JPEG4
-    cinfo.want_raw_output = TRUE;
-#else
     cinfo.raw_data_out = TRUE;
-#endif
     cinfo.out_color_space = JCS_YCbCr;
   
     /* calculate image output dimensions */
@@ -466,13 +474,7 @@ ReadJPEG(MpegFrame * const mf,
     /* Make an 8-row-high sample array that will go away when done
        with image
     */
-#ifdef JPEG4
-    buffer_height = 8;  /* could be 2, 4,8 rows high */
-#elif JPEG_LIB_VERSION >= 70
-    buffer_height = cinfo.max_v_samp_factor * cinfo.min_DCT_v_scaled_size;
-#else
-    buffer_height = cinfo.max_v_samp_factor * cinfo.min_DCT_scaled_size;
-#endif
+    buffer_height = cinfo.max_v_samp_factor * minDctVScaledSize(cinfo);
   
     for(cp=0,compptr = cinfo.comp_info;cp<cinfo.num_components;
         cp++,compptr++) {
@@ -496,11 +498,7 @@ ReadJPEG(MpegFrame * const mf,
 
     while (cinfo.output_scanline < cinfo.output_height) {
 
-#ifdef JPEG4
-        (void) jpeg_read_raw_scanlines(&cinfo, scanarray, buffer_height);
-#else
         (void) jpeg_read_raw_data(&cinfo, scanarray, buffer_height);
-#endif
 
         /* alter subsample ratio's if neccessary */
         if ((h_samp[0]==2) && (h_samp[1]==1) && (h_samp[2]==1) &&
diff --git a/converter/ppm/ppmtompeg/mheaders.c b/converter/ppm/ppmtompeg/mheaders.c
index 8a51c089..4cfe49ac 100644
--- a/converter/ppm/ppmtompeg/mheaders.c
+++ b/converter/ppm/ppmtompeg/mheaders.c
@@ -278,24 +278,350 @@ const double VidRateNum[9]={1.0, 23.976, 24.0, 25.0, 29.97, 30.0,
                              50.0 ,59.94, 60.0};
 
 
-/*===============================*
- * INTERNAL PROCEDURE prototypes *
- *===============================*/
-
-static void	GenMBAddrIncr _ANSI_ARGS_((BitBucket *bb, uint32 addr_incr));
-static void	GenPictHead _ANSI_ARGS_((BitBucket *bb, uint32 temp_ref,
-		    uint32 code_type, uint32 vbv_delay,
-		    int32 full_pel_forw_flag, uint32 forw_f_code,
-		    int32 full_pel_back_flag, uint32 back_f_code,
-		    uint8 *extra_info, uint32 extra_info_size,
-		    uint8 *ext_data, uint32 ext_data_size,
-		    uint8 *user_data, uint32 user_data_size));
-static void	GenMBType _ANSI_ARGS_((BitBucket *bb, uint32 pict_code_type,
-		  uint32 mb_quant, uint32 motion_forw, uint32 motion_back,
-		  uint32 mb_pattern, uint32 mb_intra));
-static void	GenMotionCode _ANSI_ARGS_((BitBucket * const bb, int32 const vector));
-static void	GenBlockPattern _ANSI_ARGS_((BitBucket *bb,
-					     uint32 mb_pattern));
+/*=====================*
+ * INTERNAL PROCEDURES *
+ *=====================*/
+
+/*===========================================================================*
+ *
+ * GenMBType
+ *
+ *	generate macroblock type with given attributes
+ *	append result to the specified bitstream
+ *
+ * RETURNS:	nothing
+ *
+ * SIDE EFFECTS:    none
+ *
+ *===========================================================================*/
+static void
+GenMBType(bbPtr, pict_code_type, mb_quant, motion_forw, motion_back,
+          mb_pattern, mb_intra)
+    BitBucket *bbPtr;
+    uint32 pict_code_type;
+    uint32 mb_quant;
+    uint32 motion_forw;
+    uint32 motion_back;
+    uint32 mb_pattern;
+    uint32 mb_intra;
+{
+    int code;
+
+    switch (pict_code_type) {
+    case 1:
+        if ((motion_forw != 0) || (motion_back != 0) || (mb_pattern != 0) || (mb_intra != 1)) {
+            perror("Illegal parameters for macroblock type.");
+            exit(-1);
+        }
+        if (mb_quant) {
+            Bitio_Write(bbPtr, 0x1, 2);
+        } else {
+            Bitio_Write(bbPtr, 0x1, 1);
+        }
+        break;
+
+    case 2:
+        code = 0;
+        if (mb_quant) {
+            code += 16;
+        }
+        if (motion_forw) {
+            code += 8;
+        }
+        if (motion_back) {
+            code += 4;
+        }
+        if (mb_pattern) {
+            code += 2;
+        }
+        if (mb_intra) {
+            code += 1;
+        }
+
+        switch (code) {
+        case 1:
+            Bitio_Write(bbPtr, 0x3, 5);
+            break;
+        case 2:
+            Bitio_Write(bbPtr, 0x1, 2);
+            break;
+        case 8:
+            Bitio_Write(bbPtr, 0x1, 3);
+            break;
+        case 10:
+            Bitio_Write(bbPtr, 0x1, 1);
+            break;
+        case 17:
+            Bitio_Write(bbPtr, 0x1, 6);
+            break;
+        case 18:
+            Bitio_Write(bbPtr, 0x1, 5);
+            break;
+        case 26:
+            Bitio_Write(bbPtr, 0x2, 5);
+            break;
+        default:
+            perror("Illegal parameters for macroblock type.");
+            exit(-1);
+            break;
+        }
+        break;
+
+    case 3:
+        code = 0;
+        if (mb_quant) {
+            code += 16;
+        }
+        if (motion_forw) {
+            code += 8;
+        }
+        if (motion_back) {
+            code += 4;
+        }
+        if (mb_pattern) {
+            code += 2;
+        }
+        if (mb_intra) {
+            code += 1;
+        }
+
+        switch (code) {
+        case 12:
+            Bitio_Write(bbPtr, 0x2, 2);
+            break;
+        case 14:
+            Bitio_Write(bbPtr, 0x3, 2);
+            break;
+        case 4:
+            Bitio_Write(bbPtr, 0x2, 3);
+            break;
+        case 6:
+            Bitio_Write(bbPtr, 0x3, 3);
+            break;
+        case 8:
+            Bitio_Write(bbPtr, 0x2, 4);
+            break;
+        case 10:
+            Bitio_Write(bbPtr, 0x3, 4);
+            break;
+        case 1:
+            Bitio_Write(bbPtr, 0x3, 5);
+            break;
+        case 30:
+            Bitio_Write(bbPtr, 0x2, 5);
+            break;
+        case 26:
+            Bitio_Write(bbPtr, 0x3, 6);
+            break;
+        case 22:
+            Bitio_Write(bbPtr, 0x2, 6);
+            break;
+        case 17:
+            Bitio_Write(bbPtr, 0x1, 6);
+            break;
+        default:
+            perror("Illegal parameters for macroblock type.");
+            exit(-1);
+            break;
+        }
+        break;
+    }
+}
+
+
+/*===========================================================================*
+ *
+ * GenMotionCode
+ *
+ *	generate motion vector output with given value
+ *	append result to the specified bitstream
+ *
+ * RETURNS:	nothing
+ *
+ * SIDE EFFECTS:    none
+ *
+ *===========================================================================*/
+static void
+GenMotionCode(BitBucket * const bbPtr,
+              int32       const vector) {
+
+    uint32 code, num;
+
+    if ((vector < -16) || (vector > 16)) {
+        perror("Motion vector out of range.");
+        fprintf(stderr, "Motion vector out of range:  vector = %d\n", vector);
+        exit(-1);
+    }
+    code = mbMotionVectorTable[vector + 16][0];
+    num = mbMotionVectorTable[vector + 16][1];
+
+    Bitio_Write(bbPtr, code, num);
+}
+
+
+/*===========================================================================*
+ *
+ * GenBlockPattern
+ *
+ *	generate macroblock pattern output
+ *	append result to the specified bitstream
+ *
+ * RETURNS:	nothing
+ *
+ * SIDE EFFECTS:    none
+ *
+ *===========================================================================*/
+static void
+GenBlockPattern(bbPtr, mb_pattern)
+    BitBucket *bbPtr;
+    uint32 mb_pattern;
+{
+    uint32 code, num;
+
+    code = mbPatTable[mb_pattern][0];
+    num = mbPatTable[mb_pattern][1];
+
+    Bitio_Write(bbPtr, code, num);
+}
+
+
+/*===========================================================================*
+ *
+ * GenMBAddrIncr
+ *
+ *	generate macroblock address increment output
+ *	append result to the specified bitstream
+ *
+ * RETURNS:	nothing
+ *
+ * SIDE EFFECTS:    none
+ *
+ *===========================================================================*/
+static void
+GenMBAddrIncr(bbPtr, addr_incr)
+    BitBucket *bbPtr;
+    uint32 addr_incr;
+{
+    uint32 code;
+    uint32 num;
+
+    code = mbAddrIncrTable[addr_incr][0];
+    num = mbAddrIncrTable[addr_incr][1];
+
+    Bitio_Write(bbPtr, code, num);
+}
+
+
+/*===========================================================================*
+ *
+ * GenPictHead
+ *
+ *	generate picture header with given attributes
+ *	append result to the specified bitstream
+ *
+ * RETURNS:	nothing
+ *
+ * SIDE EFFECTS:    none
+ *
+ *===========================================================================*/
+static void
+GenPictHead(bbPtr, temp_ref, code_type, vbv_delay, full_pel_forw_flag,
+            forw_f_code, full_pel_back_flag, back_f_code, extra_info,
+            extra_info_size, ext_data, ext_data_size, user_data,
+            user_data_size)
+    BitBucket *bbPtr;
+    uint32 temp_ref;
+    uint32 code_type;
+    uint32 vbv_delay;
+    int32 full_pel_forw_flag;
+    uint32 forw_f_code;
+    int32 full_pel_back_flag;
+    uint32 back_f_code;
+    uint8 *extra_info;
+    uint32 extra_info_size;
+    uint8 *ext_data;
+    uint32 ext_data_size;
+    uint8 *user_data;
+    uint32 user_data_size;
+{
+    /* Write picture start code. */
+    Bitio_Write(bbPtr, PICT_START_CODE, 32);
+
+    /* Temp reference. */
+    Bitio_Write(bbPtr, temp_ref, 10);
+
+    /* Code_type. */
+    if (code_type == 0)
+        code_type = 1;
+
+    Bitio_Write(bbPtr, code_type, 3);
+
+    /* vbv_delay. */
+    vbv_delay = 0xffff;		    /* see page 36 (section 2.4.3.4) */
+    Bitio_Write(bbPtr, vbv_delay, 16);
+
+    if ((code_type == 2) || (code_type == 3)) {
+
+        /* Full pel forw flag. */
+
+        if (full_pel_forw_flag)
+            Bitio_Write(bbPtr, 0x01, 1);
+        else
+            Bitio_Write(bbPtr, 0x00, 1);
+
+        /* Forw f code. */
+
+        Bitio_Write(bbPtr, forw_f_code, 3);
+    }
+    if (code_type == 3) {
+
+        /* Full pel back flag. */
+
+        if (full_pel_back_flag)
+            Bitio_Write(bbPtr, 0x01, 1);
+        else
+            Bitio_Write(bbPtr, 0x00, 1);
+
+        /* Back f code. */
+
+        Bitio_Write(bbPtr, back_f_code, 3);
+    }
+    /* Extra bit picture info. */
+
+    if (extra_info != NULL) {
+        unsigned int i;
+        for (i = 0; i < extra_info_size; ++i) {
+            Bitio_Write(bbPtr, 0x01, 1);
+            Bitio_Write(bbPtr, extra_info[i], 8);
+        }
+    }
+    Bitio_Write(bbPtr, 0x00, 1);
+
+    /* next start code */
+    Bitio_BytePad(bbPtr);
+
+    /* Write ext data if present. */
+
+    if (ext_data != NULL) {
+        unsigned int i;
+
+        Bitio_Write(bbPtr, EXT_START_CODE, 32);
+
+        for (i = 0; i < ext_data_size; ++i)
+            Bitio_Write(bbPtr, ext_data[i], 8);
+        Bitio_BytePad(bbPtr);
+    }
+    /* Write user data if present. */
+    if (user_data != NULL) {
+        unsigned int i;
+        Bitio_Write(bbPtr, USER_START_CODE, 32);
+
+        for (i = 0; i < user_data_size; ++i)
+            Bitio_Write(bbPtr, user_data[i], 8);
+
+        Bitio_BytePad(bbPtr);
+    }
+}
 
 
 /*=====================*
@@ -767,7 +1093,8 @@ if ( addr_incr != 1 )
     }
 
     /* Generate mb type code. */
-    GenMBType(bbPtr, pict_code_type, mb_quant, motion_forw, motion_back, mb_pattern, mb_intra);
+    GenMBType(bbPtr, pict_code_type, mb_quant,
+              motion_forw, motion_back, mb_pattern, mb_intra);
 
     /* MB quant. */
     if (mb_quant) {
@@ -831,353 +1158,6 @@ if ( addr_incr != 1 )
 }
 
 
-/*=====================*
- * INTERNAL PROCEDURES *
- *=====================*/
-
-/*===========================================================================*
- *
- * GenMBType
- *
- *	generate macroblock type with given attributes
- *	append result to the specified bitstream
- *
- * RETURNS:	nothing
- *
- * SIDE EFFECTS:    none
- *
- *===========================================================================*/
-static void
-GenMBType(bbPtr, pict_code_type, mb_quant, motion_forw, motion_back,
-	  mb_pattern, mb_intra)
-    BitBucket *bbPtr;
-    uint32 pict_code_type;
-    uint32 mb_quant;
-    uint32 motion_forw;
-    uint32 motion_back;
-    uint32 mb_pattern;
-    uint32 mb_intra;
-{
-    int code;
-
-    switch (pict_code_type) {
-    case 1:
-	if ((motion_forw != 0) || (motion_back != 0) || (mb_pattern != 0) || (mb_intra != 1)) {
-	    perror("Illegal parameters for macroblock type.");
-	    exit(-1);
-	}
-	if (mb_quant) {
-	    Bitio_Write(bbPtr, 0x1, 2);
-	} else {
-	    Bitio_Write(bbPtr, 0x1, 1);
-	}
-	break;
-
-    case 2:
-	code = 0;
-	if (mb_quant) {
-	    code += 16;
-	}
-	if (motion_forw) {
-	    code += 8;
-	}
-	if (motion_back) {
-	    code += 4;
-	}
-	if (mb_pattern) {
-	    code += 2;
-	}
-	if (mb_intra) {
-	    code += 1;
-	}
-
-	switch (code) {
-	case 1:
-	    Bitio_Write(bbPtr, 0x3, 5);
-	    break;
-	case 2:
-	    Bitio_Write(bbPtr, 0x1, 2);
-	    break;
-	case 8:
-	    Bitio_Write(bbPtr, 0x1, 3);
-	    break;
-	case 10:
-	    Bitio_Write(bbPtr, 0x1, 1);
-	    break;
-	case 17:
-	    Bitio_Write(bbPtr, 0x1, 6);
-	    break;
-	case 18:
-	    Bitio_Write(bbPtr, 0x1, 5);
-	    break;
-	case 26:
-	    Bitio_Write(bbPtr, 0x2, 5);
-	    break;
-	default:
-	    perror("Illegal parameters for macroblock type.");
-	    exit(-1);
-	    break;
-	}
-	break;
-
-    case 3:
-	code = 0;
-	if (mb_quant) {
-	    code += 16;
-	}
-	if (motion_forw) {
-	    code += 8;
-	}
-	if (motion_back) {
-	    code += 4;
-	}
-	if (mb_pattern) {
-	    code += 2;
-	}
-	if (mb_intra) {
-	    code += 1;
-	}
-
-	switch (code) {
-	case 12:
-	    Bitio_Write(bbPtr, 0x2, 2);
-	    break;
-	case 14:
-	    Bitio_Write(bbPtr, 0x3, 2);
-	    break;
-	case 4:
-	    Bitio_Write(bbPtr, 0x2, 3);
-	    break;
-	case 6:
-	    Bitio_Write(bbPtr, 0x3, 3);
-	    break;
-	case 8:
-	    Bitio_Write(bbPtr, 0x2, 4);
-	    break;
-	case 10:
-	    Bitio_Write(bbPtr, 0x3, 4);
-	    break;
-	case 1:
-	    Bitio_Write(bbPtr, 0x3, 5);
-	    break;
-	case 30:
-	    Bitio_Write(bbPtr, 0x2, 5);
-	    break;
-	case 26:
-	    Bitio_Write(bbPtr, 0x3, 6);
-	    break;
-	case 22:
-	    Bitio_Write(bbPtr, 0x2, 6);
-	    break;
-	case 17:
-	    Bitio_Write(bbPtr, 0x1, 6);
-	    break;
-	default:
-	    perror("Illegal parameters for macroblock type.");
-	    exit(-1);
-	    break;
-	}
-	break;
-    }
-}
-
-
-/*===========================================================================*
- *
- * GenMotionCode
- *
- *	generate motion vector output with given value
- *	append result to the specified bitstream
- *
- * RETURNS:	nothing
- *
- * SIDE EFFECTS:    none
- *
- *===========================================================================*/
-static void
-GenMotionCode(BitBucket * const bbPtr,
-              int32       const vector) {
-
-    uint32 code, num;
-
-    if ((vector < -16) || (vector > 16)) {
-	perror("Motion vector out of range.");
-	fprintf(stderr, "Motion vector out of range:  vector = %d\n", vector);
-	exit(-1);
-    }
-    code = mbMotionVectorTable[vector + 16][0];
-    num = mbMotionVectorTable[vector + 16][1];
-
-    Bitio_Write(bbPtr, code, num);
-}
-
-
-/*===========================================================================*
- *
- * GenBlockPattern
- *
- *	generate macroblock pattern output
- *	append result to the specified bitstream
- *
- * RETURNS:	nothing
- *
- * SIDE EFFECTS:    none
- *
- *===========================================================================*/
-static void
-GenBlockPattern(bbPtr, mb_pattern)
-    BitBucket *bbPtr;
-    uint32 mb_pattern;
-{
-    uint32 code, num;
-
-    code = mbPatTable[mb_pattern][0];
-    num = mbPatTable[mb_pattern][1];
-
-    Bitio_Write(bbPtr, code, num);
-}
-
-
-/*===========================================================================*
- *
- * GenMBAddrIncr
- *
- *	generate macroblock address increment output
- *	append result to the specified bitstream
- *
- * RETURNS:	nothing
- *
- * SIDE EFFECTS:    none
- *
- *===========================================================================*/
-static void
-GenMBAddrIncr(bbPtr, addr_incr)
-    BitBucket *bbPtr;
-    uint32 addr_incr;
-{
-    uint32 code;
-    uint32 num;
-
-    code = mbAddrIncrTable[addr_incr][0];
-    num = mbAddrIncrTable[addr_incr][1];
-
-    Bitio_Write(bbPtr, code, num);
-}
-
-
-/*===========================================================================*
- *
- * GenPictHead
- *
- *	generate picture header with given attributes
- *	append result to the specified bitstream
- *
- * RETURNS:	nothing
- *
- * SIDE EFFECTS:    none
- *
- *===========================================================================*/
-static void
-GenPictHead(bbPtr, temp_ref, code_type, vbv_delay, full_pel_forw_flag,
-	    forw_f_code, full_pel_back_flag, back_f_code, extra_info,
-	    extra_info_size, ext_data, ext_data_size, user_data,
-	    user_data_size)
-    BitBucket *bbPtr;
-    uint32 temp_ref;
-    uint32 code_type;
-    uint32 vbv_delay;
-    int32 full_pel_forw_flag;
-    uint32 forw_f_code;
-    int32 full_pel_back_flag;
-    uint32 back_f_code;
-    uint8 *extra_info;
-    uint32 extra_info_size;
-    uint8 *ext_data;
-    uint32 ext_data_size;
-    uint8 *user_data;
-    uint32 user_data_size;
-{
-    int i;
-
-    /* Write picture start code. */
-    Bitio_Write(bbPtr, PICT_START_CODE, 32);
-
-    /* Temp reference. */
-    Bitio_Write(bbPtr, temp_ref, 10);
-
-    /* Code_type. */
-    if (code_type == 0) {
-	code_type = 1;
-    }
-    Bitio_Write(bbPtr, code_type, 3);
-
-    /* vbv_delay. */
-    vbv_delay = 0xffff;		    /* see page 36 (section 2.4.3.4) */
-    Bitio_Write(bbPtr, vbv_delay, 16);
-
-    if ((code_type == 2) || (code_type == 3)) {
-
-	/* Full pel forw flag. */
-
-	if (full_pel_forw_flag) {
-	    Bitio_Write(bbPtr, 0x01, 1);
-	} else {
-	    Bitio_Write(bbPtr, 0x00, 1);
-	}
-
-	/* Forw f code. */
-
-	Bitio_Write(bbPtr, forw_f_code, 3);
-    }
-    if (code_type == 3) {
-
-	/* Full pel back flag. */
-
-	if (full_pel_back_flag) {
-	    Bitio_Write(bbPtr, 0x01, 1);
-	} else {
-	    Bitio_Write(bbPtr, 0x00, 1);
-	}
-
-	/* Back f code. */
-
-	Bitio_Write(bbPtr, back_f_code, 3);
-    }
-    /* Extra bit picture info. */
-
-    if (extra_info != NULL) {
-	for (i = 0; i < extra_info_size; i++) {
-	    Bitio_Write(bbPtr, 0x01, 1);
-	    Bitio_Write(bbPtr, extra_info[i], 8);
-	}
-    }
-    Bitio_Write(bbPtr, 0x00, 1);
-
-    /* next start code */
-    Bitio_BytePad(bbPtr);
-
-    /* Write ext data if present. */
-
-    if (ext_data != NULL) {
-	Bitio_Write(bbPtr, EXT_START_CODE, 32);
-
-	for (i = 0; i < ext_data_size; i++) {
-	    Bitio_Write(bbPtr, ext_data[i], 8);
-	}
-	Bitio_BytePad(bbPtr);
-    }
-    /* Write user data if present. */
-    if (user_data != NULL) {
-	Bitio_Write(bbPtr, USER_START_CODE, 32);
-
-	for (i = 0; i < user_data_size; i++) {
-	    Bitio_Write(bbPtr, user_data[i], 8);
-	}
-	Bitio_BytePad(bbPtr);
-    }
-}
-
-
 #ifdef UNUSED_PROCEDURES
 
 /* GenMBEnd only used for `D` pictures. Shouldn't really ever be called. */
diff --git a/converter/ppm/ppmtompeg/mpeg.c b/converter/ppm/ppmtompeg/mpeg.c
index fafbb97a..6557f377 100644
--- a/converter/ppm/ppmtompeg/mpeg.c
+++ b/converter/ppm/ppmtompeg/mpeg.c
@@ -43,8 +43,8 @@
 #endif
 #include <sys/stat.h>
 
-#include "ppm.h"
 #include "nstring.h"
+#include "nsleep.h"
 
 #include "mtypes.h"
 #include "frames.h"
@@ -276,9 +276,8 @@ SetReferenceFrameType(const char * const type) {
 
 
 void
-SetBitRateFileName(fileName)
-    char *fileName;
-{
+SetBitRateFileName(const char * const fileName) {
+
     strcpy(bitRateFileName, fileName);
 }
 
@@ -318,7 +317,7 @@ finishFrameOutput(MpegFrame * const frameP,
 
 static void
 outputIFrame(MpegFrame * const frameP,
-             BitBucket * const bb,
+             BitBucket * const bbP,
              int         const realStart,
              int         const realEnd,
              MpegFrame * const pastRefFrameP,
@@ -326,7 +325,7 @@ outputIFrame(MpegFrame * const frameP,
       
     /* only start a new GOP with I */
     /* don't start GOP if only doing frames */
-    if ((!separateFiles) && (currentGOP >= gopSize)) {
+    if (!separateFiles && currentGOP >= gopSize) {
         boolean const closed = 
             (totalFramesSent == frameP->id || pastRefFrameP == NULL);
 
@@ -344,7 +343,7 @@ outputIFrame(MpegFrame * const frameP,
             }
       
             Mhead_GenSequenceHeader(
-                bb, Fsize_x, Fsize_y,
+                bbP, Fsize_x, Fsize_y,
                 /* pratio */    aspectRatio,
                 /* pict_rate */ frameRate, /* bit_rate */ bit_rate,
                 /* buf_size */  buf_size,  /* c_param_flag */ 1,
@@ -359,7 +358,7 @@ outputIFrame(MpegFrame * const frameP,
                        closed ? "YES" : "NO", frameP->id);
     
         ++num_gop;
-        Mhead_GenGOPHeader(bb,  /* drop_frame_flag */ 0,
+        Mhead_GenGOPHeader(bbP,  /* drop_frame_flag */ 0,
                            tc_hrs, tc_min, tc_sec, tc_pict,
                            closed, /* broken_link */ 0,
                            /* ext_data */ NULL, /* ext_data_size */ 0,
@@ -368,16 +367,16 @@ outputIFrame(MpegFrame * const frameP,
         if (pastRefFrameP == NULL)
             SetGOPStartTime(0);
         else
-            SetGOPStartTime(pastRefFrameP->id+1);
+            SetGOPStartTime(pastRefFrameP->id + 1);
     }
       
-    if ((frameP->id >= realStart) && (frameP->id <= realEnd))
-        GenIFrame(bb, frameP);
+    if (frameP->id >= realStart && frameP->id <= realEnd)
+        GenIFrame(bbP, frameP);
       
-    numI--;
+    --numI;
     timeMask &= 0x6;
       
-    currentGOP++;
+    ++currentGOP;
     IncrementTCTime();
 }
 
@@ -393,10 +392,10 @@ outputPFrame(MpegFrame * const frameP,
     if ((frameP->id >= realStart) && (frameP->id <= realEnd))
         GenPFrame(bbP, frameP, pastRefFrameP);
 
-    numP--;
+    --numP;
     timeMask &= 0x5;
     
-    currentGOP++;
+    ++currentGOP;
     IncrementTCTime();
 }
 
@@ -498,6 +497,9 @@ processBFrames(MpegFrame *          const pastRefFrameP,
 
    But do only those B frames whose frame numbers are within the range
    'realStart' through 'realEnd'.
+
+   Output the frames to the output stream 'wholeStreamBbP'.  If NULL,
+   output each frame to its own individual file instead.
 -----------------------------------------------------------------------------*/
     boolean const separateFiles = (wholeStreamBbP == NULL);
     unsigned int const firstBFrameNum = pastRefFrameP->id + 1;
@@ -551,7 +553,7 @@ processBFrames(MpegFrame *          const pastRefFrameP,
 
 static void
 processRefFrame(MpegFrame *    const frameP, 
-                BitBucket *    const bb_arg,
+                BitBucket *    const wholeStreamBbP,
                 int            const realStart,
                 int            const realEnd,
                 MpegFrame *    const pastRefFrameP,
@@ -564,26 +566,28 @@ processRefFrame(MpegFrame *    const frameP,
 
    But only if its frame number is within the range 'realStart'
    through 'realEnd'.
+
+   Output the frame to the output stream 'wholeStreamBbP'.  If NULL,
+   output it to its own individual file instead.
 -----------------------------------------------------------------------------*/
     if (frameP->id >= realStart && frameP->id <= realEnd) {
-        boolean separateFiles;
-        BitBucket * bb;
+        bool const separateFiles = (wholeStreamBbP == NULL);
   
-        separateFiles = (bb_arg == NULL);
+        BitBucket * bbP;
   
-        if ( separateFiles )
-            bb = bitioNew(outputFileName, frameP->id, remoteIO);
+        if (separateFiles)
+            bbP = bitioNew(outputFileName, frameP->id, remoteIO);
         else
-            bb = bb_arg;
+            bbP = wholeStreamBbP;
   
         /* first, output this reference frame */
         switch (frameP->type) {
         case TYPE_IFRAME:
-            outputIFrame(frameP, bb, realStart, realEnd, pastRefFrameP, 
+            outputIFrame(frameP, bbP, realStart, realEnd, pastRefFrameP, 
                          separateFiles);
             break;
         case TYPE_PFRAME:
-            outputPFrame(frameP, bb, realStart, realEnd, pastRefFrameP);
+            outputPFrame(frameP, bbP, realStart, realEnd, pastRefFrameP);
             ShowRemainingTime(childProcess);
             break;
         default:
@@ -593,7 +597,7 @@ processRefFrame(MpegFrame *    const frameP,
         
         ++(*framesOutputP);
         
-        finishFrameOutput(frameP, bb, separateFiles, referenceFrame,
+        finishFrameOutput(frameP, bbP, separateFiles, referenceFrame,
                           childProcess, remoteIO);
     }
 }
@@ -702,7 +706,7 @@ readAndSaveFrame(struct inputSource * const inputSourceP,
 static void
 doFirstFrameStuff(enum frameContext const context,
                   const char *      const userDataFileName,
-                  BitBucket *       const bb,
+                  BitBucket *       const bbP,
                   int               const fsize_x,
                   int               const fsize_y,
                   int               const aspectRatio,
@@ -713,8 +717,12 @@ doFirstFrameStuff(enum frameContext const context,
 /*----------------------------------------------------------------------------
    Do stuff we have to do after reading the first frame in a sequence
    of frames requested of GenMPEGStream().
+
+   *bbP is the output stream to which to write any header stuff we have
+   to write.  If 'context' is such that there is no header stuff to write,
+   then 'bbP' is irrelevant.
 -----------------------------------------------------------------------------*/
-    *inputFrameBitsP = 24*Fsize_x*Fsize_y;
+    *inputFrameBitsP = 24 * Fsize_x * Fsize_y;
     SetBlocksPerSlice();
           
     if (context == CONTEXT_WHOLESTREAM) {
@@ -722,7 +730,7 @@ doFirstFrameStuff(enum frameContext const context,
         char * userData;
         unsigned int userDataSize;
 
-        assert(bb != NULL);
+        assert(bbP != NULL);
 
         DBG_PRINT(("Generating sequence header\n"));
         if (bitstreamMode == FIXED_RATE) {
@@ -770,7 +778,7 @@ doFirstFrameStuff(enum frameContext const context,
             userDataSize = strlen(userData);
             strfree(userDataString);
         }
-        Mhead_GenSequenceHeader(bb, Fsize_x, Fsize_y,
+        Mhead_GenSequenceHeader(bbP, Fsize_x, Fsize_y,
                                 /* pratio */ aspectRatio,
                                 /* pict_rate */ frameRate, 
                                 /* bit_rate */ bit_rate,
@@ -990,13 +998,21 @@ doAFrame(unsigned int         const frameNumber,
          unsigned int *       const framesReadP,
          unsigned int *       const framesOutputP,
          bool *               const firstFrameDoneP,
-         BitBucket *          const bbP,
+         BitBucket *          const wholeStreamBbP,
          unsigned int *       const inputFrameBitsP,
          bool *               const endOfStreamP) {
 /*----------------------------------------------------------------------------
    *endOfStreamP returned means we were unable to do a frame because
    the input stream has ended.  In that case, none of the other outputs
    are valid.
+
+   Process an input frame.  This can involve writing its description
+   to the output stream, saving it for later use, and/or writing
+   descriptions of previously saved frames to the output stream
+   because we now have enough information to do so.
+
+   Output the frames to the output stream 'wholeStreamBbP'.  If NULL,
+   output each frame to its own individual file instead.
 -----------------------------------------------------------------------------*/
     char const frameType = FType_Type(frameNumber);
     
@@ -1026,21 +1042,21 @@ doAFrame(unsigned int         const frameNumber,
             *endOfStreamP = FALSE;
 
             if (!*firstFrameDoneP) {
-                doFirstFrameStuff(context, userDataFileName,
-                                  bbP, Fsize_x, Fsize_y, aspectRatio,
+                doFirstFrameStuff(context, userDataFileName, wholeStreamBbP,
+                                  Fsize_x, Fsize_y, aspectRatio,
                                   frameRate, qtable, niqtable, 
                                   inputFrameBitsP);
             
                 *firstFrameDoneP = TRUE;
             }
-            processRefFrame(frameP, bbP, frameStart, frameEnd,
+            processRefFrame(frameP, wholeStreamBbP, frameStart, frameEnd,
                             pastRefFrameP, childProcess, outputFileName, 
                             framesReadP, framesOutputP);
                 
             if (pastRefFrameP) {
                 processBFrames(pastRefFrameP, frameP, realStart, realEnd,
                                inputSourceP, remoteIO, childProcess, 
-                               &IOtime, bbP, outputFileName,
+                               &IOtime, wholeStreamBbP, outputFileName,
                                framesReadP, framesOutputP, &currentGOP);
             }
             if (pastRefFrameP != NULL)
@@ -1086,17 +1102,20 @@ GenMPEGStream(struct inputSource * const inputSourceP,
    we stop where the stream ends if that is before 'frameEnd'.
 
 -----------------------------------------------------------------------------*/
-    BitBucket * bbP;
+    BitBucket * streamBbP;
+        /* The output stream to which we write all the frames.  NULL
+           means the frames are going to individual frame files.
+        */
     unsigned int frameNumber;
     bool endOfStream;
     bool firstFrameDone;
     int numBits;
     unsigned int firstFrame, lastFrame;
-    /* Frame numbers of the first and last frames we look at.  This
-       could be more than the the frames we actually encode because
-       we may need context (i.e. to encode a B frame, we need the subsequent
-       I or P frame).
-    */
+        /* Frame numbers of the first and last frames we look at.
+           This could be more than the the frames we actually encode
+           because we may need context (i.e. to encode a B frame, we
+           need the subsequent I or P frame).
+        */
     unsigned int framesRead;
         /* Number of frames we have read; for statistical purposes */
     MpegFrame * pastRefFrameP;
@@ -1150,10 +1169,10 @@ GenMPEGStream(struct inputSource * const inputSourceP,
     if (showBitRatePerFrame)
         OpenBitRateFile();  /* May modify showBitRatePerFrame */
 
-    if (context == CONTEXT_WHOLESTREAM || context == CONTEXT_GOP)
-        bbP = Bitio_New(ofP);
+    if (context == CONTEXT_JUSTFRAMES)
+        streamBbP = NULL;
     else
-        bbP = NULL;
+        streamBbP = Bitio_New(ofP);
 
     initTCTime(firstFrame);
 
@@ -1171,7 +1190,7 @@ GenMPEGStream(struct inputSource * const inputSourceP,
                  frameStart, frameEnd, realStart, realEnd,
                  childProcess, outputFileName,
                  pastRefFrameP, &pastRefFrameP,
-                 &framesRead, &framesOutput, &firstFrameDone, bbP,
+                 &framesRead, &framesOutput, &firstFrameDone, streamBbP,
                  inputFrameBitsP, &endOfStream);
     }
     
@@ -1180,10 +1199,10 @@ GenMPEGStream(struct inputSource * const inputSourceP,
     
     /* SEQUENCE END CODE */
     if (context == CONTEXT_WHOLESTREAM)
-        Mhead_GenSequenceEnder(bbP);
+        Mhead_GenSequenceEnder(streamBbP);
     
-    if (context == CONTEXT_WHOLESTREAM)
-        numBits = bbP->cumulativeBits;
+    if (streamBbP)
+        numBits = streamBbP->cumulativeBits;
     else {
         /* What should the correct value be?  Most likely 1.  "numBits" is
            used below, so we need to make sure it's properly initialized 
@@ -1192,9 +1211,8 @@ GenMPEGStream(struct inputSource * const inputSourceP,
         numBits = 1;
     }
 
-    if (context != CONTEXT_JUSTFRAMES) {
-        Bitio_Flush(bbP);
-        bbP = NULL;
+    if (streamBbP) {
+        Bitio_Flush(streamBbP);
         fclose(ofP);
     }
     handleBitRate(realEnd, numBits, childProcess, showBitRatePerFrame);
@@ -1662,7 +1680,7 @@ ReadDecodedRefFrame(MpegFrame *  const frameP,
     }
 
     if ((fpointer = fopen(fileName, "rb")) == NULL) {
-        sleep(1);
+        sleepN(1000);
         if ((fpointer = fopen(fileName, "rb")) == NULL) {
             fprintf(stderr, "Cannot open %s\n", fileName);
             exit(1);
diff --git a/converter/ppm/ppmtompeg/noparallel.c b/converter/ppm/ppmtompeg/noparallel.c
index b27934fb..6e6449a4 100644
--- a/converter/ppm/ppmtompeg/noparallel.c
+++ b/converter/ppm/ppmtompeg/noparallel.c
@@ -164,7 +164,7 @@ void
 CombineServer(int          const numFrames, 
               const char * const masterHostName, 
               int          const masterPortNum,
-              const char * const outputFileName) {
+              const char*  const outputFileName) {
 
     pm_error("This version of Ppmtompeg cannot run combine server because "
              "it does not have socket capability.");
diff --git a/converter/ppm/ppmtompeg/parallel.c b/converter/ppm/ppmtompeg/parallel.c
index 021e6d2b..e13bf221 100644
--- a/converter/ppm/ppmtompeg/parallel.c
+++ b/converter/ppm/ppmtompeg/parallel.c
@@ -41,6 +41,7 @@
 
 #include "mallocvar.h"
 #include "nstring.h"
+#include "nsleep.h"
 
 #include "pm.h"
 
@@ -128,7 +129,7 @@ boolean niceProcesses = FALSE;
 boolean forceIalign = FALSE;
 int     machineNumber = -1;
 boolean remoteIO = FALSE;
-bool separateConversion;
+boolean separateConversion;
     /* The I/O server will convert from the input format to the base format,
        and the slave will convert from the base format to the YUV internal
        format.  If false, the I/O server assumes the input format is the
@@ -630,7 +631,7 @@ static int safe_fork(command)       /* fork child process and remember its PID *
  *
  *===========================================================================*/
 void
-SetIOConvert(bool const separate) {
+SetIOConvert(boolean const separate) {
     separateConversion = separate;
 }
 
@@ -648,8 +649,7 @@ SetIOConvert(bool const separate) {
  *
  *===========================================================================*/
 void
-SetParallelPerfect(val)
-boolean val;
+SetParallelPerfect(boolean val)
 {
     parallelPerfect = val;
 }
@@ -1209,7 +1209,7 @@ openInputFile(const char * const fileName,
             pm_message("ERROR  Couldn't read frame file '%s' errno = %d (%s)"
                        "attempt %d", 
                        fileName, errno, strerror(errno), attempts);
-            sleep(1);
+            sleepN(1000);
         }
         ++attempts;
     }
diff --git a/converter/ppm/ppmtompeg/param.c b/converter/ppm/ppmtompeg/param.c
index 69e38a6c..a145d33c 100644
--- a/converter/ppm/ppmtompeg/param.c
+++ b/converter/ppm/ppmtompeg/param.c
@@ -665,66 +665,66 @@ processParamLine(char const input[],
 
     switch(input[0]) {
     case 'A':
-        if (STRNEQ(input, "ASPECT_RATIO", 12)) {
+        if (strneq(input, "ASPECT_RATIO", 12)) {
             aspectRatio = GetAspectRatio(SkipSpacesTabs(&input[12]));
             optionSeen[OPTION_ASPECT_RATIO] = TRUE;
         }
         break;
         
     case 'B':
-        if (STRNEQ(input, "BQSCALE", 7)) {
+        if (strneq(input, "BQSCALE", 7)) {
             SetBQScale(atoi(SkipSpacesTabs(&input[7])));
             optionSeen[OPTION_BQSCALE] = TRUE;
-        } else if (STRNEQ(input, "BASE_FILE_FORMAT", 16)) {
+        } else if (strneq(input, "BASE_FILE_FORMAT", 16)) {
             const char * arg = SkipSpacesTabs(&input[16]);
             SetFileFormat(arg);
-            if (STRNEQ(arg, "YUV", 3) || STREQ(arg, "Y"))
+            if (strneq(arg, "YUV", 3) || streq(arg, "Y"))
                 *yuvUsedP = TRUE;
             optionSeen[OPTION_BASE_FORMAT] = TRUE;
-        } else if (STRNEQ(input, "BSEARCH_ALG", 11)) {
+        } else if (strneq(input, "BSEARCH_ALG", 11)) {
             SetBSearchAlg(SkipSpacesTabs(&input[11]));
             optionSeen[OPTION_BSEARCH_ALG] = TRUE;
-        } else if (STRNEQ(input, "BIT_RATE", 8)) {
+        } else if (strneq(input, "BIT_RATE", 8)) {
             setBitRate(SkipSpacesTabs(&input[8]));
             optionSeen[OPTION_BIT_RATE] = TRUE;
-        } else if (STRNEQ(input, "BUFFER_SIZE", 11)) {
+        } else if (strneq(input, "BUFFER_SIZE", 11)) {
             setBufferSize(SkipSpacesTabs(&input[11]));
             optionSeen[OPTION_BUFFER_SIZE] = TRUE;                  
         }
         break;
 
     case 'C':
-        if (STRNEQ(input, "CDL_FILE", 8)) {
+        if (strneq(input, "CDL_FILE", 8)) {
             strcpy(specificsFile, SkipSpacesTabs(&input[8]));
             specificsOn = TRUE;
             optionSeen[OPTION_SPECIFICS] = TRUE;
-        } else if (STRNEQ(input, "CDL_DEFINES", 11)) {
+        } else if (strneq(input, "CDL_DEFINES", 11)) {
             strcpy(specificsDefines, SkipSpacesTabs(&input[11]));
             optionSeen[OPTION_DEFS_SPECIFICS] = TRUE;
         }
         break;
 
     case 'F':
-        if (STRNEQ(input, "FRAME_INPUT_DIR", 15)) {
+        if (strneq(input, "FRAME_INPUT_DIR", 15)) {
             const char * const arg = SkipSpacesTabs(&input[15]);
-            if (STRNCASEEQ(arg, "stdin", 5))
+            if (strncaseeq(arg, "stdin", 5))
                 SetStdinInput(frameInputSourceP);
 
             strcpy(currentFramePath, arg);
-        } else if (STRNEQ(input, "FRAME_INPUT", 11)) {
+        } else if (strneq(input, "FRAME_INPUT", 11)) {
             ReadInputFileNames(fpointer, "FRAME_END_INPUT", 
                                frameInputSourceP->stdinUsed ? 
                                NULL : frameInputSourceP);
             optionSeen[OPTION_FRAME_INPUT] = TRUE;
-        } else if (STRNEQ(input, "FORCE_I_ALIGN", 13)) {
+        } else if (strneq(input, "FORCE_I_ALIGN", 13)) {
             forceIalign = TRUE;
-        } else if (STRNEQ(input, "FORCE_ENCODE_LAST_FRAME", 23)) {
+        } else if (strneq(input, "FORCE_ENCODE_LAST_FRAME", 23)) {
             /* NO-OP.  We used to drop trailing B frames by default and you
                needed this option to change the last frame to I so you could
                encode all the frames.  Now we just do that all the time.  
                Why wouldn't we?
             */
-        } else if (STRNEQ(input, "FRAME_RATE", 10)) {
+        } else if (strneq(input, "FRAME_RATE", 10)) {
             frameRate = GetFrameRate(SkipSpacesTabs(&input[10]));
             frameRateRounded = (int) VidRateNum[frameRate];
             if ((frameRate % 3) == 1)
@@ -734,21 +734,21 @@ processParamLine(char const input[],
         break;
         
     case 'G':
-        if (STRNEQ(input, "GOP_SIZE", 8)) {
+        if (strneq(input, "GOP_SIZE", 8)) {
             SetGOPSize(atoi(SkipSpacesTabs(&input[8])));
             optionSeen[OPTION_GOP] = TRUE;
-        } else if (STRNEQ(input, "GOP_INPUT_DIR", 13)) {
+        } else if (strneq(input, "GOP_INPUT_DIR", 13)) {
             const char * const arg = SkipSpacesTabs(&input[13]);
-            if (STRNCASEEQ(arg, "stdin", 5))
+            if (strncaseeq(arg, "stdin", 5))
                 SetStdinInput(gopInputSourceP);
 
             strcpy(currentGOPPath, arg);
-        } else if (STRNEQ(input, "GOP_INPUT", 9)) {
+        } else if (strneq(input, "GOP_INPUT", 9)) {
             ReadInputFileNames(fpointer, "GOP_END_INPUT", 
                                gopInputSourceP->stdinUsed ? 
                                NULL : gopInputSourceP);
             optionSeen[OPTION_GOP_INPUT] = TRUE;
-        } else if (STRNEQ(input, "GAMMA", 5)) {
+        } else if (strneq(input, "GAMMA", 5)) {
             GammaCorrection = TRUE;
             sscanf(SkipSpacesTabs(&input[5]), "%f", &GammaValue);
             optionSeen[OPTION_GAMMA] = TRUE;
@@ -756,27 +756,27 @@ processParamLine(char const input[],
         break;
         
     case 'I':
-        if (STRNEQ(input, "IQSCALE", 7)) {
+        if (strneq(input, "IQSCALE", 7)) {
             SetIQScale(atoi(SkipSpacesTabs(&input[7])));
             optionSeen[OPTION_IQSCALE] = TRUE;
-        } else if (STRNEQ(input, "INPUT_DIR", 9)) {
+        } else if (strneq(input, "INPUT_DIR", 9)) {
             const char * const arg = SkipSpacesTabs(&input[9]);
-            if (STRNCASEEQ(arg, "stdin", 5))
+            if (strncaseeq(arg, "stdin", 5))
                 SetStdinInput(inputSourceP);
             strcpy(currentPath, arg);
             optionSeen[OPTION_INPUT_DIR] = TRUE;
-        } else if (STRNEQ(input, "INPUT_CONVERT", 13)) {
+        } else if (strneq(input, "INPUT_CONVERT", 13)) {
             strcpy(inputConversion, SkipSpacesTabs(&input[13]));
             optionSeen[OPTION_INPUT_CONVERT] = TRUE;
-        } else if (STREQ(input, "INPUT")) {
+        } else if (streq(input, "INPUT")) {
             ReadInputFileNames(fpointer, "END_INPUT", 
                                inputSourceP->stdinUsed ?
                                NULL : inputSourceP);
             optionSeen[OPTION_INPUT] = TRUE;
-        } else if (STRNEQ(input, "IO_SERVER_CONVERT", 17)) {
+        } else if (strneq(input, "IO_SERVER_CONVERT", 17)) {
             strcpy(ioConversion, SkipSpacesTabs(&input[17]));
             optionSeen[OPTION_IO_CONVERT] = TRUE;
-        } else if (STRNEQ(input, "IQTABLE", 7)) {
+        } else if (strneq(input, "IQTABLE", 7)) {
             processIqtable(fpointer);
 
             optionSeen[OPTION_IQTABLE] = TRUE;
@@ -784,12 +784,12 @@ processParamLine(char const input[],
         break;
 
     case 'K':
-        if (STRNEQ(input, "KEEP_TEMP_FILES", 15))
+        if (strneq(input, "KEEP_TEMP_FILES", 15))
             keepTempFiles = TRUE;
         break;
         
     case 'N':
-      if (STRNEQ(input, "NIQTABLE", 8)) {
+      if (strneq(input, "NIQTABLE", 8)) {
           readNiqTable(fpointer);
 
           optionSeen[OPTION_NIQTABLE] = TRUE;
@@ -797,7 +797,7 @@ processParamLine(char const input[],
       break;
 
     case 'O':
-        if (STRNEQ(input, "OUTPUT", 6)) {
+        if (strneq(input, "OUTPUT", 6)) {
             const char * const arg = SkipSpacesTabs(&input[6]);
             if ( whichGOP == -1 )
                 strcpy(outputFileName, arg);
@@ -809,45 +809,45 @@ processParamLine(char const input[],
         break;
         
     case 'P':
-        if (STRNEQ(input, "PATTERN", 7)) {
+        if (strneq(input, "PATTERN", 7)) {
             SetFramePattern(SkipSpacesTabs(&input[7]));
             optionSeen[OPTION_PATTERN] = TRUE;
-        } else if (STRNEQ(input, "PIXEL", 5)) {
+        } else if (strneq(input, "PIXEL", 5)) {
             SetPixelSearch(SkipSpacesTabs(&input[5]));
             optionSeen[OPTION_PIXEL] = TRUE;
-        } else if (STRNEQ(input, "PQSCALE", 7)) {
+        } else if (strneq(input, "PQSCALE", 7)) {
             SetPQScale(atoi(SkipSpacesTabs(&input[7])));
             optionSeen[OPTION_PQSCALE] = TRUE;
-        } else if (STRNEQ(input, "PSEARCH_ALG", 11)) {
+        } else if (strneq(input, "PSEARCH_ALG", 11)) {
             SetPSearchAlg(SkipSpacesTabs(&input[11]));
             optionSeen[OPTION_PSEARCH_ALG] = TRUE;
-        } else if (STRNEQ(input, "PARALLEL_TEST_FRAMES", 20)) {
+        } else if (strneq(input, "PARALLEL_TEST_FRAMES", 20)) {
             SetParallelPerfect(FALSE);
             parallelTestFrames = atoi(SkipSpacesTabs(&input[20]));
-        } else if (STRNEQ(input, "PARALLEL_TIME_CHUNKS", 20)) {
+        } else if (strneq(input, "PARALLEL_TIME_CHUNKS", 20)) {
             SetParallelPerfect(FALSE);
             parallelTimeChunks = atoi(SkipSpacesTabs(&input[20]));
-        } else if (STRNEQ(input, "PARALLEL_CHUNK_TAPER", 20)) {
+        } else if (strneq(input, "PARALLEL_CHUNK_TAPER", 20)) {
             SetParallelPerfect(FALSE);
             parallelTimeChunks = -1;
-        } else if (STRNEQ(input, "PARALLEL_PERFECT", 16)) {
+        } else if (strneq(input, "PARALLEL_PERFECT", 16)) {
             SetParallelPerfect(TRUE);
-        } else if (STRNEQ(input, "PARALLEL", 8)) {
+        } else if (strneq(input, "PARALLEL", 8)) {
             ReadMachineNames(fpointer);
             optionSeen[OPTION_PARALLEL] = TRUE;
         }
         break;
         
     case 'R':
-        if (STRNEQ(input, "RANGE", 5)) {
+        if (strneq(input, "RANGE", 5)) {
             processRanges(SkipSpacesTabs(&input[5]));
             optionSeen[OPTION_RANGE] = TRUE;
-        } else if (STRNEQ(input, "REFERENCE_FRAME", 15)) {
+        } else if (strneq(input, "REFERENCE_FRAME", 15)) {
             SetReferenceFrameType(SkipSpacesTabs(&input[15]));
             optionSeen[OPTION_REF_FRAME] = TRUE;
-        } else if (STRNEQ(input, "RSH", 3)) {
+        } else if (strneq(input, "RSH", 3)) {
             SetRemoteShell(SkipSpacesTabs(&input[3]));
-        } else if (STRNEQ(input, "RESIZE", 6)) {
+        } else if (strneq(input, "RESIZE", 6)) {
             const char * const arg = SkipSpacesTabs(&input[6]);
             sscanf(arg, "%dx%d", &outputWidth, &outputHeight);
             outputWidth &= ~(DCTSIZE * 2 - 1);
@@ -857,22 +857,22 @@ processParamLine(char const input[],
         break;
 
     case 'S':
-        if (STRNEQ(input, "SLICES_PER_FRAME", 16)) {
+        if (strneq(input, "SLICES_PER_FRAME", 16)) {
             SetSlicesPerFrame(atoi(SkipSpacesTabs(&input[16])));
             optionSeen[OPTION_SPF] = TRUE;
-        } else if (STRNEQ(input, "SLAVE_CONVERT", 13)) {
+        } else if (strneq(input, "SLAVE_CONVERT", 13)) {
             strcpy(slaveConversion, SkipSpacesTabs(&input[13]));
             optionSeen[OPTION_SLAVE_CONVERT] = TRUE;
-        } else if (STRNEQ(input, "SPECIFICS_FILE", 14)) {
+        } else if (strneq(input, "SPECIFICS_FILE", 14)) {
             strcpy(specificsFile, SkipSpacesTabs(&input[14]));
             specificsOn = TRUE;
             optionSeen[OPTION_SPECIFICS] = TRUE;
-        } else if (STRNEQ(input, "SPECIFICS_DEFINES", 16)) {
+        } else if (strneq(input, "SPECIFICS_DEFINES", 16)) {
             strcpy(specificsDefines, SkipSpacesTabs(&input[17]));
             optionSeen[OPTION_DEFS_SPECIFICS] = TRUE;
-        } else if (STRNEQ(input, "SEQUENCE_SIZE", 13)) {
+        } else if (strneq(input, "SEQUENCE_SIZE", 13)) {
             mult_seq_headers = atoi(SkipSpacesTabs(&input[13]));
-        } else if (STRNEQ(input, "SIZE", 4)) {
+        } else if (strneq(input, "SIZE", 4)) {
             const char * const arg = SkipSpacesTabs(&input[4]);
             sscanf(arg, "%dx%d", &yuvWidth, &yuvHeight);
             realWidth = yuvWidth;
@@ -883,42 +883,42 @@ processParamLine(char const input[],
         break;
 
     case 'T':
-        if (STRNEQ(input, "TUNE", 4)) {
+        if (strneq(input, "TUNE", 4)) {
             tuneingOn = TRUE;
             ParseTuneParam(SkipSpacesTabs(&input[4]));
         }
         break;
 
     case 'U':
-        if (STRNEQ(input, "USER_DATA", 9)) {
+        if (strneq(input, "USER_DATA", 9)) {
             strcpy(userDataFileName, SkipSpacesTabs(&input[9]));
             optionSeen[OPTION_USER_DATA] = TRUE;
         }
         break;
         
     case 'W':
-        if (STRNEQ(input, "WARN_UNDERFLOW", 14))
+        if (strneq(input, "WARN_UNDERFLOW", 14))
             paramP->warnUnderflow = TRUE;
-        if (STRNEQ(input, "WARN_OVERFLOW", 13))
+        if (strneq(input, "WARN_OVERFLOW", 13))
             paramP->warnOverflow = TRUE;
         break;
         
     case 'Y':
-        if (STRNEQ(input, "YUV_SIZE", 8)) {
+        if (strneq(input, "YUV_SIZE", 8)) {
             const char * const arg = SkipSpacesTabs(&input[8]);
             sscanf(arg, "%dx%d", &yuvWidth, &yuvHeight);
             realWidth = yuvWidth;
             realHeight = yuvHeight;
             Fsize_Validate(&yuvWidth, &yuvHeight);
             optionSeen[OPTION_YUV_SIZE] = TRUE;
-        } else if (STRNEQ(input, "Y_SIZE", 6)) {
+        } else if (strneq(input, "Y_SIZE", 6)) {
             const char * const arg = SkipSpacesTabs(&input[6]);
             sscanf(arg, "%dx%d", &yuvWidth, &yuvHeight);
             realWidth = yuvWidth;
             realHeight = yuvHeight;
             Fsize_Validate(&yuvWidth, &yuvHeight);
             optionSeen[OPTION_YUV_SIZE] = TRUE;
-        } else if (STRNEQ(input, "YUV_FORMAT", 10)) {
+        } else if (strneq(input, "YUV_FORMAT", 10)) {
             strcpy(yuvConversion,  SkipSpacesTabs(&input[10]));
             optionSeen[OPTION_YUV_FORMAT] = TRUE;
         }
@@ -928,26 +928,21 @@ processParamLine(char const input[],
 
 
 
-/*===========================================================================*
- *
- * ReadParamFile
- *
- *	read the parameter file
- *	function is ENCODE_FRAMES, COMBINE_GOPS, or COMBINE_FRAMES, and
- *	    will slightly modify the procedure's behavior as to what it
- *	    is looking for in the parameter file
- *
- * SIDE EFFECTS:    sets parameters accordingly, as well as machine info for
- *		    parallel execution and input file names
- *
- *===========================================================================*/
 void
-ReadParamFile(const char *    const fileName, 
-              int             const function,
-              struct params * const paramP) {
+ReadParamFile(const char *         const fileName, 
+              majorProgramFunction const function,
+              struct params *      const paramP) {
+/*----------------------------------------------------------------------------
+   Read the parameter file 'fileName' as *paramP.
 
-  FILE *fpointer;
-  char    buffer[256];
+   'function' slightly modifies our behavior as to what it is looking for
+   in the parameter file.
+
+   As a side effect, set machine info for parallel execution and input
+   file names
+-----------------------------------------------------------------------------*/
+  FILE * fpointer;
+  char buffer[256];
   bool yuvUsed;
   struct inputSource * inputSourceP;
       /* Contents of INPUT section */
diff --git a/converter/ppm/ppmtompeg/pframe.c b/converter/ppm/ppmtompeg/pframe.c
index e72fe5d6..de91e32c 100644
--- a/converter/ppm/ppmtompeg/pframe.c
+++ b/converter/ppm/ppmtompeg/pframe.c
@@ -60,8 +60,6 @@ static int32    totalTime = 0;
 static int      qscaleP;
 static float    totalSNR = 0.0;
 static float    totalPSNR = 0.0;
-extern Block    **dct, **dctr, **dctb;
-extern dct_data_type   **dct_data;
 
 /*=====================*
  * INTERNAL PROCEDURES *
diff --git a/converter/ppm/ppmtompeg/ppmtompeg.c b/converter/ppm/ppmtompeg/ppmtompeg.c
index 2296e2cb..f53ffea9 100644
--- a/converter/ppm/ppmtompeg/ppmtompeg.c
+++ b/converter/ppm/ppmtompeg/ppmtompeg.c
@@ -33,7 +33,6 @@
 #define _BSD_SOURCE   /* Make sure strdup() is in string.h */
 
 #include <assert.h>
-#include <sys/utsname.h>
 
 #include "all.h"
 #include "mtypes.h"
@@ -98,7 +97,7 @@ void init_fdct _ANSI_ARGS_((void));
 
 struct cmdlineInfo {
     bool         childProcess;
-    int          function;
+    majorProgramFunction function;
     const char * masterHostname;
     int          masterPortNumber;
     unsigned int outputFrames;
@@ -130,36 +129,33 @@ parseArgs(int     const argc,
     
     /* parse the arguments */
     idx = 1;
-    while ( idx < argc-1 ) {
-        if ( argv[idx][0] != '-' )
+    while (idx < argc-1) {
+        if (argv[idx][0] != '-')
             pm_error("argument '%s', which must be an option because "
                      "it is not the last argument, "
                      "does not start with '-'", argv[idx]);
 
-        if ( strcmp(argv[idx], "-stat") == 0 ) {
-            if ( idx+1 < argc-1 ) {
+        if (streq(argv[idx], "-stat")) {
+            if (idx+1 < argc-1) {
                 SetStatFileName(argv[idx+1]);
                 idx += 2;
-            } else {
+            } else
                 pm_error("Invalid -stat option");
-            }
-        } else if ( strcmp(argv[idx], "-gop") == 0 ) {
-            if ((cmdlineP->function != ENCODE_FRAMES) || 
-                (cmdlineP->specificFrames))
+        } else if (streq(argv[idx], "-gop")) {
+            if (cmdlineP->function != ENCODE_FRAMES || 
+                cmdlineP->specificFrames)
                 pm_error("Invalid -gop option");
             
-            if ( idx+1 < argc-1 ) {
+            if (idx+1 < argc-1) {
                 whichGOP = atoi(argv[idx+1]);
                 idx += 2;
-            } else {
+            } else
                 pm_error("Invalid -gop option");
-            }
-        } else if ( strcmp(argv[idx], "-frames") == 0 ) {
-            if ( (cmdlineP->function != ENCODE_FRAMES) || (whichGOP != -1) ) {
+        } else if (streq(argv[idx], "-frames")) {
+            if (cmdlineP->function != ENCODE_FRAMES || whichGOP != -1)
                 pm_error("invalid -frames option");
-            }
 
-            if ( idx+2 < argc-1 ) {
+            if (idx+2 < argc-1) {
                 int const frameStart = atoi(argv[idx+1]);
                 int const frameEnd = atoi(argv[idx+2]);
 
@@ -177,23 +173,23 @@ parseArgs(int     const argc,
                 idx += 3;
             } else
                 pm_error("-frames needs to be followed by two values");
-        } else if (strcmp(argv[idx], "-combine_gops") == 0) {
-            if ((cmdlineP->function != ENCODE_FRAMES) || (whichGOP != -1) || 
-                (cmdlineP->specificFrames)) {
+        } else if (streq(argv[idx], "-combine_gops")) {
+            if (cmdlineP->function != ENCODE_FRAMES || whichGOP != -1 || 
+                cmdlineP->specificFrames) {
                 pm_error("Invalid -combine_gops option");
             }
 
             cmdlineP->function = COMBINE_GOPS;
-            idx++;
-        } else if (strcmp(argv[idx], "-combine_frames") == 0) {
-            if ((cmdlineP->function != ENCODE_FRAMES) || (whichGOP != -1) ||
-                (cmdlineP->specificFrames))
+            ++idx;
+        } else if (streq(argv[idx], "-combine_frames")) {
+            if (cmdlineP->function != ENCODE_FRAMES || whichGOP != -1 ||
+                cmdlineP->specificFrames)
                 pm_error("Invalid -combine_frames option");
 
             cmdlineP->function = COMBINE_FRAMES;
-            idx++;
-        } else if ( strcmp(argv[idx], "-child") == 0 ) {
-            if ( idx+7 < argc-1 ) {
+            ++idx;
+        } else if (streq(argv[idx], "-child")) {
+            if (idx+7 < argc-1) {
                 int combinePortNumber;
                     /* This used to be important information, when the child
                        notified the combine server.  Now the master notifies
@@ -215,104 +211,94 @@ parseArgs(int     const argc,
 
             cmdlineP->childProcess = TRUE;
             idx += 8;
-        } else if ( strcmp(argv[idx], "-io_server") == 0 ) {
-            if ( idx+2 < argc-1 ) {
-                cmdlineP->masterHostname = argv[idx+1];
+        } else if (streq(argv[idx], "-io_server")) {
+            if (idx+2 < argc-1) {
+                cmdlineP->masterHostname   = argv[idx+1];
                 cmdlineP->masterPortNumber = atoi(argv[idx+2]);
-            } else {
+            } else
                 pm_error("Invalid -io_server option");
-            }
 
             ioServer = TRUE;
             idx += 3;
-        } else if ( strcmp(argv[idx], "-output_server") == 0 ) {
-            if ( idx+3 < argc-1 ) {
-                cmdlineP->masterHostname = argv[idx+1];
+        } else if (streq(argv[idx], "-output_server")) {
+            if (idx+3 < argc-1) {
+                cmdlineP->masterHostname   = argv[idx+1];
                 cmdlineP->masterPortNumber = atoi(argv[idx+2]);
-                cmdlineP->outputFrames = atoi(argv[idx+3]);
-            } else {
+                cmdlineP->outputFrames     = atoi(argv[idx+3]);
+            } else
                 pm_error("-output_server option requires 3 option values.  "
-                         "You specified %d", argc-1 - idx);
-            }
+                         "You specified %u", argc-1 - idx);
 
             outputServer = TRUE;
             idx += 4;
-        } else if ( strcmp(argv[idx], "-decode_server") == 0 ) {
-            if ( idx+3 < argc-1 ) {
-                cmdlineP->masterHostname = argv[idx+1];
+        } else if (streq(argv[idx], "-decode_server")) {
+            if (idx+3 < argc-1) {
+                cmdlineP->masterHostname   = argv[idx+1];
                 cmdlineP->masterPortNumber = atoi(argv[idx+2]);
-                cmdlineP->outputFrames = atoi(argv[idx+3]);
-            } else {
+                cmdlineP->outputFrames     = atoi(argv[idx+3]);
+            } else
                 pm_error("Invalid -decode_server option");
-            }
 
             cmdlineP->function = COMBINE_FRAMES;
             decodeServer = TRUE;
             idx += 4;
-        } else if ( strcmp(argv[idx], "-nice") == 0 ) {
+        } else if (streq(argv[idx], "-nice")) {
             niceProcesses = TRUE;
             idx++;
-        } else if ( strcmp(argv[idx], "-max_machines") == 0 ) {
-            if ( idx+1 < argc-1 ) {
+        } else if (streq(argv[idx], "-max_machines")) {
+            if (idx+1 < argc-1) {
                 cmdlineP->maxMachines = atoi(argv[idx+1]);
-            } else {
+            } else
                 pm_error("Invalid -max_machines option");
-            }
 
             idx += 2;
-        } else if ( strcmp(argv[idx], "-quiet") == 0 ) {
-            if ( idx+1 < argc-1 ) {
+        } else if (streq(argv[idx], "-quiet")) {
+            if (idx+1 < argc-1)
                 quietTime = atoi(argv[idx+1]);
-            } else {
+            else
                 pm_error("Invalid -quiet option");
-            }
 
             idx += 2;
-        } else if ( strcmp(argv[idx], "-realquiet") == 0 ) {
+        } else if (streq(argv[idx], "-realquiet")) {
             realQuiet = TRUE;
-            idx++;
-        } else if (( strcmp(argv[idx], "-float_dct") == 0 ) ||
-                   ( strcmp(argv[idx], "-float-dct") == 0 )) {
+            ++idx;
+        } else if (streq(argv[idx], "-float_dct") ||
+                   streq(argv[idx], "-float-dct")) {
             pureDCT = TRUE;
             init_idctref();
             init_fdct();
-            idx++;
-        } else if ( strcmp(argv[idx], "-no_frame_summary") == 0 ) {
-            if ( idx < argc-1 ) {
+            ++idx;
+        } else if (streq(argv[idx], "-no_frame_summary")) {
+            if (idx < argc-1)
                 noFrameSummaryOption = TRUE;
-            } else {
+            else
                 pm_error("Invalid -no_frame_summary option");
-            }
-
-            idx++;
-        } else if ( strcmp(argv[idx], "-snr") == 0 ) {
+            ++idx;
+        } else if (streq(argv[idx], "-snr")) {
             printSNR = TRUE;
-            idx++;
-        } else if ( strcmp(argv[idx], "-mse") == 0 ) {
-            printSNR =  printMSE = TRUE;
-            idx++;
-        } else if ( strcmp(argv[idx], "-debug_sockets") == 0 ) {
+            ++idx;
+        } else if (streq(argv[idx], "-mse")) {
+            printSNR = printMSE = TRUE;
+            ++idx;
+        } else if (streq(argv[idx], "-debug_sockets")) {
             debugSockets = TRUE;
-            idx++;
-        } else if ( strcmp(argv[idx], "-debug_machines") == 0 ) {
+            ++idx;
+        } else if (streq(argv[idx], "-debug_machines")) {
             debugMachines = TRUE;
-            idx++;
-        } else if ( strcmp(argv[idx], "-bit_rate_info") == 0 ) {
-            if ( idx+1 < argc-1 ) {
+            ++idx;
+        } else if (streq(argv[idx], "-bit_rate_info")) {
+            if (idx+1 < argc-1) {
                 bitRateInfoOption = TRUE;
                 SetBitRateFileName(argv[idx+1]);
                 idx += 2;
-            } else {
+            } else
                 pm_error("Invalid -bit_rate_info option");
-            }
-        } else if ( strcmp(argv[idx], "-mv_histogram") == 0 ) {
+        } else if (streq(argv[idx], "-mv_histogram")) {
             computeMVHist = TRUE;
-            idx++;
-        } else {
+            ++idx;
+        } else
             pm_error("Unrecognized option: '%s'", argv[idx]);
-        }
     }
-
     cmdlineP->paramFileName = argv[argc-1];
 }
 
@@ -686,8 +672,8 @@ main(int argc, char **argv) {
         DecodeServer(cmdline.outputFrames, outputFileName, 
                      cmdline.masterHostname, cmdline.masterPortNumber);
     } else {
-        if ((!cmdline.specificFrames) &&
-            ((numMachines == 0) || (cmdline.function != ENCODE_FRAMES)) ) {
+        if (!cmdline.specificFrames &&
+            (numMachines == 0 || cmdline.function != ENCODE_FRAMES) ) {
             ofP = fopen(outputFileName, "wb");
             if (ofP == NULL)
                 pm_error("Could not open output file!");
@@ -695,7 +681,7 @@ main(int argc, char **argv) {
             ofP = NULL;
         
         if (cmdline.function == ENCODE_FRAMES) {
-            if ((numMachines == 0) || (cmdline.specificFrames)) {
+            if (numMachines == 0 || cmdline.specificFrames) {
                 encodeFrames(params.inputSourceP,
                              cmdline.childProcess, 
                              cmdline.masterHostname, cmdline.masterPortNumber,
diff --git a/converter/ppm/ppmtompeg/psearch.c b/converter/ppm/ppmtompeg/psearch.c
index aea1a29b..83c62d04 100644
--- a/converter/ppm/ppmtompeg/psearch.c
+++ b/converter/ppm/ppmtompeg/psearch.c
@@ -16,6 +16,8 @@
 #include "prototypes.h"
 #include "fsize.h"
 #include "param.h"
+#include "subsample.h"
+#include "block.h"
 
 
 /*==================*
diff --git a/converter/ppm/ppmtompeg/rate.c b/converter/ppm/ppmtompeg/rate.c
index 3940956c..1a44cb95 100644
--- a/converter/ppm/ppmtompeg/rate.c
+++ b/converter/ppm/ppmtompeg/rate.c
@@ -50,7 +50,6 @@
 
 #include <assert.h>
 #include <sys/types.h>
-#include <sys/times.h>
 
 #include "ppm.h"
 #include "nstring.h"
diff --git a/converter/ppm/ppmtompeg/specifics.c b/converter/ppm/ppmtompeg/specifics.c
index c7bbfb5b..38e8fc43 100644
--- a/converter/ppm/ppmtompeg/specifics.c
+++ b/converter/ppm/ppmtompeg/specifics.c
@@ -47,12 +47,6 @@
 #include <string.h>
 #include "prototypes.h"
 
-/*====================*
- * System Information *
- *====================*/
-
-#define CPP_LOC "/lib/cpp"
-
 /*==================*
  * GLOBAL VARIABLES *
  *==================*/
@@ -153,26 +147,27 @@ static char version = -1;
  *
  *================================================================
  */
-void Specifics_Init()
-{
-  char command[1100];
-  FILE *specificsFP;
-  
-  sprintf(command, "/bin/rm -f %s.cpp", specificsFile);
-  system(command);
-  sprintf(command, "%s -P %s %s %s.cpp",
-	  CPP_LOC, specificsDefines, specificsFile, specificsFile);
-  system(command);
-  strcat(specificsFile, ".cpp");
-  if ((specificsFP = fopen(specificsFile, "r")) == NULL) {
-    fprintf(stderr, "Error with specifics file, cannot open %s\n", specificsFile);
-    exit(1);
-  }
-  printf("Specifics file: %s\n", specificsFile);
-  Parse_Specifics_File(specificsFP);
-  sprintf(command, "/bin/rm -f %s.cpp", specificsFile);
-  system(command);
+void
+Specifics_Init() {
 
+    char command[1100];
+    FILE *specificsFP;
+  
+    sprintf(command, "rm -f %s.cpp", specificsFile);
+    system(command);
+    sprintf(command, "cpp -P %s %s %s.cpp",
+            specificsDefines, specificsFile, specificsFile);
+    system(command);
+    strcat(specificsFile, ".cpp");
+    if ((specificsFP = fopen(specificsFile, "r")) == NULL) {
+        fprintf(stderr, "Error with specifics file, cannot open %s\n",
+                specificsFile);
+        exit(1);
+    }
+    printf("Specifics file: %s\n", specificsFile);
+    Parse_Specifics_File(specificsFP);
+    sprintf(command, "rm -f %s.cpp", specificsFile);
+    system(command);
 }
 
 
diff --git a/converter/ppm/ppmtompeg/subsample.c b/converter/ppm/ppmtompeg/subsample.c
index 5ec71814..69401a1d 100644
--- a/converter/ppm/ppmtompeg/subsample.c
+++ b/converter/ppm/ppmtompeg/subsample.c
@@ -43,6 +43,7 @@
 #include "bitio.h"
 #include "prototypes.h"
 
+#include "subsample.h"
 
 
 static void