#!/usr/bin/perl

print STDERR"
############################################################
# disre2str.pl < disre_file > str_file                     #
#                                                          #
# An attempt to convert a disre file into NMR-STAR format  #
# (correspondong to 'v2' distnace restraint lists in PDB). #
############################################################

";

use Getopt::Std;
getopts('hv') || die "Wrong options, only -h and -v allowed\n";
exit if $opt_h;

$prevdn=-1;

print "data_restraints_converted_by_disre2str.pl

save_distance_restraints
   _Gen_dist_constraint_list.Sf_category          general_distance_restraints
   _Gen_dist_constraint_list.Sf_framecode         distance_restraints
   _Gen_dist_constraint_list.ID                   1
   _Gen_dist_constraint_list.Constraint_type      NOE
   _Gen_dist_constraint_list.Details              \"Generated by disre2str.pl\"
   _Gen_dist_constraint_list.Constraint_file_ID   1
   _Gen_dist_constraint_list.Block_ID             1

  loop_
      _Gen_dist_constraint.ID
      _Gen_dist_constraint.Member_ID
      _Gen_dist_constraint.Member_logic_code
      _Gen_dist_constraint.PDB_residue_no_1
      _Gen_dist_constraint.PDB_residue_name_1
      _Gen_dist_constraint.PDB_atom_name_1
      _Gen_dist_constraint.PDB_residue_no_2
      _Gen_dist_constraint.PDB_residue_name_2
      _Gen_dist_constraint.PDB_atom_name_2
      _Gen_dist_constraint.Comp_ID_1
      _Gen_dist_constraint.Atom_ID_1
      _Gen_dist_constraint.Atom_type_1
      _Gen_dist_constraint.Comp_ID_2
      _Gen_dist_constraint.Atom_ID_2
      _Gen_dist_constraint.Atom_type_2
      _Gen_dist_constraint.Distance_upper_bound_val

";

while(<>){
    chomp;
    next if ($_=~/^\#/);
    $_=~s/\#.*$//;
    $_=~s/^ +//;
    ($dn,$rnum1,$rname1,$atom1,$rnum2,$rname2,$atom2,$dist)=split(/ +/,$_);
    $DISRE[$dn].=sprintf("  %4d %3s %4s  %4d %3s %4s    %4d %4s H  %4d %4s H   %5.2f\n",$rnum1,$rname1,$atom1,$rnum2,$rname2,$atom2,,$rnum1,$atom1,$rnum2,$atom2,$dist);
    if ($dn == $prevdn){
	$OR[$dn]="OR";
    }
    else{
	$OR[$dn]=". ";
    }
    #printf("  %4d $OR %4d %3s %4s  H  %4d %3s %4s  H %5.2f\n",$dn+1,$rnum1,$rname1,$atom1,$rnum2,$rname2,$atom2,$dist);
    $prevdn=$dn;
}
$maxdn=$dn;

for ($dn=0; $dn<=$maxdn; $dn++){

    $mid=1;
    foreach $dline (split (/\n/,$DISRE[$dn])){
	printf ("  %4d %2d $OR[$dn] $dline\n",$dn,$mid);
	$mid++;
    }

} 

print"
   stop_

save_
";
