#include <sys/stat.h>
#include <sys/param.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

/* Takes a filename (pathname) as a command line argument and prints
   the distance between the given file's inode and the inode of the
   directory that file appears in. (Distance is the absolute value of
   the difference in inode numbers.)  
   -Max Hailperin <max@gac.edu> 1999-09-01 */

int main(int argc, char *argv[]){
  __ino_t inode;
  struct stat sbuf;
  char pathname[MAXPATHLEN];
  
  if(argc != 2){
    fprintf(stderr, "Usage: %s pathname\n", argv[0]);
    exit(1);
  }

  if(realpath(argv[1], pathname) == 0){
    perror(pathname);
    exit(1);
  }

  if(stat(pathname, &sbuf) < 0){
    perror(pathname);
    exit(1);
  }

  inode = sbuf.st_ino;

  *strrchr(pathname, '/') = '\0';
  if(pathname[0] == '\0'){
    pathname[0] = '/';
    pathname[1] = '\0';
  }

  if(stat(pathname, &sbuf) < 0){
    perror(pathname);
    exit(1);
  }

  printf("%lu\n",
         inode < sbuf.st_ino ? sbuf.st_ino - inode : inode - sbuf.st_ino);

  return 0;
}