#!/usr/bin/perl -w
#
# This script recodes SNPs to -1 0 1 from a file like testdat.txt here
# recode_to_-1_0_1.pl x testdat.txt > testdat-recoded.txt
#

if($#ARGV < 0) {
    print STDERR "supply the missing data value\n";
    exit (1);
}

$[ = 1;
$miss = shift (@ARGV);

while (<>) 
{
    chop;
    @Fld = split(' ', $_);
    printf '%s  ', $Fld[1];
    for ($X = 2; $X <= $#Fld-1; $X+=2) {
	$a = $Fld[$X];
	$b = $Fld[$X+1];
	if($a ne $miss && $b ne $miss) {
	    if($a > $b) {
		$tmp = $a; $a = $b; $b = $tmp;
	    }
	    printf '  %2d', $a + $b - 3;
	}
	else {
	    print " NA";
	}
    }
    print "\n";
}
