#!/usr/bin/perl -w

########################################################################
#function 1: convert a prob beta map to binary beta-map according to threshold
#function 2: round the real number to 3 digits after ".".
#Author: Jianlin Cheng
#Date: 3/15/2005
########################################################################

if (@ARGV != 4)
{
	die "need params: input map file, format(1:binary, 2:round), prob threshold, output file\n"; 	
}

# First argument is always a map
$fmap = shift @ARGV;
$format = shift @ARGV;
$prob_thresh = shift @ARGV; 
$output_file = shift @ARGV;

open (MAP,"<$fmap") || die "file $fmap not found";
@tmap=<MAP>;
$name1 = shift @tmap;
$seq1 = shift @tmap; 
$ss1 = shift @tmap; 
$bp11 = shift @tmap;
$bp12 = shift @tmap; 
close MAP;

$size= @tmap;

@map=();
for ($i=0;$i<$size;$i++) 
{
  @line = split(/\s+/,$tmap[$i]);
  for ($j=0; $j < @line; $j++) 
  {
  	if ($format == 1) #binary
  	{
    		if ($line[$j] > $prob_thresh)
    		{
    			$map[$i][$j] = 1;
    		}
  		else
    		{
    	
   		 	$map[$i][$j] = 0;
    		}
    	}
	elsif ($format == 2) #round
	{
		$value = $line[$j];
		$value *= 100;
		$value += 0.5;
		$value = int($value);
		$value /= 100;
		$map[$i][$j] = $value;
	}
  }
}

open (OUTPUT,">$output_file") || die "can't create output file\n";
print OUTPUT "$name1$seq1$ss1$bp11$bp12";
for ($i = 0; $i < $size; $i++)
{
	@vals = ();
	for ($j = 0; $j < $size; $j++)
	{
		push @vals, $map[$i][$j]; 
	}
	$line = join(" ", @vals);
	print OUTPUT "$line\n"; 
}
close OUTPUT; 

