#!/bin/csh -f

#####**************************************************************************#####
#Despcription:  This program is used to generate ncs operator from two pdb files.
#Copyright@LBEMSB,IBP
#Author: Kai Zhang
#Last Edit: 2009-2-27

#####**************************************************************************#####

#global setup for output format
set KBold="\x1b\x5b1m"
set KDefault="\x1b\x5b0m"
set KUnderline="\x1b\x5b4m"
set KFlash="\x1b\x5b5m"

#end of global setup

set args = `echo $argv | wc | awk '{print $2}'`
set Proc_name=`echo $0 | awk '{n=split($1,scr,"/");print scr[n];}'`

if (  $args == 0 || $1 == '--help' || $1 == '-h' ) then

	printf "${KBold}Despcription:${KDefault} This program is used to generate ncs operator from two pdb files.\n"
	printf "${KBold}Usage:${KDefault}    $Proc_name <moving pdb file> <fixed pdb file> [ncs operater file]\n"
	printf "${KBold}Example:${KDefault}  $Proc_name mymoving.pdb myfixed.pdb\n"
	printf "          ncs_op_gener mymoving.pdb myfixed.pdb moving_fixed_ncs.o\n"
	exit(1)
endif

if( ! $?CBIN ) then
	echo "Please comfirm that you have installed ""'"ccp4"'"" package!"
	exit(1)
endif

set moving_pdb_file=${1}
set fixed_pdb_file=${2}

set e_name1=`echo $1 | awk '{n=split($1,scr,".");print toupper(scr[n]);}'`
set e_name2=`echo $2 | awk '{n=split($1,scr,".");print toupper(scr[n]);}'`

if ( ${#argv} == 2 ) then

	if ( $e_name1 == "PDB" ) then

		set moving_file_len=`echo $moving_pdb_file |wc|awk '{print$3}'`
		@ moving_file_len=$moving_file_len - 5
		set moving_pdb_file_cut=`echo $moving_pdb_file |cut -c 1-$moving_file_len`

	else
		set moving_pdb_file_cut="$moving_pdb_file"
	endif
	
	if ( $e_name2 == "PDB" ) then

		set fixed_file_len=`echo $fixed_pdb_file |wc|awk '{print$3}'`
		@ fixed_file_len=$fixed_file_len - 5
		set fixed_pdb_file_cut=`echo $fixed_pdb_file |cut -c 1-$fixed_file_len`

	else
		set fixed_pdb_file_cut="$fixed_pdb_file"
	endif
	
	set output_o_file="$moving_pdb_file_cut"_"$fixed_pdb_file_cut".o
endif

if( ${#argv} >= 3 ) then

	set output_o_file=$3

endif

$CBIN/superpose $1 $2 | grep -A 3 "        Rx         Ry    " | gawk '{a[NR]=$1;b[NR]=$2;c[NR]=$3;d[NR]=$4}END{printf(".ncs_symmetry_operators 	 r 	 12 	 (3F11.4) \n%11.4f%11.4f%11.4f\n%11.4f%11.4f%11.4f\n%11.4f%11.4f%11.4f\n%11.4f%11.4f%11.4f\n",a[2],a[3],a[4],b[2],b[3],b[4],c[2],c[3],c[4],d[2],d[3],d[4])}'|tee $output_o_file

#end of the program
