/*
             CREATOR: DAn williams
                DATE: Aug 07 2003
         DESCRIPTION: C version of basic code to generate alg for static division
            FILENAME: divconst.c
             STARTED: 
    OPERATING SYSTEM: Linux
1st VERSION FINISHED:



*/


#include <stdio.h>
#include <string.h>
//#include <conio.h>  // for dos
#include <stdlib.h>
#include <math.h>

//global variables

int main(int argc, char** argv)
{
  // local variables
  
 int retcode; 
 int in, bits;
 int j;
 float i, ni, accum;
  
  retcode = 0;
  
  printf("Number to divide by? ");
  scanf("%d", &in);
  printf("precision? ");
  scanf("%d", &bits);  
  
  accum = -1.0 / (float)in;
  i = 1.0;
  j = 1;
  
  while ( j < bits) {
    ni = i / 2.0;
    if ( accum < 0 ) { //neg
        if ( fabs(accum + ni) > fabs(accum + i)){
           printf( "Add dividend to accumulator (dividend /%f)\n", 1/i);
           accum = accum + i;
        } 
     } else {
        if ( fabs(accum - ni) > fabs(accum - i)){
           printf ( "Subtract dividend from accumulator (dividend /%f)\n", 1/i);
           accum = accum - i;
        }
     }
    printf( "Shift dividend right. Shift#%d\n",j);
    j = j + 1;
    i = ni;
 }
    
 if (accum != 0){
    printf( "Final error: %f would require 1/%f th of dividend to be added to accumulator\n", accum, 1/accum );
 } else {
    printf( "no error\n");
 }

  retcode = 0; 
  
  return(retcode);
}

