#!/bin/bash
if [[ "x$1" == "x-h" ]]
then
  echo "Converts an ATAT structure file (from stdin) to the VASP POSCAR format (stdout)."
  echo "Options:"
  echo "  -old  output old-style POSCAR (no atom label)."
  echo "  -r    do the reverse conversion (VASP -> ATAT)."
  echo "         works for both old- and new-style POSCAR."
  exit 1
fi
if [[ "x$1" == "x-r" ]]
then
  awk 'BEGIN {
    getline;
    getline; scale=$1;
    for (i=1; i<=3; i++) {
      getline; a[i]=scale*$1 " " scale*$2 " " scale*$3;
    }
    getline;
    if (match($0,"[A-Z]")>0) {
      split($0,atomlabel);
      getline;
      ntyp=split($0,atomnum);
    }
    else {
      ntyp=split($0,atomnum);
      for (i=1; i<=ntyp; i++) {atomlabel[i]=sprintf("%c",64+i);}
    }
    l=1;
    for (i=1; i<=ntyp; i++) {
      for (j=1; j<=atomnum[i]; j++) {
        label[l]=atomlabel[i];
	l++;
      }
    }
    l=1;
    getline;
    if (match($0,"^[sS]")>0) {getline;}
    direct=0;
    if (match($0,"^[dD]")>0) {direct=1;}
    for (i=0; i<2; i++) {
      if (i==direct) {
        for (j=1; j<=3; j++) {
	   for (k=1; k<=3; k++) {printf (j==k ? 1 : 0) " ";}
 	   print "";
        }
      }
      else {
        for (j=1; j<=3; j++) {print a[j];}
      }
    }
  }
  {
    if (match($0,"^[dDcC]")>0) {exit;}
    if (direct==1) {
      print $1,$2,$3,label[l];
    }
    else {
      print scale*$1,scale*$2,scale*$3,label[l];
    }
    l++;
  }'
else
  echo title
  echo 1
  cat - | cellcvrt -f > str${$}.tmp
  head -n 3 str${$}.tmp
  tail -n +7 str${$}.tmp | awk '{nb[$4]++} END {for (i in nb) {print i,nb[i]}}' | sort > spec${$}.tmp 
  if [[ "x$1" != "x-old" ]]
  then
    echo `cat spec${$}.tmp | awk '{print $1}'`
  fi
  echo `cat spec${$}.tmp | awk '{print $2}'`
  echo Direct
  tail -n +7 str${$}.tmp | sort -k 4,4 | awk '{print $1,$2,$3}'
  rm str${$}.tmp spec${$}.tmp
fi
