/*          ͻ
                                                                           
                                                                           
              cmandel = ADVANCED PROGRAM TO MAP THE MANDELBROT SET      
                                                                           
            ͼ
*/                       

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
#include <time.h>
#include <kernel.h>
#include "os.h"
#include "bbc.h"
#include "tools.h"
#include "welcome.h"
#define Mouse 0x1c

const int maxcol = 1280;
const int maxrow = 1023;
const int max_colors = 16;
int CURSOR_X=0,CURSOR_Y=0,col,row,MEM0=0,FLAG=0,Power=2;
int max_iterations = 512;
int max_size = 4;
int LINEWIDTH=1, OPERATOR=0x00, ANGLE, XCENTER, YCENTER;
unsigned long int PATTERN=0xFFFFFFFF;
unsigned char PALETTE[16]={0,1,2,3,4,5,20,7,56,57,58,59,60,61,62,63};
int colors[16]={0,1,3,5,15,4,12,20,60,32,48,33,51,37,54,63};
double Q[1024];
float TXMax,TXMin,TYMax,TYMin;
union LIMIT XMax,YMax,XMin,YMin,Pval,Qval;
char *CONTROL=NULL;
char file_name[9] = "mandel00";


int SPRITES=1;
os_error *error;

/* Module to display Leaf Welcome Screen 28th November 1993 Martin Carradus*/

/***************************************************************************/
/* bbc_mouse() returns mouse keys pressed, 0 if none                       */
/***************************************************************************/
  
int bbc_mouse(void)
{
 _kernel_swi_regs regs;

_kernel_swi(Mouse,&regs,&regs);
return(regs.r[2]);
}

void put_welcome(void)
{
  int j,k,l;
  /* Set colour to red                        */
  bbc_gcol(0,3);
  /* Access bitmap and display each character */
  j=0;
  while(j<7)
    {  
      k=0;
      while(k<21)
        {
         l=0;
         while(l<15)
           {  
             if(welcome[21*j+k].line[l]){
                           bbc_plot(0x45,4*(l+50+30*j),592-8*k);
                           bbc_plot(0x45,4*(l+50+30*j),592-8*k-4);
                           bbc_plot(0x45,4*(l+50+30*j)+2,592-8*k);
                           bbc_plot(0x45,4*(l+50+30*j)+2,592-8*k-4);
                                         }
             l++;
            };
          k++;
        };
      j++;
      pause(250);
     };
}

void take_welcome(colour,tint)
int colour,tint;
{
  int j,k,l;
  /* Set colour and tint                      */
  bbc_tint(2,tint);
  bbc_gcol(0,colour);
  /* Access bitmap and display each character */
  j=0;
  while(j<7)
     {             
      k=0;
      while(k<21)
        {
         l=0;
         while(l<15)
           {  
             if(welcome[21*j+k].line[l]){
                           bbc_plot(0x45,4*(l+50+30*j),592-8*k);
                           bbc_plot(0x45,4*(l+50+30*j),592-8*k-4);
                           bbc_plot(0x45,4*(l+50+30*j)+2,592-8*k);
                           bbc_plot(0x45,4*(l+50+30*j)+2,592-8*k-4);
                                         }
             l++;
            };
          k++;
        };
      j++;
     };
}

void put_leaf(void)
{
  int j,k,l;
  /* Set colour to blue                       */
  bbc_gcol(0,48);
  /* Access bitmap and display each character */
  j=0;
  while(j<4)
     {  
      k=0;
      while(k<20)
        {
         l=0;
         while(l<15)
           {  
             if(leaf[20*j+k].line[l]){
                           bbc_plot(0x45,4*(l+90+30*j),1023-8*k);
                           bbc_plot(0x45,4*(l+90+30*j),1023-8*k-4);
                           bbc_plot(0x45,4*(l+90+30*j)+2,1023-8*k);
                           bbc_plot(0x45,4*(l+90+30*j)+2,1023-8*k-4);
                                         }
             l++;
            };
          k++;
        };
      j++;
      pause(250);
     };
}

