// 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>
#include <math.h>

#define PORT1 0x3F8
  
void
wait(int ms)
{
  clock_t endwait;
  endwait = clock() + ms;
  while(clock()<endwait) {}
}


int
main(int argc, char *argv[])
{
 puts("RecCOM oshogbo//vx vexillium.org");

 if(argc<0)
 {
   fprintf(stderr, "Error: No input file");
   return 1;
 }

 FILE *pfile = fopen(argv[1], "wb");
 
 if(!pfile)
 {
  fprintf(stderr, "Error: No found file");
  return 2;
 }

 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");

 unsigned char mem;
 unsigned long i=0;
 unsigned char msg[4];
 unsigned long size;
 int get;

 for(i=0; i<3; i++)
 {
  inportb(PORT1+5);
  inportb(PORT1);
 }

 for(i = 0; i < 4; i++)
 {
   get = inportb(PORT1+5); 
   if(get & 1)
    msg[i] = inportb(PORT1);
   else
     i--;
   wait(3);
 }

 if((msg[0]=='o')&&(msg[1]=='s')&&(msg[2]=='v')&&(msg[3]=='x'))
    puts("Connected!");
 else
 {
   printf("Not found header (HEADER GET [%s])", msg);
   return 3;
 }


 int sm;
 i = 0;
 size = 0;
 while(1)
 {
  get = inportb(PORT1+5);
  if(get & 1)
  {
   sm = inportb(PORT1);
   if(sm == 0xff)
     break;	
   else
   {
     size += sm * pow(100, i);
     i++;
   }
  }
  wait(3);
 }

 printf("Start geting file (size %llu)\n", size);
 wait(10);
 i=0;
 float pp;
 int last =0;
 while(1)
 {
    get = inportb(PORT1+5);
    if(get & 1)
    {
     mem = inportb(PORT1);
     fwrite(&mem, 1, 1, pfile);
     i++;
     pp = (float(i)/float(size))*100;

     if(last != (int)pp)
     {
      printf("\rCompleate: %i\%    ", (int)pp);
      last = (int)pp;
     }
     outportb(PORT1, 0x66);
    }
   
    if(i>=size)
    {
      fclose(pfile);
      printf("\rDone!                   ");
      return 0;
    }
  }
}
