// Write by oshogbo//vx
// Team Web: vexillium.org
// Home Web: oshogbo.vexillium.org
// oshogbo@vexillium.prg
// Przyda sie temu jeszcze troche optymalizacji
// ogolnie robcie co chcecie ale pamietajcie o pierwszym autorze ;D

#include <stdio.h>
#include <dos.h>
#include <time.h>

#define PORT1 0x3F8
  
void
wait(int ms)
{
  clock_t endwait;
  endwait = clock() + ms;
  while(clock()<endwait) {}
}


int
main(int argc, char *argv[])
{
 puts("SendCOM oshogbo//vx vexillium.org");
 char msg[] = "osvx";

 if(argc<0)
 {
   fprintf(stderr, "Error: No input file");
   return 1;
 }

 FILE *pfile = fopen(argv[1], "rb");
 
 if(!pfile)
 {
  fprintf(stderr, "Error: No foud file");
  return 2;
 }
 unsigned long size;
 fseek(pfile, 0, SEEK_END);
 size = ftell(pfile);
 fseek(pfile, 0, SEEK_SET);

 printf("File name: %s\nFile size: %llu\n", argv[1], size);

 unsigned char mem[256];
 unsigned long i=0;
 printf("Setting COM1\n");
 outportb(PORT1 + 3 , 0x80);
 outportb(PORT1 + 0 , 0x03);  
 outportb(PORT1 + 1 , 0x00);
 outportb(PORT1 + 3 , 0x03); 
 outportb(PORT1 + 2 , 0xC7);
 outportb(PORT1 + 4 , 0x0B);
 printf("COM1 ready\n");

 puts("Sending header");
 for(i = 0; i < 4; i++)
 {
   outportb(PORT1, msg[i]);
   wait(25);
 }

 puts("Sending size");

 unsigned long size2 = size;
 unsigned int r = 0;
 while(size2 != 0)
 {
  r = size2 % 100;
  size2 = size2 / 100;
  outportb(PORT1, r);
  wait(25);
 }

 outportb(PORT1, 0xff);
 wait(5);

 puts("Sending Data");

 i=0;
 int get, x;
 float pp;
 int last =0;
 while(1)
 {
  fread(mem, sizeof(mem), 1, pfile);
  for(int a = 0; a<sizeof(mem); a++)
  {
     while(1)
     {
      get = inportb(PORT1 + 5);
      if((get & 1)||(i ==0))
      {
	x = inportb(PORT1);
	if((x == 0x66)||(i ==0))
	{
	  i++;
          outportb(PORT1, mem[a]);
	  x = 0;
          pp = (float(i)/float(size))*100;

          if(last != (int)pp)
          {
		  printf("\rCompleate: %i\%    ", (int)pp);
		  last = (int)pp;
	  }
	  break;
	}
      }
     }
     if(i>=size)
     {
      fclose(pfile);
      puts("Done!");
      return 0;
     }
  }
 }
}