void put_mindcraft(void)
{
  int j,k,l;
  /* Set colour to blue                       */
  bbc_gcol(0,48);
  /* Access bitmap and display each character */
  j=0;
  while(j<9)
     {  
      k=0;
      while(k<20)
        {
         l=0;
         while(l<15)
           {  
             if(mindcraft[20*j+k].line[l]){
                           bbc_plot(0x45,4*(l+15+30*j),200-8*k);
                           bbc_plot(0x45,4*(l+15+30*j),200-8*k-4);
                           bbc_plot(0x45,4*(l+15+30*j)+2,200-8*k);
                           bbc_plot(0x45,4*(l+15+30*j)+2,200-8*k-4);
                                         }
             l++;
            };
          k++;
        };
      j++;
      pause(250);
     };                                                    
}

void draw_fern(void)
{   
  int q,k;  
  double x,y,r;
  double xn,yn;
  double xf=50.0,xc=500.0,yf=50.0,yc=300.0;
  bbc_tab(11,24);
  printf("Please press Space Bar or click mouse to continue");

  bbc_gcol(0,12);
  srand(10);
  x=0.5;
  y=0.5;
  k=0;
  do {    
    r=(double)rand()/(double)RAND_MAX;
    q=-1;
    do {
    q++;
       } while (fern[q].p<=r);
  xn=fern[q].a*x+fern[q].b*y+fern[q].e;
  yn=fern[q].c*x+fern[q].d*y+fern[q].f;
  x=xn;y=yn;
  k++;
  if(k>100){bbc_plot(0x45,(int)(x*xf+xc),(int)(y*yf+yc));pause(1);}
    } while (bbc_inkey(0)!=' ' && !bbc_mouse());
}

void logo(void)
{     
  int colour,tint;           
  /* Initialise sceen */
  bbc_mode(15);
  bbc_cls();
  bbc_cursor(0);
  pause(1000);
  /* Write Welcome */
  put_welcome();
  /* Wear Out Welcome  */
  colour=3;
  while(colour>0)
  {
  tint=3;
  while (tint>=0)
    {
      pause(250);                                
      take_welcome(colour,tint);
      tint--;   
    }
   colour--;
  }
  pause(500);     
  bbc_cls();
  /* Write Company Name */
  put_leaf();
  put_mindcraft();
  /* Draw Fractal Fern  */
  draw_fern();
  bbc_cursor(1);
 
}


int skipspace(void)
{char c;
  do {
  c=getc(stdin);
  while(c==' ')c=getc(stdin);
  if(c=='\n')printf("Enter Numeric!\n");
  } while (c=='\n');
  ungetc(c,stdin);
  return(0);
  }

int skipgarb(void)
{char c;
  int i=0;
  c=getc(stdin);
  while(c!='\n'){i++;c=getc(stdin);};
  return(i);
}

