#!/usr/bin/python
import os, sys, tty, time
from select import select

class NotTTYException (Exception): pass
class TerminalFile:
  def __init__ (self,infile):
    if not infile.isatty (): raise NotTTYException ()
    self.file=infile
    #prepare for getch
    self.save_attr=tty.tcgetattr(self.file)
    newattr=self.save_attr[:]
    newattr[3] &= ~tty.ECHO & ~tty.ICANON
    tty.tcsetattr(self.file, tty.TCSANOW, newattr)
  def __del__(self):
    #restoring stdin
    import tty  #required this import here
    tty.tcsetattr(self.file, tty.TCSADRAIN, self.save_attr)
  def getch(self):
    if select([self.file],[],[],0)[0]: c=self.file.read(1)
    else: c = ''
    return c

# A simple text-based stop-watch
# Written by Marc Pickett I of Padelford

# Turn the time into a string
def abuTimeString (totalElap):
  second2 = int (totalElap * 10)
  second = int (second2/10)%60
  minute = int (second2/10)/60 % 60
  hour   = int (second2/10)/3600 % 60
  timestr = ''
  if (hour < 10): timestr = timestr + '0'
  timestr = timestr + str (hour) + ':'
  if (minute < 10): timestr = timestr + '0'
  timestr = timestr + str (minute) + ':'
  if (second < 10): timestr = timestr + '0'
  timestr = timestr + str (second) + '.' + str (second2 % 10)
  return timestr

s = TerminalFile (sys.stdin)
flag = True
baseElap = 0.0
totalElap = 0.0
ersteTime = time.time ()
while flag == True:
  startTime = time.time ()
  # The clock is ticking
  c = s.getch ()
  while (c != ' ') and (c != 'q'):
    c = s.getch ()
    totalElap = baseElap + (time.time () - startTime)
    timestr = 'MZEIT ' + abuTimeString (totalElap)
    sys.stdout.write(timestr + '\r')
    sys.stdout.flush()
    time.sleep (.1)
  baseElap = baseElap + (time.time () - startTime)
  print timestr
  if (c != 'q'):
    c = s.getch ()
    # Paused...
    while (c != ' ') and (c != 'q'):
      c = s.getch ()
      timestr2 = '      TOTAL ' + abuTimeString (time.time () - ersteTime)
      sys.stdout.write(timestr + timestr2 + '\r')
      sys.stdout.flush()
      time.sleep (0.1)
  # Not my most elegant programming...
  else:
    timestr2 = '      TOTAL ' + abuTimeString (time.time () - ersteTime)
    
  print timestr + timestr2
  if (c == 'q'): flag = False
print 'Seconds Elapsed = ' + str ((int (totalElap * 10))/10.0)
