/* 
 * pvflin.c
 *
 * Convert various `linear' formats.
 *
 * 16-bit intel byte order conversion code written by Wolfgang Jung
 * (woju@keep.fan.bln.sub.org) 
 *
 */
 
char pvflin_c[] = "$Id: pvflin.c,v 1.9 1995/03/29 18:27:16 marc Exp $";

#include <stdio.h>

#ifndef _NOSTDLIB_H
#include <stdlib.h>
#endif

#include "../mgetty.h"
#include "pvflib.h"

int
pvftolin _P2((argc, argv), int argc, char **argv ) {
    FILE *in=stdin, *out=stdout;
    int sgned=0, i16=0;

    if (argc > 1 && !strcmp(argv[1], "-signed"))
    {
	sgned = 1;
	--argc, argv++;
    }
    
    if (argc > 1 && !strcmp(argv[1], "-16i"))
    {
	i16 = 1;
	--argc, argv++;
    }
    
    if (argc>1 ) USAGE("[-signed] [-16i]");

    if(sgned) {
	while(1) {
	    int d=zget(in);
	    if (feof(in)) break;
	    if (i16) putc(d & 0xff, out);
	    putc(d>>8, out);
	}
    } else {
	while(1) {
	    int d=zget(in);
	    if (feof(in)) break;
	    d += 0x8000;
	    if (i16) putc(d & 0xff, out);
	    putc((d>>8), out);
	}
    }
    return 0;
}

int
lintopvf _P2((argc, argv), int argc, char **argv ) {
    FILE *in=stdin, *out=stdout;
    int skip=0, sgned=0, i16=0;
    int i, d;

    if (argc > 1 && !strcmp(argv[1], "-signed"))
    {
	sgned = 1;
	--argc, argv++;
    }
    
    if (argc > 1 && !strcmp(argv[1], "-16i"))
    {
	i16 = 1;
	--argc, argv++;
    }
    
    if( argc>1 && (skip=atoi(argv[1])))
	--argc, argv++;
    
    if( argc>1 ) USAGE("[-signed] [-16i] [skip]");

    for(i=0; i<skip; i++) getc(in);
    
    if(sgned) {
	while ( (d=getc(in))!=EOF ) {
	    if (i16) {
		d |= (getc(in) <<8);
	    } else {
		d = (d<<8);
	    }
	    if (d >= 0x8000)
		d -= 0x10000;
	    zput(d, out );
	}
    } else {
	if (i16) {
	    while ( (d=getc(in)) != EOF ) {
		d |= ((getc(in)) << 8); 
		zput((d-0x8000), out );
	    }
	} else {
	    while ( (d=getc(in)) != EOF )
		zput((d-0x80)<<8, out );
	}
    }
    return 0;
}