int main(void)
{FILE *fsave;
  char *timestr;
  char command[256];
  char a,b,c,red,green,blue;
  union LIMIT num;
  int igarb,i,j,k,x2;
  char yesno[4];

     double P,deltaP, deltaQ, X, Y, Xsquare, Ysquare;
     int ch=0,ch1,color, row, col,error,response,repeat=0x30,start_col;
     /* Introductory Sequence */
     logo();
     timestr=(char *)malloc(26*sizeof(char));
     bbc_mode(15);
     bbc_cursor(0);
     printf("!HyperMand  Martin Carradus 2002\n\nThis program generates Fractal plots caused by observing the behaviour of\ncomputation with complex numbers.\n\nA Complex Number has both a \'real\' and an \'imaginary\' part, and can be\nrepresented as a co-ordinate number pair in a plane (Argand Diagram).\n\nThe method used is to perform a calculation (function) on a complex number,\nthen keep on taking out the complex number so formed and putting it back\ninto the function again (iterating the function).\n\nThe function concerned is to raise the complex number to a certain power,\n(usually two), add a fixed complex number, then keep on repeating the process.\n\nThe starting value for this is zero, but the successive complex numbers\nformed can either remain bounded (converge), or start becoming larger and larger\n(diverge).\n\nAs we vary the complex number that is added on to the power,\nthe behaviour alters.\n\nPress a Key to Continue");bbc_get();cls(0);
printf("So the plot you see on the screen is the complex plane near zero,\nwith the degree of instability of the iteration for each added complex number\nin this plane marked by a colour.\n\nThe black coloured region is where the iteration remains stable.\n\nThe plot takes more time in the black region, as the iteration is performed\nthe maximum number of times.\n\nIt also tends to take more time with higher powers due to the increased amount\nof computation.\n\nAfter or during Plotting, you may halt the process and choose a\nsub area to zoom in on and investigate.\n\nChoose an unused Plot Number to generate the initial Mandelbrot with new Power.\n\nSpite File is called \'!SysSprite\' in the directory 'Sprites' within application.\n\n");
     printf("Do you require a resum of Sprites captured so far? Press Y or N or Q to Quit");
     do {
       a=tolower(bbc_get());
       } while(a!='y' && a!='n' && a!='q');
       if(a=='q')exit(0);
     if(a=='y'){cls(0);j=0;k=3;printf("Sprite   Complete? Power  XMin     YMin     XMax     YMax     Captured\n\n");
       while (file_name[6] < 0x3A)
       {strcpy(command,"<HyperMand$Dir>.Headers.");
              if ((fsave = fopen (strcat(command,file_name),"rb")) != NULL)
              {c=fgetc(fsave);
            for (i=0; i<4; i++)num.c[i]=fgetc(fsave);
            for (i=0; i<4; i++)num.c[i]=fgetc(fsave);
            for (i=0; i<4; i++)num.c[i]=fgetc(fsave);
            x2=num.i;if(x2<1279)strcpy(yesno,"No "); else strcpy(yesno,"Yes");
            for (i=0; i<4; i++)num.c[i]=fgetc(fsave);
    for (i=12; i<16; i++)
        c = fgetc(fsave);
        for (i=0; i<4; i++)num.c[i]=fgetc(fsave);
     SPRITES=num.i;
    for (i=0; i<16; i++)
    {
        red = fgetc(fsave);
        green = fgetc(fsave);
        blue = fgetc(fsave);
        color=red & green<<2 & blue<<4;
    }

    for (i=64; i<72; i++)
        c = fgetc(fsave);
    for (i=0; i<4; i++)
        XMax.c[i] = fgetc(fsave);
    for (i=0; i<4; i++)
        XMin.c[i] = fgetc(fsave);
    for (i=0; i<4; i++)
        YMax.c[i] = fgetc(fsave);
    for (i=0; i<4; i++)
        YMin.c[i] = fgetc(fsave);
    for (i=0; i<4; i++)
        Pval.c[i] = fgetc(fsave);
    for (i=0; i<4; i++)
        Qval.c[i] = fgetc(fsave);
        Power=fgetc(fsave);
        if(Power==' ')Power='2';
        for (i=0; i<21; i++)timestr[i]=fgetc(fsave);
        timestr[i]='\0';
     if(k>29){printf("\n\nMore... Press a Key to Continue");bbc_get();cls(0);
       printf("Sprite   Complete? Power  XMin     YMin     XMax     YMax     Captured\n\n");k=3;}
        printf("mandel%c%c   %s      %c  %8.5f %8.5f %8.5f %8.5f %s\n",file_name[6],file_name[7],yesno,Power,XMin.f,YMin.f,XMax.f,YMax.f,timestr);j++;k++;
                     file_name[7]++;
                     if (file_name[7] >= 0x3A)
                     {
                            file_name[7] = 0x30;
                            file_name[6]++;
                     }
                     fclose(fsave);
              } else break;
           }
     if(j==0)printf("No Sprites Stored. Press a Key to Continue"); else printf("\n\nEnd of List. Press a Key to Continue");
     bbc_get();
       }
     free(timestr);
     cls(0);
     bbc_cursor(1);
     do {bbc_tab(24,0);
     printf("Enter screen number (00 -  99): ");
     file_name[6] = getc(stdin);
     if(file_name[6]!='\n')file_name[7] = getc(stdin);
     if(file_name[7]!='\n')ch=getc(stdin);
     if(!isdigit(file_name[6]) || !isdigit(file_name[7]) || ch!='\n')printf("                        Enter two numerics!");
     ch1=ch;while(ch1!='\n')ch1=getc(stdin);
          } while(!isdigit(file_name[6]) || !isdigit(file_name[7]) || ch!='\n');
     cls(0);bbc_cursor(0);
     error = restore_screen(file_name);

     if (error == 0)
     {   bbc_cursor(0);
          printf("\n\nPress '0' to generate initial Mandelbrot screen");
          printf("\n\nPress '1' to exit:");bbc_cursor(0);
          do {
          response = bbc_get();
          } while(response!='0' && response!='1');
          if (response != '0')
               exit(0);
          else
          {a=file_name[6];b=file_name[7];
            file_name[6]='0';file_name[7]='0';
            while (file_name[6] < 0x3A)
       {strcpy(command,"<HyperMand$Dir>.Headers.");
              if ((fsave = fopen (strcat(command,file_name),"rb")) != NULL)
              {
                     file_name[7]++;
                     if (file_name[7] >= 0x3A)
                     {
                            file_name[7] = 0x30;
                            file_name[6]++;
                     }
                     fclose(fsave);
              } else break;
           }
            if(file_name[6]!=a || file_name[7]!=b)printf("\n\nThe first available Sprite is \'%s\'.",file_name);
            else printf("\n\nChosen Sprite is \'%s\'.",file_name);bbc_cursor(1);
            do {
            printf("\n\nEnter Power (2-5): ");
            skipspace();Power=getc(stdin);if(Power=='\n')ungetc('\n',stdin);igarb=skipgarb();
            if(igarb==0 && Power!='2' && Power!='3' && Power!='4' && Power!='5')printf("\nEnter 2 - 5");
            } while(igarb!=0 || (Power!='2' && Power!='3' && Power!='4' && Power!='5'));
            bbc_cursor(0);
            printf("\n\nA new Plot will now start.\n\nDuring Plotting a Key Press will halt the Plot,\n\nOr the Plot finishes when the Screen is full.\n\nPress a Key to Continue.");bbc_cursor(0);bbc_get();
            /* Starting Values */
if(Power=='5'){XMax.f = (float)1.2;
               XMin.f = (float)-1.2;
               YMax.f = (float)1.2;
               YMin.f = (float)-1.2;
               } else if(Power=='4'){
               XMax.f = (float)1.5;
               XMin.f = (float)-1.5;
               YMax.f = (float)1.3;
               YMin.f = (float)-1.3;
              } else if(Power=='3'){
               XMax.f = (float)1.0;
               XMin.f = (float)-1.0;
               YMax.f = (float)1.55;
               YMin.f = (float)-1.55;
              } else if(Power=='2'){
              XMax.f = (float)1.2;
              XMin.f = (float)-2.0;
               YMax.f = (float)1.2;
               YMin.f = (float)-1.2;
              }
               start_col = 0;
               cls(0);bbc_cursor(0);
          }
     }
     else
     {bbc_cursor(0);
          if (error < 1279)
          {
               start_col = error;
               re_move(file_name);
          }
          else
          {
               start_col = 0;
               move_cursor(0,63,0,0,1279);
               move_cursor(1,63,CURSOR_X,CURSOR_Y,1279);
               XMax.f = TXMax;
               XMin.f = TXMin;
               YMax.f = TYMax;
               YMin.f = TYMin;
               cls(0);bbc_cursor(0);
          }

     }

     while (repeat == '0')
     {
          deltaP = (double)(XMax.f - XMin.f)/(double)(maxcol);
          deltaQ = (double)(YMax.f - YMin.f)/(double)(maxrow);
          Q[0] = YMin.f;
          for (row=1; row<=maxrow; row++)
               Q[row] = Q[row-1] + deltaQ;
          P = XMin.f + start_col * deltaP;
          for (col=start_col; col<maxcol; col++)
          {
               if (~bbc_inkey(0))
               {
                    save_screen(0,0,col,1023,file_name);
                    bbc_tab(12,0);
                    printf("Saved Sprite %s, Press '0' to Zoom In, '1' to End",file_name);
                    do {
                    repeat=bbc_get();
                    } while (repeat!='0' && repeat!='1');
                    bbc_tab(12,0);
                    printf("                                                          ");
                    if(repeat=='1')exit(0); else goto jump;
               }
               for (row=0; row<=maxrow; row++)
               {
                    X = Y = Xsquare = Ysquare = 0.0;
                    color = 1;
                    if(Power=='5'){
                    while ((color<max_iterations) && ((Xsquare +
                    Ysquare) < max_size))
                    {
                         Xsquare = X*X;
                         Ysquare = Y*Y;
                         Y= Y*(5*Xsquare*(Xsquare - Ysquare) + Ysquare*(Ysquare - 5*Xsquare))+ Q[row];
                         X= X*(Xsquare*(Xsquare - 5*Ysquare) + 5*Ysquare*(Ysquare-Xsquare)) + P;
                         color ++;
                    }
                    } else if(Power=='4'){
                    while ((color<max_iterations) && ((Xsquare +
                    Ysquare) < max_size))
                    {
                         Xsquare = X*X;
                         Ysquare = Y*Y;
                         Y= 4*X*Y*(Xsquare-Ysquare)+ Q[row];
                         X= Xsquare*(Xsquare-3*Ysquare)+Ysquare*(Ysquare-3*Xsquare) + P;
                         color ++;
                      }
                    } else if(Power=='3'){
                    while ((color<max_iterations) && ((Xsquare +
                    Ysquare) < max_size))
                    {
                         Xsquare = X*X;
                         Ysquare = Y*Y;
                         Y=Y*(3*Xsquare - Ysquare) + Q[row];
                         X=X*(Xsquare - 3*Ysquare) + P;
                         color ++;
                         }
                    }  else if(Power=='2'){
                    while ((color<max_iterations) && ((Xsquare +
                    Ysquare) < max_size))
                    {
                         Xsquare = X*X;
                         Ysquare = Y*Y;
                         Y = 2*X*Y + Q[row];
                         X = Xsquare - Ysquare + P;
                         color ++;
                        }
                    }
                    plot(col, row, colors[color % max_colors]);
             }
               P += deltaP;
          }
          col--;
          save_screen(0,0,1279,1023,file_name);
          bbc_tab(24,31);
          printf("Sprite %s Saved, Press a Key to Continue",file_name);
          bbc_get();
          bbc_tab(24,31);
          printf("                                              ");
          bbc_cursor(0);
          bbc_tab(24,0);
          printf("Press '0' to run another plot, '1' to quit: ");
          do {
          repeat = bbc_get();
          } while(repeat!='0' && repeat!='1');
          bbc_tab(24,0);
          printf("                                            ");
          if (repeat == '0')
          {
jump:  cls(0);bbc_cursor(0);
            printf("\n\nThis Sprite \'%s\' is to Power %c.",file_name,Power);
            printf("\n\nYou are now required to choose the area you wish to zoom into,\n\nAn angle caret will appear in the lower left hand corner of the screen,\n\nUse the cursor keys to move the caret to the lower left hand corner of interest.\n\nPress Return (Enter), and another angle caret will appear.\n\nMove this caret to the upper right hand corner of the area of interest.\n\nPress Return (Enter) again and a Plot of the indicated area will be made.\n\nHolding down the 'Control' Key whilst pressing cursor keys speeds up the carets.\n\nPressing any key whilst Plotting will halt it.\n\nPress Key to Continue.");bbc_cursor(0);bbc_get();cls(0);bbc_cursor(0);FLAG=1;
            restore_screen(file_name);
            FLAG=0;
            CURSOR_X=0;CURSOR_Y=0;
               move_cursor(0,63,0,0,col);
               move_cursor(1,63,CURSOR_X,CURSOR_Y,col);
               XMax.f = TXMax;
               XMin.f = TXMin;
               YMax.f = TYMax;
               YMin.f = TYMin;
               start_col = 0;
               cls(0);bbc_cursor(0);
          }
     }
 if(CONTROL!=NULL)free(CONTROL);
 exit(0);
}
