/* FixObj.e    Replaces $0d characters out of Pixel3D Pro
	       Wavefront files with $20
	       Also adds 'g' lines which set up grouping data
	       Also checks if file has already been operated on
								  */

ENUM ER_NONE, ER_FILE, ER_MEM, ER_USAGE,ER_BRK, ER_OUT, ER_FIXED

DEF flen, mem:PTR TO CHAR,wmem:PTR TO CHAR, pos:PTR TO CHAR,wpos:PTR TO CHAR
DEF handle=NIL,corrections=0

PROC main()
   WriteF('FixObj 1.1 : Fixes Pixel3DPro-generated Wavefront files\n')
   WriteF('(c) 1993 Danimal\n\n')
   IF StrCmp(arg,'',1) OR StrCmp(arg,'?',2) THEN error(ER_USAGE)
   flen:=FileLength(arg)
   handle:=Open(arg,OLDFILE)
   IF (flen<1) OR (handle=NIL) THEN error(ER_FILE)
   mem:=New(flen+4); wmem:= New(flen+10)
   IF (mem=NIL OR wmem=NIL) THEN error(ER_MEM)
   IF Read(handle,mem,flen)<>flen THEN error(ER_FILE)
   Close(handle); handle:=NIL
   WriteF('Now fixing "\s"\n',arg)
   fix()
   IF corrections=0 THEN error(ER_FIXED)
   handle:=Open(arg,NEWFILE)
   IF handle=NIL THEN error(ER_OUT)
   WriteF('Writing "\s".\n',arg)
   IF Write(handle,wmem,flen)<>flen THEN error(ER_OUT)
   error(ER_NONE)
ENDPROC

PROC error(nr)
   IF handle THEN Close(handle)
   SELECT nr
      CASE ER_NONE;   WriteF('Done.\n')
      CASE ER_FILE;   WriteF('Could not read file "\s"\n',arg)
      CASE ER_MEM;    WriteF('No memory for loading file\n')
      CASE ER_USAGE;  WriteF('USAGE: Wavefix <file>\n')
      CASE ER_BRK;    WriteF('**User Break**\n')
      CASE ER_OUT;    WriteF('Could not write file "\s"\n',arg)
      CASE ER_FIXED;  WriteF('File "\s" appears to be already fixed.\n',arg)
   ENDSELECT
   CleanUp(0)
ENDPROC

PROC fix()
/*	 This procedure makes the actual corrections to the file   */

DEF counter=0,firstf=NIL
   pos:=mem; wpos:=wmem
   IF pos[]<>$67
      wpos[]++:=$67; wpos[]++:=$0a
      flen:=flen+2
      corrections++
   ENDIF
   REPEAT
      IF CtrlC() THEN error(ER_BRK)
      IF (pos[]=$66 AND (firstf=NIL) AND (corrections>0))
	 wpos[]++:=$67; wpos[]++:=$0a
	 firstf:=wpos
	 flen:=flen+2
	 corrections++
      ENDIF
      IF pos[]=$0D
	 pos[]:=$20
	 corrections++
      ENDIF
      IF pos[]=$0a THEN counter++
      wpos[]++:=pos[]++
      IF Mod(counter,50)=0 THEN WriteF('\bLine: \d   ',counter)
   UNTIL (pos-mem)>=flen
   WriteF('\n')
ENDPROC
