#! /usr/bin/gawk -f
# Last edited on 2008-02-04 18:24:39 by stolfi

BEGIN {
  usage = "$0 < INDEXFILE";
  abort = -1;

  # Reads a file with image caption entries in the folllowing format
  #
  #   IMAGEDIRECTORY
  #   + BLA BLA {INDEX KEY} BLA BLA {INDEX KEY}
  #   + ....
  #   + Photo taken {by AUTHOR}
  #
  # Writes each group of "+" lines to the file "p.comments" in the 
  # corresponding IMAGEDIRECTORY.  Ignores blank lines and lines
  # that begin with "#".

  newfile = "";
  oldfile = "";
}

(abort >= 0) { exit abort; }

/^[ ]*([#]|$)/ {
  next;
}

/^[+][ ]/ {
  if (newfile == "") { data_error(("missing image directory line")); }
  lin = substr($0, 3);
  print lin >> newfile;
  next;
}

/^[a-zA-Z][-_\/A-Za-z0-9]*[A-Za-z0-9] *$/ {
  if (newfile != "") { finish_file(newfile, oldfile); }
  curdir = $1;
  n = length(curdir); 
  if (substr(curdir,n,1) == "/") { curdir = substr(curdir,1,n-1); }
  oldfile = (curdir "/p.comments");
  printf "%s\n", oldfile >> "/dev/stderr";
  newfile = (oldfile "~@~");
  status = system(("/bin/rm -f " newfile));
  status = system(("/bin/touch " newfile));
  if (status != 0) { data_error(("cannot touch " newfile)); }
  next;
}

END {
  if (abort >= 0) { exit abort; }
  if (newfile != "") { finish_file(newfile, oldfile); }
}

function finish_file(newf, oldf,   status)
{
  close(newf);
  if (system(("cmp -s " oldf " " newf)) == 0) 
    { printf "file %s not changed, retaining old copy\n", oldf >> "/dev/stderr"; }
  else
    { status = system(("/bin/mv " oldf " " oldf "~"));
      if (status != 0) { data_error(("cannot backupify " oldf)); }
      status = system(("/bin/mv " newf " " oldf));
      if (status != 0) { data_error(("could not rename " newf " to " oldf)); }
    }
}

/./ {
  data_error(("bad input line format"));
}

function data_error(msg)
{
  printf "line %d: %s\n", FNR, msg;
  abort = 1;
  exit abort;
}