#!/bin/sh
: ; exec klone $0 "$@"
; The above line finds the klone executable in the $PATH
;;Skeleton of a typical klone script

(setq args (getopts "USAGE: %0 [options] marker file
checks that file ends with marker (string). Returns a shell status of true if 
yes, flase if no."
    ("-x" () exact-match "marker must be exactly at end. Otherwise a 
terminating newline is tolerated")
    ("-r" () remove "if marker is there, removes it")
    ("-v" () verbose "verbose operation")
))

(if (/= 2 (length args)) (getopts :usage))

(defun main (&aux
    (marker (getn args 0))
    (l (length marker))
    (file (getn args 1))
    (fd (open file))
    fl
  )
  (setq fl
    (catch 'Ok
      (file-position fd (- l) 2)
      (if 
	(= marker (read-chars l fd))
	(throw 'Ok 
	  (verbose? "Marker is found at end of file")
	  (- (get (file-stats file) 'size) l))
	
	(and (not exact-match)
	  (progn (file-position fd -1 2)
	    (= #\newline (read-char fd))
	  )
	  (progn (file-position fd (- (- l) 1) 2)
	    (= marker (read-chars l fd))
	))
	(throw 'Ok 
	  (verbose? "Marker is found at end of file + newline")
	  (- (get (file-stats file) 'size) (+ l 1)))
	
	t (progn
	  (verbose? "Marker not found")
	  ()
      ))
  ))
  (close fd)
  (if (and remove fl)
    (progn
      (verbose? "Removing marker from end of file")
      (file-truncate file fl)
  ))
  (exit (if fl 0 1))
)

(main)

;;; EMACS MODES
;;; Local Variables: ***
;;; mode:lisp ***
;;; End: ***
